Merge branch 'MDL-61947-master' of git://github.com/zig-moodle/moodle
[moodle.git] / lib / externallib.php
blob667eed8f6c8cd4685222906e9c078998af6c289a
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('servicenotavailable', 'webservice');
213 if (!isloggedin()) {
214 throw new moodle_exception('servicenotavailable', '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);
225 // Execute - gulp!
226 $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
227 $result = call_user_func_array($callable,
228 array_values($params));
230 // Validate the return parameters.
231 if ($externalfunctioninfo->returns_desc !== null) {
232 $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
233 $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
236 $response['error'] = false;
237 $response['data'] = $result;
238 } catch (Exception $e) {
239 $exception = get_exception_info($e);
240 unset($exception->a);
241 $exception->backtrace = format_backtrace($exception->backtrace, true);
242 if (!debugging('', DEBUG_DEVELOPER)) {
243 unset($exception->debuginfo);
244 unset($exception->backtrace);
246 $response['error'] = true;
247 $response['exception'] = $exception;
248 // Do not process the remaining requests.
251 $PAGE = $currentpage;
252 $COURSE = $currentcourse;
254 return $response;
258 * Set context restriction for all following subsequent function calls.
260 * @param stdClass $context the context restriction
261 * @since Moodle 2.0
263 public static function set_context_restriction($context) {
264 self::$contextrestriction = $context;
268 * This method has to be called before every operation
269 * that takes a longer time to finish!
271 * @param int $seconds max expected time the next operation needs
272 * @since Moodle 2.0
274 public static function set_timeout($seconds=360) {
275 $seconds = ($seconds < 300) ? 300 : $seconds;
276 core_php_time_limit::raise($seconds);
280 * Validates submitted function parameters, if anything is incorrect
281 * invalid_parameter_exception is thrown.
282 * This is a simple recursive method which is intended to be called from
283 * each implementation method of external API.
285 * @param external_description $description description of parameters
286 * @param mixed $params the actual parameters
287 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
288 * @since Moodle 2.0
290 public static function validate_parameters(external_description $description, $params) {
291 if ($description instanceof external_value) {
292 if (is_array($params) or is_object($params)) {
293 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
296 if ($description->type == PARAM_BOOL) {
297 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
298 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
299 return (bool)$params;
302 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
303 '", the server was expecting "' . $description->type . '" type';
304 return validate_param($params, $description->type, $description->allownull, $debuginfo);
306 } else if ($description instanceof external_single_structure) {
307 if (!is_array($params)) {
308 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
309 . print_r($params, true) . '\'');
311 $result = array();
312 foreach ($description->keys as $key=>$subdesc) {
313 if (!array_key_exists($key, $params)) {
314 if ($subdesc->required == VALUE_REQUIRED) {
315 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
317 if ($subdesc->required == VALUE_DEFAULT) {
318 try {
319 $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
320 } catch (invalid_parameter_exception $e) {
321 //we are only interested by exceptions returned by validate_param() and validate_parameters()
322 //(in order to build the path to the faulty attribut)
323 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
326 } else {
327 try {
328 $result[$key] = static::validate_parameters($subdesc, $params[$key]);
329 } catch (invalid_parameter_exception $e) {
330 //we are only interested by exceptions returned by validate_param() and validate_parameters()
331 //(in order to build the path to the faulty attribut)
332 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
335 unset($params[$key]);
337 if (!empty($params)) {
338 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
340 return $result;
342 } else if ($description instanceof external_multiple_structure) {
343 if (!is_array($params)) {
344 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
345 . print_r($params, true) . '\'');
347 $result = array();
348 foreach ($params as $param) {
349 $result[] = static::validate_parameters($description->content, $param);
351 return $result;
353 } else {
354 throw new invalid_parameter_exception('Invalid external api description');
359 * Clean response
360 * If a response attribute is unknown from the description, we just ignore the attribute.
361 * If a response attribute is incorrect, invalid_response_exception is thrown.
362 * Note: this function is similar to validate parameters, however it is distinct because
363 * parameters validation must be distinct from cleaning return values.
365 * @param external_description $description description of the return values
366 * @param mixed $response the actual response
367 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
368 * @author 2010 Jerome Mouneyrac
369 * @since Moodle 2.0
371 public static function clean_returnvalue(external_description $description, $response) {
372 if ($description instanceof external_value) {
373 if (is_array($response) or is_object($response)) {
374 throw new invalid_response_exception('Scalar type expected, array or object received.');
377 if ($description->type == PARAM_BOOL) {
378 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
379 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
380 return (bool)$response;
383 $debuginfo = 'Invalid external api response: the value is "' . $response .
384 '", the server was expecting "' . $description->type . '" type';
385 try {
386 return validate_param($response, $description->type, $description->allownull, $debuginfo);
387 } catch (invalid_parameter_exception $e) {
388 //proper exception name, to be recursively catched to build the path to the faulty attribut
389 throw new invalid_response_exception($e->debuginfo);
392 } else if ($description instanceof external_single_structure) {
393 if (!is_array($response) && !is_object($response)) {
394 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
395 print_r($response, true) . '\'');
398 // Cast objects into arrays.
399 if (is_object($response)) {
400 $response = (array) $response;
403 $result = array();
404 foreach ($description->keys as $key=>$subdesc) {
405 if (!array_key_exists($key, $response)) {
406 if ($subdesc->required == VALUE_REQUIRED) {
407 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
409 if ($subdesc instanceof external_value) {
410 if ($subdesc->required == VALUE_DEFAULT) {
411 try {
412 $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
413 } catch (invalid_response_exception $e) {
414 //build the path to the faulty attribut
415 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
419 } else {
420 try {
421 $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
422 } catch (invalid_response_exception $e) {
423 //build the path to the faulty attribut
424 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
427 unset($response[$key]);
430 return $result;
432 } else if ($description instanceof external_multiple_structure) {
433 if (!is_array($response)) {
434 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
435 print_r($response, true) . '\'');
437 $result = array();
438 foreach ($response as $param) {
439 $result[] = static::clean_returnvalue($description->content, $param);
441 return $result;
443 } else {
444 throw new invalid_response_exception('Invalid external api response description');
449 * Makes sure user may execute functions in this context.
451 * @param stdClass $context
452 * @since Moodle 2.0
454 public static function validate_context($context) {
455 global $CFG, $PAGE;
457 if (empty($context)) {
458 throw new invalid_parameter_exception('Context does not exist');
460 if (empty(self::$contextrestriction)) {
461 self::$contextrestriction = context_system::instance();
463 $rcontext = self::$contextrestriction;
465 if ($rcontext->contextlevel == $context->contextlevel) {
466 if ($rcontext->id != $context->id) {
467 throw new restricted_context_exception();
469 } else if ($rcontext->contextlevel > $context->contextlevel) {
470 throw new restricted_context_exception();
471 } else {
472 $parents = $context->get_parent_context_ids();
473 if (!in_array($rcontext->id, $parents)) {
474 throw new restricted_context_exception();
478 $PAGE->reset_theme_and_output();
479 list($unused, $course, $cm) = get_context_info_array($context->id);
480 require_login($course, false, $cm, false, true);
481 $PAGE->set_context($context);
485 * Get context from passed parameters.
486 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
487 * For example, the context level can be "course" and instanceid can be courseid.
489 * See context_helper::get_all_levels() for a list of valid context levels.
491 * @param array $param
492 * @since Moodle 2.6
493 * @throws invalid_parameter_exception
494 * @return context
496 protected static function get_context_from_params($param) {
497 $levels = context_helper::get_all_levels();
498 if (!empty($param['contextid'])) {
499 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
500 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
501 $contextlevel = "context_".$param['contextlevel'];
502 if (!array_search($contextlevel, $levels)) {
503 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
505 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
506 } else {
507 // No valid context info was found.
508 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
513 * Returns a prepared structure to use a context parameters.
514 * @return external_single_structure
516 protected static function get_context_parameters() {
517 $id = new external_value(
518 PARAM_INT,
519 'Context ID. Either use this value, or level and instanceid.',
520 VALUE_DEFAULT,
523 $level = new external_value(
524 PARAM_ALPHA,
525 'Context level. To be used with instanceid.',
526 VALUE_DEFAULT,
529 $instanceid = new external_value(
530 PARAM_INT,
531 'Context instance ID. To be used with level',
532 VALUE_DEFAULT,
535 return new external_single_structure(array(
536 'contextid' => $id,
537 'contextlevel' => $level,
538 'instanceid' => $instanceid,
545 * Common ancestor of all parameter description classes
547 * @package core_webservice
548 * @copyright 2009 Petr Skodak
549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550 * @since Moodle 2.0
552 abstract class external_description {
553 /** @var string Description of element */
554 public $desc;
556 /** @var bool Element value required, null not allowed */
557 public $required;
559 /** @var mixed Default value */
560 public $default;
563 * Contructor
565 * @param string $desc
566 * @param bool $required
567 * @param mixed $default
568 * @since Moodle 2.0
570 public function __construct($desc, $required, $default) {
571 $this->desc = $desc;
572 $this->required = $required;
573 $this->default = $default;
578 * Scalar value description class
580 * @package core_webservice
581 * @copyright 2009 Petr Skodak
582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
583 * @since Moodle 2.0
585 class external_value extends external_description {
587 /** @var mixed Value type PARAM_XX */
588 public $type;
590 /** @var bool Allow null values */
591 public $allownull;
594 * Constructor
596 * @param mixed $type
597 * @param string $desc
598 * @param bool $required
599 * @param mixed $default
600 * @param bool $allownull
601 * @since Moodle 2.0
603 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
604 $default=null, $allownull=NULL_ALLOWED) {
605 parent::__construct($desc, $required, $default);
606 $this->type = $type;
607 $this->allownull = $allownull;
612 * Associative array description class
614 * @package core_webservice
615 * @copyright 2009 Petr Skodak
616 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
617 * @since Moodle 2.0
619 class external_single_structure extends external_description {
621 /** @var array Description of array keys key=>external_description */
622 public $keys;
625 * Constructor
627 * @param array $keys
628 * @param string $desc
629 * @param bool $required
630 * @param array $default
631 * @since Moodle 2.0
633 public function __construct(array $keys, $desc='',
634 $required=VALUE_REQUIRED, $default=null) {
635 parent::__construct($desc, $required, $default);
636 $this->keys = $keys;
641 * Bulk 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_multiple_structure extends external_description {
650 /** @var external_description content */
651 public $content;
654 * Constructor
656 * @param external_description $content
657 * @param string $desc
658 * @param bool $required
659 * @param array $default
660 * @since Moodle 2.0
662 public function __construct(external_description $content, $desc='',
663 $required=VALUE_REQUIRED, $default=null) {
664 parent::__construct($desc, $required, $default);
665 $this->content = $content;
670 * Description of top level - PHP function parameters.
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_function_parameters extends external_single_structure {
680 * Constructor - does extra checking to prevent top level optional parameters.
682 * @param array $keys
683 * @param string $desc
684 * @param bool $required
685 * @param array $default
687 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
688 global $CFG;
690 if ($CFG->debugdeveloper) {
691 foreach ($keys as $key => $value) {
692 if ($value instanceof external_value) {
693 if ($value->required == VALUE_OPTIONAL) {
694 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
695 break;
700 parent::__construct($keys, $desc, $required, $default);
705 * Generate a token
707 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
708 * @param stdClass|int $serviceorid service linked to the token
709 * @param int $userid user linked to the token
710 * @param stdClass|int $contextorid
711 * @param int $validuntil date when the token expired
712 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
713 * @return string generated token
714 * @author 2010 Jamie Pratt
715 * @since Moodle 2.0
717 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
718 global $DB, $USER;
719 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
720 $numtries = 0;
721 do {
722 $numtries ++;
723 $generatedtoken = md5(uniqid(rand(),1));
724 if ($numtries > 5){
725 throw new moodle_exception('tokengenerationfailed');
727 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
728 $newtoken = new stdClass();
729 $newtoken->token = $generatedtoken;
730 if (!is_object($serviceorid)){
731 $service = $DB->get_record('external_services', array('id' => $serviceorid));
732 } else {
733 $service = $serviceorid;
735 if (!is_object($contextorid)){
736 $context = context::instance_by_id($contextorid, MUST_EXIST);
737 } else {
738 $context = $contextorid;
740 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
741 $newtoken->externalserviceid = $service->id;
742 } else {
743 throw new moodle_exception('nocapabilitytousethisservice');
745 $newtoken->tokentype = $tokentype;
746 $newtoken->userid = $userid;
747 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
748 $newtoken->sid = session_id();
751 $newtoken->contextid = $context->id;
752 $newtoken->creatorid = $USER->id;
753 $newtoken->timecreated = time();
754 $newtoken->validuntil = $validuntil;
755 if (!empty($iprestriction)) {
756 $newtoken->iprestriction = $iprestriction;
758 $newtoken->privatetoken = null;
759 $DB->insert_record('external_tokens', $newtoken);
760 return $newtoken->token;
764 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
765 * with the Moodle server through web services. The token is linked to the current session for the current page request.
766 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
767 * returned token will be somehow passed into the client app being embedded in the page.
769 * @param string $servicename name of the web service. Service name as defined in db/services.php
770 * @param int $context context within which the web service can operate.
771 * @return int returns token id.
772 * @since Moodle 2.0
774 function external_create_service_token($servicename, $context){
775 global $USER, $DB;
776 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
777 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
781 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
783 * @param string $component name of component (moodle, mod_assignment, etc.)
785 function external_delete_descriptions($component) {
786 global $DB;
788 $params = array($component);
790 $DB->delete_records_select('external_tokens',
791 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
792 $DB->delete_records_select('external_services_users',
793 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
794 $DB->delete_records_select('external_services_functions',
795 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
796 $DB->delete_records('external_services', array('component'=>$component));
797 $DB->delete_records('external_functions', array('component'=>$component));
801 * Standard Moodle web service warnings
803 * @package core_webservice
804 * @copyright 2012 Jerome Mouneyrac
805 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
806 * @since Moodle 2.3
808 class external_warnings extends external_multiple_structure {
811 * Constructor
813 * @since Moodle 2.3
815 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
816 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
818 parent::__construct(
819 new external_single_structure(
820 array(
821 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
822 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
823 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
824 'message' => new external_value(PARAM_TEXT,
825 'untranslated english message to explain the warning')
826 ), 'warning'),
827 'list of warnings', VALUE_OPTIONAL);
832 * A pre-filled external_value class for text format.
834 * Default is FORMAT_HTML
835 * This should be used all the time in external xxx_params()/xxx_returns functions
836 * as it is the standard way to implement text format param/return values.
838 * @package core_webservice
839 * @copyright 2012 Jerome Mouneyrac
840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
841 * @since Moodle 2.3
843 class external_format_value extends external_value {
846 * Constructor
848 * @param string $textfieldname Name of the text field
849 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
850 * @param int $default Default value.
851 * @since Moodle 2.3
853 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
855 if ($default == null && $required == VALUE_DEFAULT) {
856 $default = FORMAT_HTML;
859 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
860 . FORMAT_MOODLE . ' = MOODLE, '
861 . FORMAT_PLAIN . ' = PLAIN or '
862 . FORMAT_MARKDOWN . ' = MARKDOWN)';
864 parent::__construct(PARAM_INT, $desc, $required, $default);
869 * Validate text field format against known FORMAT_XXX
871 * @param array $format the format to validate
872 * @return the validated format
873 * @throws coding_exception
874 * @since Moodle 2.3
876 function external_validate_format($format) {
877 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
878 if (!in_array($format, $allowedformats)) {
879 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
880 'The format with value=' . $format . ' is not supported by this Moodle site');
882 return $format;
886 * Format the string to be returned properly as requested by the either the web service server,
887 * either by an internally call.
888 * The caller can change the format (raw) with the external_settings singleton
889 * All web service servers must set this singleton when parsing the $_GET and $_POST.
891 * <pre>
892 * Options are the same that in {@link format_string()} with some changes:
893 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
894 * </pre>
896 * @param string $str The string to be filtered. Should be plain text, expect
897 * possibly for multilang tags.
898 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
899 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
900 * @param array $options options array/object or courseid
901 * @return string text
902 * @since Moodle 3.0
904 function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
906 // Get settings (singleton).
907 $settings = external_settings::get_instance();
908 if (empty($contextorid)) {
909 throw new coding_exception('contextid is required');
912 if (!$settings->get_raw()) {
913 if (is_object($contextorid) && is_a($contextorid, 'context')) {
914 $context = $contextorid;
915 } else {
916 $context = context::instance_by_id($contextorid);
918 $options['context'] = $context;
919 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
920 $str = format_string($str, $striplinks, $options);
923 return $str;
927 * Format the text to be returned properly as requested by the either the web service server,
928 * either by an internally call.
929 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
930 * All web service servers must set this singleton when parsing the $_GET and $_POST.
932 * <pre>
933 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
934 * trusted : If true the string won't be cleaned. Default false.
935 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
936 * nocache : If true the string will not be cached and will be formatted every call. Default false.
937 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
938 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
939 * Default changed because div tags are not commonly needed.
940 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
941 * context : Not used! Using contextid parameter instead.
942 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
943 * returned. Default false.
944 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
945 * format_text) true. Default changed id attributes are commonly needed.
946 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
947 * </pre>
949 * @param string $text The content that may contain ULRs in need of rewriting.
950 * @param int $textformat The text format.
951 * @param context|int $contextorid This parameter and the next two identify the file area to use.
952 * @param string $component
953 * @param string $filearea helps identify the file area.
954 * @param int $itemid helps identify the file area.
955 * @param object/array $options text formatting options
956 * @return array text + textformat
957 * @since Moodle 2.3
958 * @since Moodle 3.2 component, filearea and itemid are optional parameters
960 function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
961 $options = null) {
962 global $CFG;
964 // Get settings (singleton).
965 $settings = external_settings::get_instance();
967 if (is_object($contextorid) && is_a($contextorid, 'context')) {
968 $context = $contextorid;
969 $contextid = $context->id;
970 } else {
971 $context = null;
972 $contextid = $contextorid;
975 if ($component and $filearea and $settings->get_fileurl()) {
976 require_once($CFG->libdir . "/filelib.php");
977 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
980 // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
981 // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
983 if (!$settings->get_raw()) {
984 $options = (array)$options;
986 // If context is passed in options, check that is the same to show a debug message.
987 if (isset($options['context'])) {
988 if ((is_object($options['context']) && $options['context']->id != $contextid)
989 || (!is_object($options['context']) && $options['context'] != $contextid)) {
990 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
991 Using $contextid parameter...', DEBUG_DEVELOPER);
995 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
996 $options['para'] = isset($options['para']) ? $options['para'] : false;
997 $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
998 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
1000 $text = format_text($text, $textformat, $options);
1001 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
1004 return array($text, $textformat);
1008 * Generate or return an existing token for the current authenticated user.
1009 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
1011 * @param stdClass $service external service object
1012 * @return stdClass token object
1013 * @since Moodle 3.2
1014 * @throws moodle_exception
1016 function external_generate_token_for_current_user($service) {
1017 global $DB, $USER, $CFG;
1019 core_user::require_active_user($USER, true, true);
1021 // Check if there is any required system capability.
1022 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1023 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1026 // Specific checks related to user restricted service.
1027 if ($service->restrictedusers) {
1028 $authoriseduser = $DB->get_record('external_services_users',
1029 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1031 if (empty($authoriseduser)) {
1032 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1035 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1036 throw new moodle_exception('invalidtimedtoken', 'webservice');
1039 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1040 throw new moodle_exception('invalidiptoken', 'webservice');
1044 // Check if a token has already been created for this user and this service.
1045 $conditions = array(
1046 'userid' => $USER->id,
1047 'externalserviceid' => $service->id,
1048 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1050 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1052 // A bit of sanity checks.
1053 foreach ($tokens as $key => $token) {
1055 // Checks related to a specific token. (script execution continue).
1056 $unsettoken = false;
1057 // If sid is set then there must be a valid associated session no matter the token type.
1058 if (!empty($token->sid)) {
1059 if (!\core\session\manager::session_exists($token->sid)) {
1060 // This token will never be valid anymore, delete it.
1061 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1062 $unsettoken = true;
1066 // Remove token is not valid anymore.
1067 if (!empty($token->validuntil) and $token->validuntil < time()) {
1068 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1069 $unsettoken = true;
1072 // Remove token if its ip not in whitelist.
1073 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1074 $unsettoken = true;
1077 if ($unsettoken) {
1078 unset($tokens[$key]);
1082 // If some valid tokens exist then use the most recent.
1083 if (count($tokens) > 0) {
1084 $token = array_pop($tokens);
1085 } else {
1086 $context = context_system::instance();
1087 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1089 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1090 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1092 // Create a new token.
1093 $token = new stdClass;
1094 $token->token = md5(uniqid(rand(), 1));
1095 $token->userid = $USER->id;
1096 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1097 $token->contextid = context_system::instance()->id;
1098 $token->creatorid = $USER->id;
1099 $token->timecreated = time();
1100 $token->externalserviceid = $service->id;
1101 // By default tokens are valid for 12 weeks.
1102 $token->validuntil = $token->timecreated + $CFG->tokenduration;
1103 $token->iprestriction = null;
1104 $token->sid = null;
1105 $token->lastaccess = null;
1106 // Generate the private token, it must be transmitted only via https.
1107 $token->privatetoken = random_string(64);
1108 $token->id = $DB->insert_record('external_tokens', $token);
1110 $eventtoken = clone $token;
1111 $eventtoken->privatetoken = null;
1112 $params = array(
1113 'objectid' => $eventtoken->id,
1114 'relateduserid' => $USER->id,
1115 'other' => array(
1116 'auto' => true
1119 $event = \core\event\webservice_token_created::create($params);
1120 $event->add_record_snapshot('external_tokens', $eventtoken);
1121 $event->trigger();
1122 } else {
1123 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1126 return $token;
1130 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1132 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1133 * In order to protect the privatetoken, we remove it from the event params.
1135 * @param stdClass $token token object
1136 * @since Moodle 3.2
1138 function external_log_token_request($token) {
1139 global $DB;
1141 $token->privatetoken = null;
1143 // Log token access.
1144 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1146 $params = array(
1147 'objectid' => $token->id,
1149 $event = \core\event\webservice_token_sent::create($params);
1150 $event->add_record_snapshot('external_tokens', $token);
1151 $event->trigger();
1155 * Singleton to handle the external settings.
1157 * We use singleton to encapsulate the "logic"
1159 * @package core_webservice
1160 * @copyright 2012 Jerome Mouneyrac
1161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1162 * @since Moodle 2.3
1164 class external_settings {
1166 /** @var object the singleton instance */
1167 public static $instance = null;
1169 /** @var boolean Should the external function return raw text or formatted */
1170 private $raw = false;
1172 /** @var boolean Should the external function filter the text */
1173 private $filter = false;
1175 /** @var boolean Should the external function rewrite plugin file url */
1176 private $fileurl = true;
1178 /** @var string In which file should the urls be rewritten */
1179 private $file = 'webservice/pluginfile.php';
1181 /** @var string The session lang */
1182 private $lang = '';
1185 * Constructor - protected - can not be instanciated
1187 protected function __construct() {
1188 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
1189 // For normal pages, the default should match the default for format_text.
1190 $this->filter = true;
1191 // Use pluginfile.php for web requests.
1192 $this->file = 'pluginfile.php';
1197 * Clone - private - can not be cloned
1199 private final function __clone() {
1203 * Return only one instance
1205 * @return \external_settings
1207 public static function get_instance() {
1208 if (self::$instance === null) {
1209 self::$instance = new external_settings;
1212 return self::$instance;
1216 * Set raw
1218 * @param boolean $raw
1220 public function set_raw($raw) {
1221 $this->raw = $raw;
1225 * Get raw
1227 * @return boolean
1229 public function get_raw() {
1230 return $this->raw;
1234 * Set filter
1236 * @param boolean $filter
1238 public function set_filter($filter) {
1239 $this->filter = $filter;
1243 * Get filter
1245 * @return boolean
1247 public function get_filter() {
1248 return $this->filter;
1252 * Set fileurl
1254 * @param boolean $fileurl
1256 public function set_fileurl($fileurl) {
1257 $this->fileurl = $fileurl;
1261 * Get fileurl
1263 * @return boolean
1265 public function get_fileurl() {
1266 return $this->fileurl;
1270 * Set file
1272 * @param string $file
1274 public function set_file($file) {
1275 $this->file = $file;
1279 * Get file
1281 * @return string
1283 public function get_file() {
1284 return $this->file;
1288 * Set lang
1290 * @param string $lang
1292 public function set_lang($lang) {
1293 $this->lang = $lang;
1297 * Get lang
1299 * @return string
1301 public function get_lang() {
1302 return $this->lang;
1307 * Utility functions for the external API.
1309 * @package core_webservice
1310 * @copyright 2015 Juan Leyva
1311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1312 * @since Moodle 3.0
1314 class external_util {
1317 * Validate a list of courses, returning the complete course objects for valid courses.
1319 * @param array $courseids A list of course ids
1320 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1321 * @param bool $addcontext True if the returned course object should include the full context object.
1322 * @return array An array of courses and the validation warnings
1324 public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
1325 // Delete duplicates.
1326 $courseids = array_unique($courseids);
1327 $warnings = array();
1329 // Remove courses which are not even requested.
1330 $courses = array_intersect_key($courses, array_flip($courseids));
1332 foreach ($courseids as $cid) {
1333 // Check the user can function in this context.
1334 try {
1335 $context = context_course::instance($cid);
1336 external_api::validate_context($context);
1338 if (!isset($courses[$cid])) {
1339 $courses[$cid] = get_course($cid);
1341 if ($addcontext) {
1342 $courses[$cid]->context = $context;
1344 } catch (Exception $e) {
1345 unset($courses[$cid]);
1346 $warnings[] = array(
1347 'item' => 'course',
1348 'itemid' => $cid,
1349 'warningcode' => '1',
1350 'message' => 'No access rights in course context'
1355 return array($courses, $warnings);
1359 * Returns all area files (optionally limited by itemid).
1361 * @param int $contextid context ID
1362 * @param string $component component
1363 * @param string $filearea file area
1364 * @param int $itemid item ID or all files if not specified
1365 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1366 * @return array of files, compatible with the external_files structure.
1367 * @since Moodle 3.2
1369 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1370 $files = array();
1371 $fs = get_file_storage();
1373 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1374 foreach ($areafiles as $areafile) {
1375 $file = array();
1376 $file['filename'] = $areafile->get_filename();
1377 $file['filepath'] = $areafile->get_filepath();
1378 $file['mimetype'] = $areafile->get_mimetype();
1379 $file['filesize'] = $areafile->get_filesize();
1380 $file['timemodified'] = $areafile->get_timemodified();
1381 $file['isexternalfile'] = $areafile->is_external_file();
1382 if ($file['isexternalfile']) {
1383 $file['repositorytype'] = $areafile->get_repository_type();
1385 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1386 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1387 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1388 $files[] = $file;
1391 return $files;
1396 * External structure representing a set of files.
1398 * @package core_webservice
1399 * @copyright 2016 Juan Leyva
1400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1401 * @since Moodle 3.2
1403 class external_files extends external_multiple_structure {
1406 * Constructor
1407 * @param string $desc Description for the multiple structure.
1408 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1410 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1412 parent::__construct(
1413 new external_single_structure(
1414 array(
1415 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1416 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1417 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1418 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1419 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1420 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1421 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1422 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
1424 'File.'
1426 $desc,
1427 $required
1432 * Return the properties ready to be used by an exporter.
1434 * @return array properties
1435 * @since Moodle 3.3
1437 public static function get_properties_for_exporter() {
1438 return [
1439 'filename' => array(
1440 'type' => PARAM_FILE,
1441 'description' => 'File name.',
1442 'optional' => true,
1443 'null' => NULL_NOT_ALLOWED,
1445 'filepath' => array(
1446 'type' => PARAM_PATH,
1447 'description' => 'File path.',
1448 'optional' => true,
1449 'null' => NULL_NOT_ALLOWED,
1451 'filesize' => array(
1452 'type' => PARAM_INT,
1453 'description' => 'File size.',
1454 'optional' => true,
1455 'null' => NULL_NOT_ALLOWED,
1457 'fileurl' => array(
1458 'type' => PARAM_URL,
1459 'description' => 'Downloadable file url.',
1460 'optional' => true,
1461 'null' => NULL_NOT_ALLOWED,
1463 'timemodified' => array(
1464 'type' => PARAM_INT,
1465 'description' => 'Time modified.',
1466 'optional' => true,
1467 'null' => NULL_NOT_ALLOWED,
1469 'mimetype' => array(
1470 'type' => PARAM_RAW,
1471 'description' => 'File mime type.',
1472 'optional' => true,
1473 'null' => NULL_NOT_ALLOWED,
1475 'isexternalfile' => array(
1476 'type' => PARAM_BOOL,
1477 'description' => 'Whether is an external file.',
1478 'optional' => true,
1479 'null' => NULL_NOT_ALLOWED,
1481 'repositorytype' => array(
1482 'type' => PARAM_PLUGIN,
1483 'description' => 'The repository type for the external files.',
1484 'optional' => true,
1485 'null' => NULL_ALLOWED,