Merge branch 'MDL-68854-master' of git://github.com/vmdef/moodle
[moodle.git] / lib / externallib.php
blob002a99d2deec59ed5127c0bba9d27af0b49d603f
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;
164 if (isset($functions[$function->name]['readonlysession'])) {
165 $function->readonlysession = $functions[$function->name]['readonlysession'];
166 } else {
167 $function->readonlysession = false;
171 return $function;
175 * Call an external function validating all params/returns correctly.
177 * Note that an external function may modify the state of the current page, so this wrapper
178 * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
180 * @param string $function A webservice function name.
181 * @param array $args Params array (named params)
182 * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
183 * @return array containing keys for error (bool), exception and data.
185 public static function call_external_function($function, $args, $ajaxonly=false) {
186 global $PAGE, $COURSE, $CFG, $SITE;
188 require_once($CFG->libdir . "/pagelib.php");
190 $externalfunctioninfo = static::external_function_info($function);
192 // Eventually this should shift into the various handlers and not be handled via config.
193 $readonlysession = $externalfunctioninfo->readonlysession ?? false;
194 if (!$readonlysession || empty($CFG->enable_read_only_sessions)) {
195 \core\session\manager::restart_with_write_lock();
198 $currentpage = $PAGE;
199 $currentcourse = $COURSE;
200 $response = array();
202 try {
203 // Taken straight from from setup.php.
204 if (!empty($CFG->moodlepageclass)) {
205 if (!empty($CFG->moodlepageclassfile)) {
206 require_once($CFG->moodlepageclassfile);
208 $classname = $CFG->moodlepageclass;
209 } else {
210 $classname = 'moodle_page';
212 $PAGE = new $classname();
213 $COURSE = clone($SITE);
215 if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
216 throw new moodle_exception('servicenotavailable', 'webservice');
219 // Do not allow access to write or delete webservices as a public user.
220 if ($externalfunctioninfo->loginrequired && !WS_SERVER) {
221 if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
222 throw new moodle_exception('servicerequireslogin', 'webservice');
224 if (!isloggedin()) {
225 throw new moodle_exception('servicerequireslogin', 'webservice');
226 } else {
227 require_sesskey();
230 // Validate params, this also sorts the params properly, we need the correct order in the next part.
231 $callable = array($externalfunctioninfo->classname, 'validate_parameters');
232 $params = call_user_func($callable,
233 $externalfunctioninfo->parameters_desc,
234 $args);
235 $params = array_values($params);
237 // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
238 // make arbitrary behaviour customisations. The overriding plugin could call the 'real'
239 // function first and then modify the results, or it could do a completely separate
240 // thing.
241 $callbacks = get_plugins_with_function('override_webservice_execution');
242 $result = false;
243 foreach ($callbacks as $plugintype => $plugins) {
244 foreach ($plugins as $plugin => $callback) {
245 $result = $callback($externalfunctioninfo, $params);
246 if ($result !== false) {
247 break;
252 // If the function was not overridden, call the real one.
253 if ($result === false) {
254 $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
255 $result = call_user_func_array($callable, $params);
258 // Validate the return parameters.
259 if ($externalfunctioninfo->returns_desc !== null) {
260 $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
261 $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
264 $response['error'] = false;
265 $response['data'] = $result;
266 } catch (Throwable $e) {
267 $exception = get_exception_info($e);
268 unset($exception->a);
269 $exception->backtrace = format_backtrace($exception->backtrace, true);
270 if (!debugging('', DEBUG_DEVELOPER)) {
271 unset($exception->debuginfo);
272 unset($exception->backtrace);
274 $response['error'] = true;
275 $response['exception'] = $exception;
276 // Do not process the remaining requests.
279 $PAGE = $currentpage;
280 $COURSE = $currentcourse;
282 return $response;
286 * Set context restriction for all following subsequent function calls.
288 * @param stdClass $context the context restriction
289 * @since Moodle 2.0
291 public static function set_context_restriction($context) {
292 self::$contextrestriction = $context;
296 * This method has to be called before every operation
297 * that takes a longer time to finish!
299 * @param int $seconds max expected time the next operation needs
300 * @since Moodle 2.0
302 public static function set_timeout($seconds=360) {
303 $seconds = ($seconds < 300) ? 300 : $seconds;
304 core_php_time_limit::raise($seconds);
308 * Validates submitted function parameters, if anything is incorrect
309 * invalid_parameter_exception is thrown.
310 * This is a simple recursive method which is intended to be called from
311 * each implementation method of external API.
313 * @param external_description $description description of parameters
314 * @param mixed $params the actual parameters
315 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
316 * @since Moodle 2.0
318 public static function validate_parameters(external_description $description, $params) {
319 if ($description instanceof external_value) {
320 if (is_array($params) or is_object($params)) {
321 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
324 if ($description->type == PARAM_BOOL) {
325 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
326 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
327 return (bool)$params;
330 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
331 '", the server was expecting "' . $description->type . '" type';
332 return validate_param($params, $description->type, $description->allownull, $debuginfo);
334 } else if ($description instanceof external_single_structure) {
335 if (!is_array($params)) {
336 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
337 . print_r($params, true) . '\'');
339 $result = array();
340 foreach ($description->keys as $key=>$subdesc) {
341 if (!array_key_exists($key, $params)) {
342 if ($subdesc->required == VALUE_REQUIRED) {
343 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
345 if ($subdesc->required == VALUE_DEFAULT) {
346 try {
347 $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
348 } catch (invalid_parameter_exception $e) {
349 //we are only interested by exceptions returned by validate_param() and validate_parameters()
350 //(in order to build the path to the faulty attribut)
351 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
354 } else {
355 try {
356 $result[$key] = static::validate_parameters($subdesc, $params[$key]);
357 } catch (invalid_parameter_exception $e) {
358 //we are only interested by exceptions returned by validate_param() and validate_parameters()
359 //(in order to build the path to the faulty attribut)
360 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
363 unset($params[$key]);
365 if (!empty($params)) {
366 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
368 return $result;
370 } else if ($description instanceof external_multiple_structure) {
371 if (!is_array($params)) {
372 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
373 . print_r($params, true) . '\'');
375 $result = array();
376 foreach ($params as $param) {
377 $result[] = static::validate_parameters($description->content, $param);
379 return $result;
381 } else {
382 throw new invalid_parameter_exception('Invalid external api description');
387 * Clean response
388 * If a response attribute is unknown from the description, we just ignore the attribute.
389 * If a response attribute is incorrect, invalid_response_exception is thrown.
390 * Note: this function is similar to validate parameters, however it is distinct because
391 * parameters validation must be distinct from cleaning return values.
393 * @param external_description $description description of the return values
394 * @param mixed $response the actual response
395 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
396 * @author 2010 Jerome Mouneyrac
397 * @since Moodle 2.0
399 public static function clean_returnvalue(external_description $description, $response) {
400 if ($description instanceof external_value) {
401 if (is_array($response) or is_object($response)) {
402 throw new invalid_response_exception('Scalar type expected, array or object received.');
405 if ($description->type == PARAM_BOOL) {
406 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
407 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
408 return (bool)$response;
411 $responsetype = gettype($response);
412 $debuginfo = 'Invalid external api response: the value is "' . $response .
413 '" of PHP type "' . $responsetype . '", the server was expecting "' . $description->type . '" type';
414 try {
415 return validate_param($response, $description->type, $description->allownull, $debuginfo);
416 } catch (invalid_parameter_exception $e) {
417 //proper exception name, to be recursively catched to build the path to the faulty attribut
418 throw new invalid_response_exception($e->debuginfo);
421 } else if ($description instanceof external_single_structure) {
422 if (!is_array($response) && !is_object($response)) {
423 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
424 print_r($response, true) . '\'');
427 // Cast objects into arrays.
428 if (is_object($response)) {
429 $response = (array) $response;
432 $result = array();
433 foreach ($description->keys as $key=>$subdesc) {
434 if (!array_key_exists($key, $response)) {
435 if ($subdesc->required == VALUE_REQUIRED) {
436 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
438 if ($subdesc instanceof external_value) {
439 if ($subdesc->required == VALUE_DEFAULT) {
440 try {
441 $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
442 } catch (invalid_response_exception $e) {
443 //build the path to the faulty attribut
444 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
448 } else {
449 try {
450 $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
451 } catch (invalid_response_exception $e) {
452 //build the path to the faulty attribut
453 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
456 unset($response[$key]);
459 return $result;
461 } else if ($description instanceof external_multiple_structure) {
462 if (!is_array($response)) {
463 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
464 print_r($response, true) . '\'');
466 $result = array();
467 foreach ($response as $param) {
468 $result[] = static::clean_returnvalue($description->content, $param);
470 return $result;
472 } else {
473 throw new invalid_response_exception('Invalid external api response description');
478 * Makes sure user may execute functions in this context.
480 * @param stdClass $context
481 * @since Moodle 2.0
483 public static function validate_context($context) {
484 global $CFG, $PAGE;
486 if (empty($context)) {
487 throw new invalid_parameter_exception('Context does not exist');
489 if (empty(self::$contextrestriction)) {
490 self::$contextrestriction = context_system::instance();
492 $rcontext = self::$contextrestriction;
494 if ($rcontext->contextlevel == $context->contextlevel) {
495 if ($rcontext->id != $context->id) {
496 throw new restricted_context_exception();
498 } else if ($rcontext->contextlevel > $context->contextlevel) {
499 throw new restricted_context_exception();
500 } else {
501 $parents = $context->get_parent_context_ids();
502 if (!in_array($rcontext->id, $parents)) {
503 throw new restricted_context_exception();
507 $PAGE->reset_theme_and_output();
508 list($unused, $course, $cm) = get_context_info_array($context->id);
509 require_login($course, false, $cm, false, true);
510 $PAGE->set_context($context);
514 * Get context from passed parameters.
515 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
516 * For example, the context level can be "course" and instanceid can be courseid.
518 * See context_helper::get_all_levels() for a list of valid context levels.
520 * @param array $param
521 * @since Moodle 2.6
522 * @throws invalid_parameter_exception
523 * @return context
525 protected static function get_context_from_params($param) {
526 $levels = context_helper::get_all_levels();
527 if (!empty($param['contextid'])) {
528 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
529 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
530 $contextlevel = "context_".$param['contextlevel'];
531 if (!array_search($contextlevel, $levels)) {
532 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
534 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
535 } else {
536 // No valid context info was found.
537 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
542 * Returns a prepared structure to use a context parameters.
543 * @return external_single_structure
545 protected static function get_context_parameters() {
546 $id = new external_value(
547 PARAM_INT,
548 'Context ID. Either use this value, or level and instanceid.',
549 VALUE_DEFAULT,
552 $level = new external_value(
553 PARAM_ALPHA,
554 'Context level. To be used with instanceid.',
555 VALUE_DEFAULT,
558 $instanceid = new external_value(
559 PARAM_INT,
560 'Context instance ID. To be used with level',
561 VALUE_DEFAULT,
564 return new external_single_structure(array(
565 'contextid' => $id,
566 'contextlevel' => $level,
567 'instanceid' => $instanceid,
574 * Common ancestor of all parameter description classes
576 * @package core_webservice
577 * @copyright 2009 Petr Skodak
578 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
579 * @since Moodle 2.0
581 abstract class external_description {
582 /** @var string Description of element */
583 public $desc;
585 /** @var bool Element value required, null not allowed */
586 public $required;
588 /** @var mixed Default value */
589 public $default;
592 * Contructor
594 * @param string $desc
595 * @param bool $required
596 * @param mixed $default
597 * @since Moodle 2.0
599 public function __construct($desc, $required, $default) {
600 $this->desc = $desc;
601 $this->required = $required;
602 $this->default = $default;
607 * Scalar value description class
609 * @package core_webservice
610 * @copyright 2009 Petr Skodak
611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
612 * @since Moodle 2.0
614 class external_value extends external_description {
616 /** @var mixed Value type PARAM_XX */
617 public $type;
619 /** @var bool Allow null values */
620 public $allownull;
623 * Constructor
625 * @param mixed $type
626 * @param string $desc
627 * @param bool $required
628 * @param mixed $default
629 * @param bool $allownull
630 * @since Moodle 2.0
632 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
633 $default=null, $allownull=NULL_ALLOWED) {
634 parent::__construct($desc, $required, $default);
635 $this->type = $type;
636 $this->allownull = $allownull;
641 * Associative array description class
643 * @package core_webservice
644 * @copyright 2009 Petr Skodak
645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
646 * @since Moodle 2.0
648 class external_single_structure extends external_description {
650 /** @var array Description of array keys key=>external_description */
651 public $keys;
654 * Constructor
656 * @param array $keys
657 * @param string $desc
658 * @param bool $required
659 * @param array $default
660 * @since Moodle 2.0
662 public function __construct(array $keys, $desc='',
663 $required=VALUE_REQUIRED, $default=null) {
664 parent::__construct($desc, $required, $default);
665 $this->keys = $keys;
670 * Bulk array description class.
672 * @package core_webservice
673 * @copyright 2009 Petr Skodak
674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
675 * @since Moodle 2.0
677 class external_multiple_structure extends external_description {
679 /** @var external_description content */
680 public $content;
683 * Constructor
685 * @param external_description $content
686 * @param string $desc
687 * @param bool $required
688 * @param array $default
689 * @since Moodle 2.0
691 public function __construct(external_description $content, $desc='',
692 $required=VALUE_REQUIRED, $default=null) {
693 parent::__construct($desc, $required, $default);
694 $this->content = $content;
699 * Description of top level - PHP function parameters.
701 * @package core_webservice
702 * @copyright 2009 Petr Skodak
703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
704 * @since Moodle 2.0
706 class external_function_parameters extends external_single_structure {
709 * Constructor - does extra checking to prevent top level optional parameters.
711 * @param array $keys
712 * @param string $desc
713 * @param bool $required
714 * @param array $default
716 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
717 global $CFG;
719 if ($CFG->debugdeveloper) {
720 foreach ($keys as $key => $value) {
721 if ($value instanceof external_value) {
722 if ($value->required == VALUE_OPTIONAL) {
723 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
724 break;
729 parent::__construct($keys, $desc, $required, $default);
734 * Generate a token
736 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
737 * @param stdClass|int $serviceorid service linked to the token
738 * @param int $userid user linked to the token
739 * @param stdClass|int $contextorid
740 * @param int $validuntil date when the token expired
741 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
742 * @return string generated token
743 * @author 2010 Jamie Pratt
744 * @since Moodle 2.0
746 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
747 global $DB, $USER;
748 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
749 $numtries = 0;
750 do {
751 $numtries ++;
752 $generatedtoken = md5(uniqid(rand(),1));
753 if ($numtries > 5){
754 throw new moodle_exception('tokengenerationfailed');
756 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
757 $newtoken = new stdClass();
758 $newtoken->token = $generatedtoken;
759 if (!is_object($serviceorid)){
760 $service = $DB->get_record('external_services', array('id' => $serviceorid));
761 } else {
762 $service = $serviceorid;
764 if (!is_object($contextorid)){
765 $context = context::instance_by_id($contextorid, MUST_EXIST);
766 } else {
767 $context = $contextorid;
769 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
770 $newtoken->externalserviceid = $service->id;
771 } else {
772 throw new moodle_exception('nocapabilitytousethisservice');
774 $newtoken->tokentype = $tokentype;
775 $newtoken->userid = $userid;
776 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
777 $newtoken->sid = session_id();
780 $newtoken->contextid = $context->id;
781 $newtoken->creatorid = $USER->id;
782 $newtoken->timecreated = time();
783 $newtoken->validuntil = $validuntil;
784 if (!empty($iprestriction)) {
785 $newtoken->iprestriction = $iprestriction;
787 // Generate the private token, it must be transmitted only via https.
788 $newtoken->privatetoken = random_string(64);
789 $DB->insert_record('external_tokens', $newtoken);
790 return $newtoken->token;
794 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
795 * with the Moodle server through web services. The token is linked to the current session for the current page request.
796 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
797 * returned token will be somehow passed into the client app being embedded in the page.
799 * @param string $servicename name of the web service. Service name as defined in db/services.php
800 * @param int $context context within which the web service can operate.
801 * @return int returns token id.
802 * @since Moodle 2.0
804 function external_create_service_token($servicename, $context){
805 global $USER, $DB;
806 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
807 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
811 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
813 * @param string $component name of component (moodle, mod_assignment, etc.)
815 function external_delete_descriptions($component) {
816 global $DB;
818 $params = array($component);
820 $DB->delete_records_select('external_tokens',
821 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
822 $DB->delete_records_select('external_services_users',
823 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
824 $DB->delete_records_select('external_services_functions',
825 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
826 $DB->delete_records('external_services', array('component'=>$component));
827 $DB->delete_records('external_functions', array('component'=>$component));
831 * Standard Moodle web service warnings
833 * @package core_webservice
834 * @copyright 2012 Jerome Mouneyrac
835 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
836 * @since Moodle 2.3
838 class external_warnings extends external_multiple_structure {
841 * Constructor
843 * @since Moodle 2.3
845 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
846 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
848 parent::__construct(
849 new external_single_structure(
850 array(
851 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
852 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
853 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
854 'message' => new external_value(PARAM_TEXT,
855 'untranslated english message to explain the warning')
856 ), 'warning'),
857 'list of warnings', VALUE_OPTIONAL);
862 * A pre-filled external_value class for text format.
864 * Default is FORMAT_HTML
865 * This should be used all the time in external xxx_params()/xxx_returns functions
866 * as it is the standard way to implement text format param/return values.
868 * @package core_webservice
869 * @copyright 2012 Jerome Mouneyrac
870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
871 * @since Moodle 2.3
873 class external_format_value extends external_value {
876 * Constructor
878 * @param string $textfieldname Name of the text field
879 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
880 * @param int $default Default value.
881 * @since Moodle 2.3
883 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
885 if ($default == null && $required == VALUE_DEFAULT) {
886 $default = FORMAT_HTML;
889 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
890 . FORMAT_MOODLE . ' = MOODLE, '
891 . FORMAT_PLAIN . ' = PLAIN or '
892 . FORMAT_MARKDOWN . ' = MARKDOWN)';
894 parent::__construct(PARAM_INT, $desc, $required, $default);
899 * Validate text field format against known FORMAT_XXX
901 * @param array $format the format to validate
902 * @return the validated format
903 * @throws coding_exception
904 * @since Moodle 2.3
906 function external_validate_format($format) {
907 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
908 if (!in_array($format, $allowedformats)) {
909 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
910 'The format with value=' . $format . ' is not supported by this Moodle site');
912 return $format;
916 * Format the string to be returned properly as requested by the either the web service server,
917 * either by an internally call.
918 * The caller can change the format (raw) with the external_settings singleton
919 * All web service servers must set this singleton when parsing the $_GET and $_POST.
921 * <pre>
922 * Options are the same that in {@link format_string()} with some changes:
923 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
924 * </pre>
926 * @param string $str The string to be filtered. Should be plain text, expect
927 * possibly for multilang tags.
928 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
929 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
930 * @param array $options options array/object or courseid
931 * @return string text
932 * @since Moodle 3.0
934 function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
936 // Get settings (singleton).
937 $settings = external_settings::get_instance();
938 if (empty($contextorid)) {
939 throw new coding_exception('contextid is required');
942 if (!$settings->get_raw()) {
943 if (is_object($contextorid) && is_a($contextorid, 'context')) {
944 $context = $contextorid;
945 } else {
946 $context = context::instance_by_id($contextorid);
948 $options['context'] = $context;
949 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
950 $str = format_string($str, $striplinks, $options);
953 return $str;
957 * Format the text to be returned properly as requested by the either the web service server,
958 * either by an internally call.
959 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
960 * All web service servers must set this singleton when parsing the $_GET and $_POST.
962 * <pre>
963 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
964 * trusted : If true the string won't be cleaned. Default false.
965 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
966 * nocache : If true the string will not be cached and will be formatted every call. Default false.
967 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
968 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
969 * Default changed because div tags are not commonly needed.
970 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
971 * context : Not used! Using contextid parameter instead.
972 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
973 * returned. Default false.
974 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
975 * format_text) true. Default changed id attributes are commonly needed.
976 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
977 * </pre>
979 * @param string $text The content that may contain ULRs in need of rewriting.
980 * @param int $textformat The text format.
981 * @param context|int $contextorid This parameter and the next two identify the file area to use.
982 * @param string $component
983 * @param string $filearea helps identify the file area.
984 * @param int $itemid helps identify the file area.
985 * @param object/array $options text formatting options
986 * @return array text + textformat
987 * @since Moodle 2.3
988 * @since Moodle 3.2 component, filearea and itemid are optional parameters
990 function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
991 $options = null) {
992 global $CFG;
994 // Get settings (singleton).
995 $settings = external_settings::get_instance();
997 if (is_object($contextorid) && is_a($contextorid, 'context')) {
998 $context = $contextorid;
999 $contextid = $context->id;
1000 } else {
1001 $context = null;
1002 $contextid = $contextorid;
1005 if ($component and $filearea and $settings->get_fileurl()) {
1006 require_once($CFG->libdir . "/filelib.php");
1007 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
1010 // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
1011 // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
1013 if (!$settings->get_raw()) {
1014 $options = (array)$options;
1016 // If context is passed in options, check that is the same to show a debug message.
1017 if (isset($options['context'])) {
1018 if ((is_object($options['context']) && $options['context']->id != $contextid)
1019 || (!is_object($options['context']) && $options['context'] != $contextid)) {
1020 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
1021 Using $contextid parameter...', DEBUG_DEVELOPER);
1025 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
1026 $options['para'] = isset($options['para']) ? $options['para'] : false;
1027 $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
1028 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
1030 $text = format_text($text, $textformat, $options);
1031 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
1034 return array($text, $textformat);
1038 * Generate or return an existing token for the current authenticated user.
1039 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
1041 * @param stdClass $service external service object
1042 * @return stdClass token object
1043 * @since Moodle 3.2
1044 * @throws moodle_exception
1046 function external_generate_token_for_current_user($service) {
1047 global $DB, $USER, $CFG;
1049 core_user::require_active_user($USER, true, true);
1051 // Check if there is any required system capability.
1052 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1053 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1056 // Specific checks related to user restricted service.
1057 if ($service->restrictedusers) {
1058 $authoriseduser = $DB->get_record('external_services_users',
1059 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1061 if (empty($authoriseduser)) {
1062 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1065 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1066 throw new moodle_exception('invalidtimedtoken', 'webservice');
1069 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1070 throw new moodle_exception('invalidiptoken', 'webservice');
1074 // Check if a token has already been created for this user and this service.
1075 $conditions = array(
1076 'userid' => $USER->id,
1077 'externalserviceid' => $service->id,
1078 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1080 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1082 // A bit of sanity checks.
1083 foreach ($tokens as $key => $token) {
1085 // Checks related to a specific token. (script execution continue).
1086 $unsettoken = false;
1087 // If sid is set then there must be a valid associated session no matter the token type.
1088 if (!empty($token->sid)) {
1089 if (!\core\session\manager::session_exists($token->sid)) {
1090 // This token will never be valid anymore, delete it.
1091 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1092 $unsettoken = true;
1096 // Remove token is not valid anymore.
1097 if (!empty($token->validuntil) and $token->validuntil < time()) {
1098 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1099 $unsettoken = true;
1102 // Remove token if its ip not in whitelist.
1103 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1104 $unsettoken = true;
1107 if ($unsettoken) {
1108 unset($tokens[$key]);
1112 // If some valid tokens exist then use the most recent.
1113 if (count($tokens) > 0) {
1114 $token = array_pop($tokens);
1115 } else {
1116 $context = context_system::instance();
1117 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1119 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1120 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1122 // Create a new token.
1123 $token = new stdClass;
1124 $token->token = md5(uniqid(rand(), 1));
1125 $token->userid = $USER->id;
1126 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1127 $token->contextid = context_system::instance()->id;
1128 $token->creatorid = $USER->id;
1129 $token->timecreated = time();
1130 $token->externalserviceid = $service->id;
1131 // By default tokens are valid for 12 weeks.
1132 $token->validuntil = $token->timecreated + $CFG->tokenduration;
1133 $token->iprestriction = null;
1134 $token->sid = null;
1135 $token->lastaccess = null;
1136 // Generate the private token, it must be transmitted only via https.
1137 $token->privatetoken = random_string(64);
1138 $token->id = $DB->insert_record('external_tokens', $token);
1140 $eventtoken = clone $token;
1141 $eventtoken->privatetoken = null;
1142 $params = array(
1143 'objectid' => $eventtoken->id,
1144 'relateduserid' => $USER->id,
1145 'other' => array(
1146 'auto' => true
1149 $event = \core\event\webservice_token_created::create($params);
1150 $event->add_record_snapshot('external_tokens', $eventtoken);
1151 $event->trigger();
1152 } else {
1153 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1156 return $token;
1160 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1162 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1163 * In order to protect the privatetoken, we remove it from the event params.
1165 * @param stdClass $token token object
1166 * @since Moodle 3.2
1168 function external_log_token_request($token) {
1169 global $DB;
1171 $token->privatetoken = null;
1173 // Log token access.
1174 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1176 $params = array(
1177 'objectid' => $token->id,
1179 $event = \core\event\webservice_token_sent::create($params);
1180 $event->add_record_snapshot('external_tokens', $token);
1181 $event->trigger();
1185 * Singleton to handle the external settings.
1187 * We use singleton to encapsulate the "logic"
1189 * @package core_webservice
1190 * @copyright 2012 Jerome Mouneyrac
1191 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1192 * @since Moodle 2.3
1194 class external_settings {
1196 /** @var object the singleton instance */
1197 public static $instance = null;
1199 /** @var boolean Should the external function return raw text or formatted */
1200 private $raw = false;
1202 /** @var boolean Should the external function filter the text */
1203 private $filter = false;
1205 /** @var boolean Should the external function rewrite plugin file url */
1206 private $fileurl = true;
1208 /** @var string In which file should the urls be rewritten */
1209 private $file = 'webservice/pluginfile.php';
1211 /** @var string The session lang */
1212 private $lang = '';
1215 * Constructor - protected - can not be instanciated
1217 protected function __construct() {
1218 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
1219 // For normal pages, the default should match the default for format_text.
1220 $this->filter = true;
1221 // Use pluginfile.php for web requests.
1222 $this->file = 'pluginfile.php';
1227 * Clone - private - can not be cloned
1229 private final function __clone() {
1233 * Return only one instance
1235 * @return \external_settings
1237 public static function get_instance() {
1238 if (self::$instance === null) {
1239 self::$instance = new external_settings;
1242 return self::$instance;
1246 * Set raw
1248 * @param boolean $raw
1250 public function set_raw($raw) {
1251 $this->raw = $raw;
1255 * Get raw
1257 * @return boolean
1259 public function get_raw() {
1260 return $this->raw;
1264 * Set filter
1266 * @param boolean $filter
1268 public function set_filter($filter) {
1269 $this->filter = $filter;
1273 * Get filter
1275 * @return boolean
1277 public function get_filter() {
1278 return $this->filter;
1282 * Set fileurl
1284 * @param boolean $fileurl
1286 public function set_fileurl($fileurl) {
1287 $this->fileurl = $fileurl;
1291 * Get fileurl
1293 * @return boolean
1295 public function get_fileurl() {
1296 return $this->fileurl;
1300 * Set file
1302 * @param string $file
1304 public function set_file($file) {
1305 $this->file = $file;
1309 * Get file
1311 * @return string
1313 public function get_file() {
1314 return $this->file;
1318 * Set lang
1320 * @param string $lang
1322 public function set_lang($lang) {
1323 $this->lang = $lang;
1327 * Get lang
1329 * @return string
1331 public function get_lang() {
1332 return $this->lang;
1337 * Utility functions for the external API.
1339 * @package core_webservice
1340 * @copyright 2015 Juan Leyva
1341 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1342 * @since Moodle 3.0
1344 class external_util {
1347 * Validate a list of courses, returning the complete course objects for valid courses.
1349 * Each course has an additional 'contextvalidated' field, this will be set to true unless
1350 * you set $keepfails, in which case it will be false if validation fails for a course.
1352 * @param array $courseids A list of course ids
1353 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1354 * @param bool $addcontext True if the returned course object should include the full context object.
1355 * @param bool $keepfails True to keep all the course objects even if validation fails
1356 * @return array An array of courses and the validation warnings
1358 public static function validate_courses($courseids, $courses = array(), $addcontext = false,
1359 $keepfails = false) {
1360 global $DB;
1362 // Delete duplicates.
1363 $courseids = array_unique($courseids);
1364 $warnings = array();
1366 // Remove courses which are not even requested.
1367 $courses = array_intersect_key($courses, array_flip($courseids));
1369 // For any courses NOT loaded already, get them in a single query (and preload contexts)
1370 // for performance. Preserve ordering because some tests depend on it.
1371 $newcourseids = [];
1372 foreach ($courseids as $cid) {
1373 if (!array_key_exists($cid, $courses)) {
1374 $newcourseids[] = $cid;
1377 if ($newcourseids) {
1378 list ($listsql, $listparams) = $DB->get_in_or_equal($newcourseids);
1380 // Load list of courses, and preload associated contexts.
1381 $contextselect = context_helper::get_preload_record_columns_sql('x');
1382 $newcourses = $DB->get_records_sql("
1383 SELECT c.*, $contextselect
1384 FROM {course} c
1385 JOIN {context} x ON x.instanceid = c.id
1386 WHERE x.contextlevel = ? AND c.id $listsql",
1387 array_merge([CONTEXT_COURSE], $listparams));
1388 foreach ($newcourseids as $cid) {
1389 if (array_key_exists($cid, $newcourses)) {
1390 $course = $newcourses[$cid];
1391 context_helper::preload_from_record($course);
1392 $courses[$course->id] = $course;
1397 foreach ($courseids as $cid) {
1398 // Check the user can function in this context.
1399 try {
1400 $context = context_course::instance($cid);
1401 external_api::validate_context($context);
1403 if ($addcontext) {
1404 $courses[$cid]->context = $context;
1406 $courses[$cid]->contextvalidated = true;
1407 } catch (Exception $e) {
1408 if ($keepfails) {
1409 $courses[$cid]->contextvalidated = false;
1410 } else {
1411 unset($courses[$cid]);
1413 $warnings[] = array(
1414 'item' => 'course',
1415 'itemid' => $cid,
1416 'warningcode' => '1',
1417 'message' => 'No access rights in course context'
1422 return array($courses, $warnings);
1426 * Returns all area files (optionally limited by itemid).
1428 * @param int $contextid context ID
1429 * @param string $component component
1430 * @param string $filearea file area
1431 * @param int $itemid item ID or all files if not specified
1432 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1433 * @return array of files, compatible with the external_files structure.
1434 * @since Moodle 3.2
1436 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1437 $files = array();
1438 $fs = get_file_storage();
1440 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1441 foreach ($areafiles as $areafile) {
1442 $file = array();
1443 $file['filename'] = $areafile->get_filename();
1444 $file['filepath'] = $areafile->get_filepath();
1445 $file['mimetype'] = $areafile->get_mimetype();
1446 $file['filesize'] = $areafile->get_filesize();
1447 $file['timemodified'] = $areafile->get_timemodified();
1448 $file['isexternalfile'] = $areafile->is_external_file();
1449 if ($file['isexternalfile']) {
1450 $file['repositorytype'] = $areafile->get_repository_type();
1452 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1453 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1454 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1455 $files[] = $file;
1458 return $files;
1463 * External structure representing a set of files.
1465 * @package core_webservice
1466 * @copyright 2016 Juan Leyva
1467 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1468 * @since Moodle 3.2
1470 class external_files extends external_multiple_structure {
1473 * Constructor
1474 * @param string $desc Description for the multiple structure.
1475 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1477 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1479 parent::__construct(
1480 new external_single_structure(
1481 array(
1482 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1483 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1484 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1485 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1486 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1487 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1488 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1489 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
1491 'File.'
1493 $desc,
1494 $required
1499 * Return the properties ready to be used by an exporter.
1501 * @return array properties
1502 * @since Moodle 3.3
1504 public static function get_properties_for_exporter() {
1505 return [
1506 'filename' => array(
1507 'type' => PARAM_FILE,
1508 'description' => 'File name.',
1509 'optional' => true,
1510 'null' => NULL_NOT_ALLOWED,
1512 'filepath' => array(
1513 'type' => PARAM_PATH,
1514 'description' => 'File path.',
1515 'optional' => true,
1516 'null' => NULL_NOT_ALLOWED,
1518 'filesize' => array(
1519 'type' => PARAM_INT,
1520 'description' => 'File size.',
1521 'optional' => true,
1522 'null' => NULL_NOT_ALLOWED,
1524 'fileurl' => array(
1525 'type' => PARAM_URL,
1526 'description' => 'Downloadable file url.',
1527 'optional' => true,
1528 'null' => NULL_NOT_ALLOWED,
1530 'timemodified' => array(
1531 'type' => PARAM_INT,
1532 'description' => 'Time modified.',
1533 'optional' => true,
1534 'null' => NULL_NOT_ALLOWED,
1536 'mimetype' => array(
1537 'type' => PARAM_RAW,
1538 'description' => 'File mime type.',
1539 'optional' => true,
1540 'null' => NULL_NOT_ALLOWED,
1542 'isexternalfile' => array(
1543 'type' => PARAM_BOOL,
1544 'description' => 'Whether is an external file.',
1545 'optional' => true,
1546 'null' => NULL_NOT_ALLOWED,
1548 'repositorytype' => array(
1549 'type' => PARAM_PLUGIN,
1550 'description' => 'The repository type for the external files.',
1551 'optional' => true,
1552 'null' => NULL_ALLOWED,