Merge branch 'MDL-58454-master' of git://github.com/junpataleta/moodle
[moodle.git] / lib / externallib.php
blob17961911a64069667f8f639808964711518ab6a0
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 $responsetype = gettype($response);
401 $debuginfo = 'Invalid external api response: the value is "' . $response .
402 '" of PHP type "' . $responsetype . '", the server was expecting "' . $description->type . '" type';
403 try {
404 return validate_param($response, $description->type, $description->allownull, $debuginfo);
405 } catch (invalid_parameter_exception $e) {
406 //proper exception name, to be recursively catched to build the path to the faulty attribut
407 throw new invalid_response_exception($e->debuginfo);
410 } else if ($description instanceof external_single_structure) {
411 if (!is_array($response) && !is_object($response)) {
412 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
413 print_r($response, true) . '\'');
416 // Cast objects into arrays.
417 if (is_object($response)) {
418 $response = (array) $response;
421 $result = array();
422 foreach ($description->keys as $key=>$subdesc) {
423 if (!array_key_exists($key, $response)) {
424 if ($subdesc->required == VALUE_REQUIRED) {
425 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
427 if ($subdesc instanceof external_value) {
428 if ($subdesc->required == VALUE_DEFAULT) {
429 try {
430 $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
431 } catch (invalid_response_exception $e) {
432 //build the path to the faulty attribut
433 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
437 } else {
438 try {
439 $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
440 } catch (invalid_response_exception $e) {
441 //build the path to the faulty attribut
442 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
445 unset($response[$key]);
448 return $result;
450 } else if ($description instanceof external_multiple_structure) {
451 if (!is_array($response)) {
452 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
453 print_r($response, true) . '\'');
455 $result = array();
456 foreach ($response as $param) {
457 $result[] = static::clean_returnvalue($description->content, $param);
459 return $result;
461 } else {
462 throw new invalid_response_exception('Invalid external api response description');
467 * Makes sure user may execute functions in this context.
469 * @param stdClass $context
470 * @since Moodle 2.0
472 public static function validate_context($context) {
473 global $CFG, $PAGE;
475 if (empty($context)) {
476 throw new invalid_parameter_exception('Context does not exist');
478 if (empty(self::$contextrestriction)) {
479 self::$contextrestriction = context_system::instance();
481 $rcontext = self::$contextrestriction;
483 if ($rcontext->contextlevel == $context->contextlevel) {
484 if ($rcontext->id != $context->id) {
485 throw new restricted_context_exception();
487 } else if ($rcontext->contextlevel > $context->contextlevel) {
488 throw new restricted_context_exception();
489 } else {
490 $parents = $context->get_parent_context_ids();
491 if (!in_array($rcontext->id, $parents)) {
492 throw new restricted_context_exception();
496 $PAGE->reset_theme_and_output();
497 list($unused, $course, $cm) = get_context_info_array($context->id);
498 require_login($course, false, $cm, false, true);
499 $PAGE->set_context($context);
503 * Get context from passed parameters.
504 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
505 * For example, the context level can be "course" and instanceid can be courseid.
507 * See context_helper::get_all_levels() for a list of valid context levels.
509 * @param array $param
510 * @since Moodle 2.6
511 * @throws invalid_parameter_exception
512 * @return context
514 protected static function get_context_from_params($param) {
515 $levels = context_helper::get_all_levels();
516 if (!empty($param['contextid'])) {
517 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
518 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
519 $contextlevel = "context_".$param['contextlevel'];
520 if (!array_search($contextlevel, $levels)) {
521 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
523 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
524 } else {
525 // No valid context info was found.
526 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
531 * Returns a prepared structure to use a context parameters.
532 * @return external_single_structure
534 protected static function get_context_parameters() {
535 $id = new external_value(
536 PARAM_INT,
537 'Context ID. Either use this value, or level and instanceid.',
538 VALUE_DEFAULT,
541 $level = new external_value(
542 PARAM_ALPHA,
543 'Context level. To be used with instanceid.',
544 VALUE_DEFAULT,
547 $instanceid = new external_value(
548 PARAM_INT,
549 'Context instance ID. To be used with level',
550 VALUE_DEFAULT,
553 return new external_single_structure(array(
554 'contextid' => $id,
555 'contextlevel' => $level,
556 'instanceid' => $instanceid,
563 * Common ancestor of all parameter description classes
565 * @package core_webservice
566 * @copyright 2009 Petr Skodak
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
568 * @since Moodle 2.0
570 abstract class external_description {
571 /** @var string Description of element */
572 public $desc;
574 /** @var bool Element value required, null not allowed */
575 public $required;
577 /** @var mixed Default value */
578 public $default;
581 * Contructor
583 * @param string $desc
584 * @param bool $required
585 * @param mixed $default
586 * @since Moodle 2.0
588 public function __construct($desc, $required, $default) {
589 $this->desc = $desc;
590 $this->required = $required;
591 $this->default = $default;
596 * Scalar value description class
598 * @package core_webservice
599 * @copyright 2009 Petr Skodak
600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
601 * @since Moodle 2.0
603 class external_value extends external_description {
605 /** @var mixed Value type PARAM_XX */
606 public $type;
608 /** @var bool Allow null values */
609 public $allownull;
612 * Constructor
614 * @param mixed $type
615 * @param string $desc
616 * @param bool $required
617 * @param mixed $default
618 * @param bool $allownull
619 * @since Moodle 2.0
621 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
622 $default=null, $allownull=NULL_ALLOWED) {
623 parent::__construct($desc, $required, $default);
624 $this->type = $type;
625 $this->allownull = $allownull;
630 * Associative array description class
632 * @package core_webservice
633 * @copyright 2009 Petr Skodak
634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
635 * @since Moodle 2.0
637 class external_single_structure extends external_description {
639 /** @var array Description of array keys key=>external_description */
640 public $keys;
643 * Constructor
645 * @param array $keys
646 * @param string $desc
647 * @param bool $required
648 * @param array $default
649 * @since Moodle 2.0
651 public function __construct(array $keys, $desc='',
652 $required=VALUE_REQUIRED, $default=null) {
653 parent::__construct($desc, $required, $default);
654 $this->keys = $keys;
659 * Bulk array description class.
661 * @package core_webservice
662 * @copyright 2009 Petr Skodak
663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
664 * @since Moodle 2.0
666 class external_multiple_structure extends external_description {
668 /** @var external_description content */
669 public $content;
672 * Constructor
674 * @param external_description $content
675 * @param string $desc
676 * @param bool $required
677 * @param array $default
678 * @since Moodle 2.0
680 public function __construct(external_description $content, $desc='',
681 $required=VALUE_REQUIRED, $default=null) {
682 parent::__construct($desc, $required, $default);
683 $this->content = $content;
688 * Description of top level - PHP function parameters.
690 * @package core_webservice
691 * @copyright 2009 Petr Skodak
692 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 * @since Moodle 2.0
695 class external_function_parameters extends external_single_structure {
698 * Constructor - does extra checking to prevent top level optional parameters.
700 * @param array $keys
701 * @param string $desc
702 * @param bool $required
703 * @param array $default
705 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
706 global $CFG;
708 if ($CFG->debugdeveloper) {
709 foreach ($keys as $key => $value) {
710 if ($value instanceof external_value) {
711 if ($value->required == VALUE_OPTIONAL) {
712 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
713 break;
718 parent::__construct($keys, $desc, $required, $default);
723 * Generate a token
725 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
726 * @param stdClass|int $serviceorid service linked to the token
727 * @param int $userid user linked to the token
728 * @param stdClass|int $contextorid
729 * @param int $validuntil date when the token expired
730 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
731 * @return string generated token
732 * @author 2010 Jamie Pratt
733 * @since Moodle 2.0
735 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
736 global $DB, $USER;
737 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
738 $numtries = 0;
739 do {
740 $numtries ++;
741 $generatedtoken = md5(uniqid(rand(),1));
742 if ($numtries > 5){
743 throw new moodle_exception('tokengenerationfailed');
745 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
746 $newtoken = new stdClass();
747 $newtoken->token = $generatedtoken;
748 if (!is_object($serviceorid)){
749 $service = $DB->get_record('external_services', array('id' => $serviceorid));
750 } else {
751 $service = $serviceorid;
753 if (!is_object($contextorid)){
754 $context = context::instance_by_id($contextorid, MUST_EXIST);
755 } else {
756 $context = $contextorid;
758 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
759 $newtoken->externalserviceid = $service->id;
760 } else {
761 throw new moodle_exception('nocapabilitytousethisservice');
763 $newtoken->tokentype = $tokentype;
764 $newtoken->userid = $userid;
765 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
766 $newtoken->sid = session_id();
769 $newtoken->contextid = $context->id;
770 $newtoken->creatorid = $USER->id;
771 $newtoken->timecreated = time();
772 $newtoken->validuntil = $validuntil;
773 if (!empty($iprestriction)) {
774 $newtoken->iprestriction = $iprestriction;
776 $newtoken->privatetoken = null;
777 $DB->insert_record('external_tokens', $newtoken);
778 return $newtoken->token;
782 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
783 * with the Moodle server through web services. The token is linked to the current session for the current page request.
784 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
785 * returned token will be somehow passed into the client app being embedded in the page.
787 * @param string $servicename name of the web service. Service name as defined in db/services.php
788 * @param int $context context within which the web service can operate.
789 * @return int returns token id.
790 * @since Moodle 2.0
792 function external_create_service_token($servicename, $context){
793 global $USER, $DB;
794 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
795 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
799 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
801 * @param string $component name of component (moodle, mod_assignment, etc.)
803 function external_delete_descriptions($component) {
804 global $DB;
806 $params = array($component);
808 $DB->delete_records_select('external_tokens',
809 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
810 $DB->delete_records_select('external_services_users',
811 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
812 $DB->delete_records_select('external_services_functions',
813 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
814 $DB->delete_records('external_services', array('component'=>$component));
815 $DB->delete_records('external_functions', array('component'=>$component));
819 * Standard Moodle web service warnings
821 * @package core_webservice
822 * @copyright 2012 Jerome Mouneyrac
823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
824 * @since Moodle 2.3
826 class external_warnings extends external_multiple_structure {
829 * Constructor
831 * @since Moodle 2.3
833 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
834 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
836 parent::__construct(
837 new external_single_structure(
838 array(
839 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
840 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
841 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
842 'message' => new external_value(PARAM_TEXT,
843 'untranslated english message to explain the warning')
844 ), 'warning'),
845 'list of warnings', VALUE_OPTIONAL);
850 * A pre-filled external_value class for text format.
852 * Default is FORMAT_HTML
853 * This should be used all the time in external xxx_params()/xxx_returns functions
854 * as it is the standard way to implement text format param/return values.
856 * @package core_webservice
857 * @copyright 2012 Jerome Mouneyrac
858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
859 * @since Moodle 2.3
861 class external_format_value extends external_value {
864 * Constructor
866 * @param string $textfieldname Name of the text field
867 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
868 * @param int $default Default value.
869 * @since Moodle 2.3
871 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
873 if ($default == null && $required == VALUE_DEFAULT) {
874 $default = FORMAT_HTML;
877 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
878 . FORMAT_MOODLE . ' = MOODLE, '
879 . FORMAT_PLAIN . ' = PLAIN or '
880 . FORMAT_MARKDOWN . ' = MARKDOWN)';
882 parent::__construct(PARAM_INT, $desc, $required, $default);
887 * Validate text field format against known FORMAT_XXX
889 * @param array $format the format to validate
890 * @return the validated format
891 * @throws coding_exception
892 * @since Moodle 2.3
894 function external_validate_format($format) {
895 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
896 if (!in_array($format, $allowedformats)) {
897 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
898 'The format with value=' . $format . ' is not supported by this Moodle site');
900 return $format;
904 * Format the string to be returned properly as requested by the either the web service server,
905 * either by an internally call.
906 * The caller can change the format (raw) with the external_settings singleton
907 * All web service servers must set this singleton when parsing the $_GET and $_POST.
909 * <pre>
910 * Options are the same that in {@link format_string()} with some changes:
911 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
912 * </pre>
914 * @param string $str The string to be filtered. Should be plain text, expect
915 * possibly for multilang tags.
916 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
917 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
918 * @param array $options options array/object or courseid
919 * @return string text
920 * @since Moodle 3.0
922 function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
924 // Get settings (singleton).
925 $settings = external_settings::get_instance();
926 if (empty($contextorid)) {
927 throw new coding_exception('contextid is required');
930 if (!$settings->get_raw()) {
931 if (is_object($contextorid) && is_a($contextorid, 'context')) {
932 $context = $contextorid;
933 } else {
934 $context = context::instance_by_id($contextorid);
936 $options['context'] = $context;
937 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
938 $str = format_string($str, $striplinks, $options);
941 return $str;
945 * Format the text to be returned properly as requested by the either the web service server,
946 * either by an internally call.
947 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
948 * All web service servers must set this singleton when parsing the $_GET and $_POST.
950 * <pre>
951 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
952 * trusted : If true the string won't be cleaned. Default false.
953 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
954 * nocache : If true the string will not be cached and will be formatted every call. Default false.
955 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
956 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
957 * Default changed because div tags are not commonly needed.
958 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
959 * context : Not used! Using contextid parameter instead.
960 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
961 * returned. Default false.
962 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
963 * format_text) true. Default changed id attributes are commonly needed.
964 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
965 * </pre>
967 * @param string $text The content that may contain ULRs in need of rewriting.
968 * @param int $textformat The text format.
969 * @param context|int $contextorid This parameter and the next two identify the file area to use.
970 * @param string $component
971 * @param string $filearea helps identify the file area.
972 * @param int $itemid helps identify the file area.
973 * @param object/array $options text formatting options
974 * @return array text + textformat
975 * @since Moodle 2.3
976 * @since Moodle 3.2 component, filearea and itemid are optional parameters
978 function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
979 $options = null) {
980 global $CFG;
982 // Get settings (singleton).
983 $settings = external_settings::get_instance();
985 if (is_object($contextorid) && is_a($contextorid, 'context')) {
986 $context = $contextorid;
987 $contextid = $context->id;
988 } else {
989 $context = null;
990 $contextid = $contextorid;
993 if ($component and $filearea and $settings->get_fileurl()) {
994 require_once($CFG->libdir . "/filelib.php");
995 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
998 // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
999 // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
1001 if (!$settings->get_raw()) {
1002 $options = (array)$options;
1004 // If context is passed in options, check that is the same to show a debug message.
1005 if (isset($options['context'])) {
1006 if ((is_object($options['context']) && $options['context']->id != $contextid)
1007 || (!is_object($options['context']) && $options['context'] != $contextid)) {
1008 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
1009 Using $contextid parameter...', DEBUG_DEVELOPER);
1013 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
1014 $options['para'] = isset($options['para']) ? $options['para'] : false;
1015 $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
1016 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
1018 $text = format_text($text, $textformat, $options);
1019 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
1022 return array($text, $textformat);
1026 * Generate or return an existing token for the current authenticated user.
1027 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
1029 * @param stdClass $service external service object
1030 * @return stdClass token object
1031 * @since Moodle 3.2
1032 * @throws moodle_exception
1034 function external_generate_token_for_current_user($service) {
1035 global $DB, $USER, $CFG;
1037 core_user::require_active_user($USER, true, true);
1039 // Check if there is any required system capability.
1040 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1041 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1044 // Specific checks related to user restricted service.
1045 if ($service->restrictedusers) {
1046 $authoriseduser = $DB->get_record('external_services_users',
1047 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1049 if (empty($authoriseduser)) {
1050 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1053 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1054 throw new moodle_exception('invalidtimedtoken', 'webservice');
1057 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1058 throw new moodle_exception('invalidiptoken', 'webservice');
1062 // Check if a token has already been created for this user and this service.
1063 $conditions = array(
1064 'userid' => $USER->id,
1065 'externalserviceid' => $service->id,
1066 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1068 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1070 // A bit of sanity checks.
1071 foreach ($tokens as $key => $token) {
1073 // Checks related to a specific token. (script execution continue).
1074 $unsettoken = false;
1075 // If sid is set then there must be a valid associated session no matter the token type.
1076 if (!empty($token->sid)) {
1077 if (!\core\session\manager::session_exists($token->sid)) {
1078 // This token will never be valid anymore, delete it.
1079 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1080 $unsettoken = true;
1084 // Remove token is not valid anymore.
1085 if (!empty($token->validuntil) and $token->validuntil < time()) {
1086 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1087 $unsettoken = true;
1090 // Remove token if its ip not in whitelist.
1091 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1092 $unsettoken = true;
1095 if ($unsettoken) {
1096 unset($tokens[$key]);
1100 // If some valid tokens exist then use the most recent.
1101 if (count($tokens) > 0) {
1102 $token = array_pop($tokens);
1103 } else {
1104 $context = context_system::instance();
1105 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1107 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1108 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1110 // Create a new token.
1111 $token = new stdClass;
1112 $token->token = md5(uniqid(rand(), 1));
1113 $token->userid = $USER->id;
1114 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1115 $token->contextid = context_system::instance()->id;
1116 $token->creatorid = $USER->id;
1117 $token->timecreated = time();
1118 $token->externalserviceid = $service->id;
1119 // By default tokens are valid for 12 weeks.
1120 $token->validuntil = $token->timecreated + $CFG->tokenduration;
1121 $token->iprestriction = null;
1122 $token->sid = null;
1123 $token->lastaccess = null;
1124 // Generate the private token, it must be transmitted only via https.
1125 $token->privatetoken = random_string(64);
1126 $token->id = $DB->insert_record('external_tokens', $token);
1128 $eventtoken = clone $token;
1129 $eventtoken->privatetoken = null;
1130 $params = array(
1131 'objectid' => $eventtoken->id,
1132 'relateduserid' => $USER->id,
1133 'other' => array(
1134 'auto' => true
1137 $event = \core\event\webservice_token_created::create($params);
1138 $event->add_record_snapshot('external_tokens', $eventtoken);
1139 $event->trigger();
1140 } else {
1141 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1144 return $token;
1148 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1150 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1151 * In order to protect the privatetoken, we remove it from the event params.
1153 * @param stdClass $token token object
1154 * @since Moodle 3.2
1156 function external_log_token_request($token) {
1157 global $DB;
1159 $token->privatetoken = null;
1161 // Log token access.
1162 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1164 $params = array(
1165 'objectid' => $token->id,
1167 $event = \core\event\webservice_token_sent::create($params);
1168 $event->add_record_snapshot('external_tokens', $token);
1169 $event->trigger();
1173 * Singleton to handle the external settings.
1175 * We use singleton to encapsulate the "logic"
1177 * @package core_webservice
1178 * @copyright 2012 Jerome Mouneyrac
1179 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1180 * @since Moodle 2.3
1182 class external_settings {
1184 /** @var object the singleton instance */
1185 public static $instance = null;
1187 /** @var boolean Should the external function return raw text or formatted */
1188 private $raw = false;
1190 /** @var boolean Should the external function filter the text */
1191 private $filter = false;
1193 /** @var boolean Should the external function rewrite plugin file url */
1194 private $fileurl = true;
1196 /** @var string In which file should the urls be rewritten */
1197 private $file = 'webservice/pluginfile.php';
1199 /** @var string The session lang */
1200 private $lang = '';
1203 * Constructor - protected - can not be instanciated
1205 protected function __construct() {
1206 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
1207 // For normal pages, the default should match the default for format_text.
1208 $this->filter = true;
1209 // Use pluginfile.php for web requests.
1210 $this->file = 'pluginfile.php';
1215 * Clone - private - can not be cloned
1217 private final function __clone() {
1221 * Return only one instance
1223 * @return \external_settings
1225 public static function get_instance() {
1226 if (self::$instance === null) {
1227 self::$instance = new external_settings;
1230 return self::$instance;
1234 * Set raw
1236 * @param boolean $raw
1238 public function set_raw($raw) {
1239 $this->raw = $raw;
1243 * Get raw
1245 * @return boolean
1247 public function get_raw() {
1248 return $this->raw;
1252 * Set filter
1254 * @param boolean $filter
1256 public function set_filter($filter) {
1257 $this->filter = $filter;
1261 * Get filter
1263 * @return boolean
1265 public function get_filter() {
1266 return $this->filter;
1270 * Set fileurl
1272 * @param boolean $fileurl
1274 public function set_fileurl($fileurl) {
1275 $this->fileurl = $fileurl;
1279 * Get fileurl
1281 * @return boolean
1283 public function get_fileurl() {
1284 return $this->fileurl;
1288 * Set file
1290 * @param string $file
1292 public function set_file($file) {
1293 $this->file = $file;
1297 * Get file
1299 * @return string
1301 public function get_file() {
1302 return $this->file;
1306 * Set lang
1308 * @param string $lang
1310 public function set_lang($lang) {
1311 $this->lang = $lang;
1315 * Get lang
1317 * @return string
1319 public function get_lang() {
1320 return $this->lang;
1325 * Utility functions for the external API.
1327 * @package core_webservice
1328 * @copyright 2015 Juan Leyva
1329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 * @since Moodle 3.0
1332 class external_util {
1335 * Validate a list of courses, returning the complete course objects for valid courses.
1337 * @param array $courseids A list of course ids
1338 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1339 * @param bool $addcontext True if the returned course object should include the full context object.
1340 * @return array An array of courses and the validation warnings
1342 public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
1343 // Delete duplicates.
1344 $courseids = array_unique($courseids);
1345 $warnings = array();
1347 // Remove courses which are not even requested.
1348 $courses = array_intersect_key($courses, array_flip($courseids));
1350 foreach ($courseids as $cid) {
1351 // Check the user can function in this context.
1352 try {
1353 $context = context_course::instance($cid);
1354 external_api::validate_context($context);
1356 if (!isset($courses[$cid])) {
1357 $courses[$cid] = get_course($cid);
1359 if ($addcontext) {
1360 $courses[$cid]->context = $context;
1362 } catch (Exception $e) {
1363 unset($courses[$cid]);
1364 $warnings[] = array(
1365 'item' => 'course',
1366 'itemid' => $cid,
1367 'warningcode' => '1',
1368 'message' => 'No access rights in course context'
1373 return array($courses, $warnings);
1377 * Returns all area files (optionally limited by itemid).
1379 * @param int $contextid context ID
1380 * @param string $component component
1381 * @param string $filearea file area
1382 * @param int $itemid item ID or all files if not specified
1383 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1384 * @return array of files, compatible with the external_files structure.
1385 * @since Moodle 3.2
1387 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1388 $files = array();
1389 $fs = get_file_storage();
1391 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1392 foreach ($areafiles as $areafile) {
1393 $file = array();
1394 $file['filename'] = $areafile->get_filename();
1395 $file['filepath'] = $areafile->get_filepath();
1396 $file['mimetype'] = $areafile->get_mimetype();
1397 $file['filesize'] = $areafile->get_filesize();
1398 $file['timemodified'] = $areafile->get_timemodified();
1399 $file['isexternalfile'] = $areafile->is_external_file();
1400 if ($file['isexternalfile']) {
1401 $file['repositorytype'] = $areafile->get_repository_type();
1403 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1404 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1405 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1406 $files[] = $file;
1409 return $files;
1414 * External structure representing a set of files.
1416 * @package core_webservice
1417 * @copyright 2016 Juan Leyva
1418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1419 * @since Moodle 3.2
1421 class external_files extends external_multiple_structure {
1424 * Constructor
1425 * @param string $desc Description for the multiple structure.
1426 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1428 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1430 parent::__construct(
1431 new external_single_structure(
1432 array(
1433 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1434 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1435 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1436 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1437 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1438 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1439 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1440 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
1442 'File.'
1444 $desc,
1445 $required
1450 * Return the properties ready to be used by an exporter.
1452 * @return array properties
1453 * @since Moodle 3.3
1455 public static function get_properties_for_exporter() {
1456 return [
1457 'filename' => array(
1458 'type' => PARAM_FILE,
1459 'description' => 'File name.',
1460 'optional' => true,
1461 'null' => NULL_NOT_ALLOWED,
1463 'filepath' => array(
1464 'type' => PARAM_PATH,
1465 'description' => 'File path.',
1466 'optional' => true,
1467 'null' => NULL_NOT_ALLOWED,
1469 'filesize' => array(
1470 'type' => PARAM_INT,
1471 'description' => 'File size.',
1472 'optional' => true,
1473 'null' => NULL_NOT_ALLOWED,
1475 'fileurl' => array(
1476 'type' => PARAM_URL,
1477 'description' => 'Downloadable file url.',
1478 'optional' => true,
1479 'null' => NULL_NOT_ALLOWED,
1481 'timemodified' => array(
1482 'type' => PARAM_INT,
1483 'description' => 'Time modified.',
1484 'optional' => true,
1485 'null' => NULL_NOT_ALLOWED,
1487 'mimetype' => array(
1488 'type' => PARAM_RAW,
1489 'description' => 'File mime type.',
1490 'optional' => true,
1491 'null' => NULL_NOT_ALLOWED,
1493 'isexternalfile' => array(
1494 'type' => PARAM_BOOL,
1495 'description' => 'Whether is an external file.',
1496 'optional' => true,
1497 'null' => NULL_NOT_ALLOWED,
1499 'repositorytype' => array(
1500 'type' => PARAM_PLUGIN,
1501 'description' => 'The repository type for the external files.',
1502 'optional' => true,
1503 'null' => NULL_ALLOWED,