Merge branch 'MDL-60302-master' of git://github.com/jleyva/moodle
[moodle.git] / lib / externallib.php
blobe49aaf27c824fc07ab1d92274c1784747828ea39
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 int $contextid The id of the context for the string (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, $contextid, $striplinks = true, $options = array()) {
906 // Get settings (singleton).
907 $settings = external_settings::get_instance();
908 if (empty($contextid)) {
909 throw new coding_exception('contextid is required');
912 if (!$settings->get_raw()) {
913 $context = context::instance_by_id($contextid);
914 $options['context'] = $context;
915 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
916 $str = format_string($str, $striplinks, $options);
919 return $str;
923 * Format the text to be returned properly as requested by the either the web service server,
924 * either by an internally call.
925 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
926 * All web service servers must set this singleton when parsing the $_GET and $_POST.
928 * <pre>
929 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
930 * trusted : If true the string won't be cleaned. Default false.
931 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
932 * nocache : If true the string will not be cached and will be formatted every call. Default false.
933 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
934 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
935 * Default changed because div tags are not commonly needed.
936 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
937 * context : Not used! Using contextid parameter instead.
938 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
939 * returned. Default false.
940 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
941 * format_text) true. Default changed id attributes are commonly needed.
942 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
943 * </pre>
945 * @param string $text The content that may contain ULRs in need of rewriting.
946 * @param int $textformat The text format.
947 * @param int $contextid This parameter and the next two identify the file area to use.
948 * @param string $component
949 * @param string $filearea helps identify the file area.
950 * @param int $itemid helps identify the file area.
951 * @param object/array $options text formatting options
952 * @return array text + textformat
953 * @since Moodle 2.3
954 * @since Moodle 3.2 component, filearea and itemid are optional parameters
956 function external_format_text($text, $textformat, $contextid, $component = null, $filearea = null, $itemid = null,
957 $options = null) {
958 global $CFG;
960 // Get settings (singleton).
961 $settings = external_settings::get_instance();
963 if ($component and $filearea and $settings->get_fileurl()) {
964 require_once($CFG->libdir . "/filelib.php");
965 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
968 if (!$settings->get_raw()) {
969 $options = (array)$options;
971 // If context is passed in options, check that is the same to show a debug message.
972 if (isset($options['context'])) {
973 if ((is_object($options['context']) && $options['context']->id != $contextid)
974 || (!is_object($options['context']) && $options['context'] != $contextid)) {
975 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
976 Using $contextid parameter...', DEBUG_DEVELOPER);
980 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
981 $options['para'] = isset($options['para']) ? $options['para'] : false;
982 $options['context'] = context::instance_by_id($contextid);
983 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
985 $text = format_text($text, $textformat, $options);
986 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
989 return array($text, $textformat);
993 * Generate or return an existing token for the current authenticated user.
994 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
996 * @param stdClass $service external service object
997 * @return stdClass token object
998 * @since Moodle 3.2
999 * @throws moodle_exception
1001 function external_generate_token_for_current_user($service) {
1002 global $DB, $USER, $CFG;
1004 core_user::require_active_user($USER, true, true);
1006 // Check if there is any required system capability.
1007 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1008 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1011 // Specific checks related to user restricted service.
1012 if ($service->restrictedusers) {
1013 $authoriseduser = $DB->get_record('external_services_users',
1014 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1016 if (empty($authoriseduser)) {
1017 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1020 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1021 throw new moodle_exception('invalidtimedtoken', 'webservice');
1024 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1025 throw new moodle_exception('invalidiptoken', 'webservice');
1029 // Check if a token has already been created for this user and this service.
1030 $conditions = array(
1031 'userid' => $USER->id,
1032 'externalserviceid' => $service->id,
1033 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1035 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1037 // A bit of sanity checks.
1038 foreach ($tokens as $key => $token) {
1040 // Checks related to a specific token. (script execution continue).
1041 $unsettoken = false;
1042 // If sid is set then there must be a valid associated session no matter the token type.
1043 if (!empty($token->sid)) {
1044 if (!\core\session\manager::session_exists($token->sid)) {
1045 // This token will never be valid anymore, delete it.
1046 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1047 $unsettoken = true;
1051 // Remove token is not valid anymore.
1052 if (!empty($token->validuntil) and $token->validuntil < time()) {
1053 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1054 $unsettoken = true;
1057 // Remove token if its ip not in whitelist.
1058 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1059 $unsettoken = true;
1062 if ($unsettoken) {
1063 unset($tokens[$key]);
1067 // If some valid tokens exist then use the most recent.
1068 if (count($tokens) > 0) {
1069 $token = array_pop($tokens);
1070 } else {
1071 $context = context_system::instance();
1072 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1074 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1075 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1077 // Create a new token.
1078 $token = new stdClass;
1079 $token->token = md5(uniqid(rand(), 1));
1080 $token->userid = $USER->id;
1081 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1082 $token->contextid = context_system::instance()->id;
1083 $token->creatorid = $USER->id;
1084 $token->timecreated = time();
1085 $token->externalserviceid = $service->id;
1086 // By default tokens are valid for 12 weeks.
1087 $token->validuntil = $token->timecreated + $CFG->tokenduration;
1088 $token->iprestriction = null;
1089 $token->sid = null;
1090 $token->lastaccess = null;
1091 // Generate the private token, it must be transmitted only via https.
1092 $token->privatetoken = random_string(64);
1093 $token->id = $DB->insert_record('external_tokens', $token);
1095 $eventtoken = clone $token;
1096 $eventtoken->privatetoken = null;
1097 $params = array(
1098 'objectid' => $eventtoken->id,
1099 'relateduserid' => $USER->id,
1100 'other' => array(
1101 'auto' => true
1104 $event = \core\event\webservice_token_created::create($params);
1105 $event->add_record_snapshot('external_tokens', $eventtoken);
1106 $event->trigger();
1107 } else {
1108 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1111 return $token;
1115 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1117 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1118 * In order to protect the privatetoken, we remove it from the event params.
1120 * @param stdClass $token token object
1121 * @since Moodle 3.2
1123 function external_log_token_request($token) {
1124 global $DB;
1126 $token->privatetoken = null;
1128 // Log token access.
1129 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1131 $params = array(
1132 'objectid' => $token->id,
1134 $event = \core\event\webservice_token_sent::create($params);
1135 $event->add_record_snapshot('external_tokens', $token);
1136 $event->trigger();
1140 * Singleton to handle the external settings.
1142 * We use singleton to encapsulate the "logic"
1144 * @package core_webservice
1145 * @copyright 2012 Jerome Mouneyrac
1146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1147 * @since Moodle 2.3
1149 class external_settings {
1151 /** @var object the singleton instance */
1152 public static $instance = null;
1154 /** @var boolean Should the external function return raw text or formatted */
1155 private $raw = false;
1157 /** @var boolean Should the external function filter the text */
1158 private $filter = false;
1160 /** @var boolean Should the external function rewrite plugin file url */
1161 private $fileurl = true;
1163 /** @var string In which file should the urls be rewritten */
1164 private $file = 'webservice/pluginfile.php';
1167 * Constructor - protected - can not be instanciated
1169 protected function __construct() {
1170 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
1171 // For normal pages, the default should match the default for format_text.
1172 $this->filter = true;
1173 // Use pluginfile.php for web requests.
1174 $this->file = 'pluginfile.php';
1179 * Clone - private - can not be cloned
1181 private final function __clone() {
1185 * Return only one instance
1187 * @return \external_settings
1189 public static function get_instance() {
1190 if (self::$instance === null) {
1191 self::$instance = new external_settings;
1194 return self::$instance;
1198 * Set raw
1200 * @param boolean $raw
1202 public function set_raw($raw) {
1203 $this->raw = $raw;
1207 * Get raw
1209 * @return boolean
1211 public function get_raw() {
1212 return $this->raw;
1216 * Set filter
1218 * @param boolean $filter
1220 public function set_filter($filter) {
1221 $this->filter = $filter;
1225 * Get filter
1227 * @return boolean
1229 public function get_filter() {
1230 return $this->filter;
1234 * Set fileurl
1236 * @param boolean $fileurl
1238 public function set_fileurl($fileurl) {
1239 $this->fileurl = $fileurl;
1243 * Get fileurl
1245 * @return boolean
1247 public function get_fileurl() {
1248 return $this->fileurl;
1252 * Set file
1254 * @param string $file
1256 public function set_file($file) {
1257 $this->file = $file;
1261 * Get file
1263 * @return string
1265 public function get_file() {
1266 return $this->file;
1271 * Utility functions for the external API.
1273 * @package core_webservice
1274 * @copyright 2015 Juan Leyva
1275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1276 * @since Moodle 3.0
1278 class external_util {
1281 * Validate a list of courses, returning the complete course objects for valid courses.
1283 * @param array $courseids A list of course ids
1284 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1285 * @param bool $addcontext True if the returned course object should include the full context object.
1286 * @return array An array of courses and the validation warnings
1288 public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
1289 // Delete duplicates.
1290 $courseids = array_unique($courseids);
1291 $warnings = array();
1293 // Remove courses which are not even requested.
1294 $courses = array_intersect_key($courses, array_flip($courseids));
1296 foreach ($courseids as $cid) {
1297 // Check the user can function in this context.
1298 try {
1299 $context = context_course::instance($cid);
1300 external_api::validate_context($context);
1302 if (!isset($courses[$cid])) {
1303 $courses[$cid] = get_course($cid);
1305 if ($addcontext) {
1306 $courses[$cid]->context = $context;
1308 } catch (Exception $e) {
1309 unset($courses[$cid]);
1310 $warnings[] = array(
1311 'item' => 'course',
1312 'itemid' => $cid,
1313 'warningcode' => '1',
1314 'message' => 'No access rights in course context'
1319 return array($courses, $warnings);
1323 * Returns all area files (optionally limited by itemid).
1325 * @param int $contextid context ID
1326 * @param string $component component
1327 * @param string $filearea file area
1328 * @param int $itemid item ID or all files if not specified
1329 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1330 * @return array of files, compatible with the external_files structure.
1331 * @since Moodle 3.2
1333 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1334 $files = array();
1335 $fs = get_file_storage();
1337 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1338 foreach ($areafiles as $areafile) {
1339 $file = array();
1340 $file['filename'] = $areafile->get_filename();
1341 $file['filepath'] = $areafile->get_filepath();
1342 $file['mimetype'] = $areafile->get_mimetype();
1343 $file['filesize'] = $areafile->get_filesize();
1344 $file['timemodified'] = $areafile->get_timemodified();
1345 $file['isexternalfile'] = $areafile->is_external_file();
1346 if ($file['isexternalfile']) {
1347 $file['repositorytype'] = $areafile->get_repository_type();
1349 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1350 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1351 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1352 $files[] = $file;
1355 return $files;
1360 * External structure representing a set of files.
1362 * @package core_webservice
1363 * @copyright 2016 Juan Leyva
1364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1365 * @since Moodle 3.2
1367 class external_files extends external_multiple_structure {
1370 * Constructor
1371 * @param string $desc Description for the multiple structure.
1372 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1374 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1376 parent::__construct(
1377 new external_single_structure(
1378 array(
1379 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1380 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1381 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1382 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1383 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1384 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1385 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1386 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
1388 'File.'
1390 $desc,
1391 $required
1396 * Return the properties ready to be used by an exporter.
1398 * @return array properties
1399 * @since Moodle 3.3
1401 public static function get_properties_for_exporter() {
1402 return [
1403 'filename' => array(
1404 'type' => PARAM_FILE,
1405 'description' => 'File name.',
1406 'optional' => true,
1407 'null' => NULL_NOT_ALLOWED,
1409 'filepath' => array(
1410 'type' => PARAM_PATH,
1411 'description' => 'File path.',
1412 'optional' => true,
1413 'null' => NULL_NOT_ALLOWED,
1415 'filesize' => array(
1416 'type' => PARAM_INT,
1417 'description' => 'File size.',
1418 'optional' => true,
1419 'null' => NULL_NOT_ALLOWED,
1421 'fileurl' => array(
1422 'type' => PARAM_URL,
1423 'description' => 'Downloadable file url.',
1424 'optional' => true,
1425 'null' => NULL_NOT_ALLOWED,
1427 'timemodified' => array(
1428 'type' => PARAM_INT,
1429 'description' => 'Time modified.',
1430 'optional' => true,
1431 'null' => NULL_NOT_ALLOWED,
1433 'mimetype' => array(
1434 'type' => PARAM_RAW,
1435 'description' => 'File mime type.',
1436 'optional' => true,
1437 'null' => NULL_NOT_ALLOWED,
1439 'isexternalfile' => array(
1440 'type' => PARAM_BOOL,
1441 'description' => 'Whether is an external file.',
1442 'optional' => true,
1443 'null' => NULL_NOT_ALLOWED,
1445 'repositorytype' => array(
1446 'type' => PARAM_PLUGIN,
1447 'description' => 'The repository type for the external files.',
1448 'optional' => true,
1449 'null' => NULL_ALLOWED,