Merge branch 'MDL-47162' of git://github.com/merrill-oakland/moodle
[moodle.git] / lib / externallib.php
bloba0c989591177b3a12cfd7c1833ff7a0c8e0d778b
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();
220 // Validate params, this also sorts the params properly, we need the correct order in the next part.
221 $callable = array($externalfunctioninfo->classname, 'validate_parameters');
222 $params = call_user_func($callable,
223 $externalfunctioninfo->parameters_desc,
224 $args);
226 // Execute - gulp!
227 $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
228 $result = call_user_func_array($callable,
229 array_values($params));
231 // Validate the return parameters.
232 if ($externalfunctioninfo->returns_desc !== null) {
233 $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
234 $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
237 $response['error'] = false;
238 $response['data'] = $result;
239 } catch (Exception $e) {
240 $exception = get_exception_info($e);
241 unset($exception->a);
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] = self::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] = self::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[] = self::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] = self::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] = self::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[] = self::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');
514 * Common ancestor of all parameter description classes
516 * @package core_webservice
517 * @copyright 2009 Petr Skodak
518 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
519 * @since Moodle 2.0
521 abstract class external_description {
522 /** @var string Description of element */
523 public $desc;
525 /** @var bool Element value required, null not allowed */
526 public $required;
528 /** @var mixed Default value */
529 public $default;
532 * Contructor
534 * @param string $desc
535 * @param bool $required
536 * @param mixed $default
537 * @since Moodle 2.0
539 public function __construct($desc, $required, $default) {
540 $this->desc = $desc;
541 $this->required = $required;
542 $this->default = $default;
547 * Scalar value description class
549 * @package core_webservice
550 * @copyright 2009 Petr Skodak
551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 * @since Moodle 2.0
554 class external_value extends external_description {
556 /** @var mixed Value type PARAM_XX */
557 public $type;
559 /** @var bool Allow null values */
560 public $allownull;
563 * Constructor
565 * @param mixed $type
566 * @param string $desc
567 * @param bool $required
568 * @param mixed $default
569 * @param bool $allownull
570 * @since Moodle 2.0
572 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
573 $default=null, $allownull=NULL_ALLOWED) {
574 parent::__construct($desc, $required, $default);
575 $this->type = $type;
576 $this->allownull = $allownull;
581 * Associative array description class
583 * @package core_webservice
584 * @copyright 2009 Petr Skodak
585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
586 * @since Moodle 2.0
588 class external_single_structure extends external_description {
590 /** @var array Description of array keys key=>external_description */
591 public $keys;
594 * Constructor
596 * @param array $keys
597 * @param string $desc
598 * @param bool $required
599 * @param array $default
600 * @since Moodle 2.0
602 public function __construct(array $keys, $desc='',
603 $required=VALUE_REQUIRED, $default=null) {
604 parent::__construct($desc, $required, $default);
605 $this->keys = $keys;
610 * Bulk array description class.
612 * @package core_webservice
613 * @copyright 2009 Petr Skodak
614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
615 * @since Moodle 2.0
617 class external_multiple_structure extends external_description {
619 /** @var external_description content */
620 public $content;
623 * Constructor
625 * @param external_description $content
626 * @param string $desc
627 * @param bool $required
628 * @param array $default
629 * @since Moodle 2.0
631 public function __construct(external_description $content, $desc='',
632 $required=VALUE_REQUIRED, $default=null) {
633 parent::__construct($desc, $required, $default);
634 $this->content = $content;
639 * Description of top level - PHP function parameters.
641 * @package core_webservice
642 * @copyright 2009 Petr Skodak
643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
644 * @since Moodle 2.0
646 class external_function_parameters extends external_single_structure {
649 * Constructor - does extra checking to prevent top level optional parameters.
651 * @param array $keys
652 * @param string $desc
653 * @param bool $required
654 * @param array $default
656 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
657 global $CFG;
659 if ($CFG->debugdeveloper) {
660 foreach ($keys as $key => $value) {
661 if ($value instanceof external_value) {
662 if ($value->required == VALUE_OPTIONAL) {
663 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
664 break;
669 parent::__construct($keys, $desc, $required, $default);
674 * Generate a token
676 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
677 * @param stdClass|int $serviceorid service linked to the token
678 * @param int $userid user linked to the token
679 * @param stdClass|int $contextorid
680 * @param int $validuntil date when the token expired
681 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
682 * @return string generated token
683 * @author 2010 Jamie Pratt
684 * @since Moodle 2.0
686 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
687 global $DB, $USER;
688 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
689 $numtries = 0;
690 do {
691 $numtries ++;
692 $generatedtoken = md5(uniqid(rand(),1));
693 if ($numtries > 5){
694 throw new moodle_exception('tokengenerationfailed');
696 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
697 $newtoken = new stdClass();
698 $newtoken->token = $generatedtoken;
699 if (!is_object($serviceorid)){
700 $service = $DB->get_record('external_services', array('id' => $serviceorid));
701 } else {
702 $service = $serviceorid;
704 if (!is_object($contextorid)){
705 $context = context::instance_by_id($contextorid, MUST_EXIST);
706 } else {
707 $context = $contextorid;
709 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
710 $newtoken->externalserviceid = $service->id;
711 } else {
712 throw new moodle_exception('nocapabilitytousethisservice');
714 $newtoken->tokentype = $tokentype;
715 $newtoken->userid = $userid;
716 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
717 $newtoken->sid = session_id();
720 $newtoken->contextid = $context->id;
721 $newtoken->creatorid = $USER->id;
722 $newtoken->timecreated = time();
723 $newtoken->validuntil = $validuntil;
724 if (!empty($iprestriction)) {
725 $newtoken->iprestriction = $iprestriction;
727 $newtoken->privatetoken = null;
728 $DB->insert_record('external_tokens', $newtoken);
729 return $newtoken->token;
733 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
734 * with the Moodle server through web services. The token is linked to the current session for the current page request.
735 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
736 * returned token will be somehow passed into the client app being embedded in the page.
738 * @param string $servicename name of the web service. Service name as defined in db/services.php
739 * @param int $context context within which the web service can operate.
740 * @return int returns token id.
741 * @since Moodle 2.0
743 function external_create_service_token($servicename, $context){
744 global $USER, $DB;
745 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
746 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
750 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
752 * @param string $component name of component (moodle, mod_assignment, etc.)
754 function external_delete_descriptions($component) {
755 global $DB;
757 $params = array($component);
759 $DB->delete_records_select('external_tokens',
760 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
761 $DB->delete_records_select('external_services_users',
762 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
763 $DB->delete_records_select('external_services_functions',
764 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
765 $DB->delete_records('external_services', array('component'=>$component));
766 $DB->delete_records('external_functions', array('component'=>$component));
770 * Standard Moodle web service warnings
772 * @package core_webservice
773 * @copyright 2012 Jerome Mouneyrac
774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 * @since Moodle 2.3
777 class external_warnings extends external_multiple_structure {
780 * Constructor
782 * @since Moodle 2.3
784 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
785 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
787 parent::__construct(
788 new external_single_structure(
789 array(
790 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
791 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
792 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
793 'message' => new external_value(PARAM_TEXT,
794 'untranslated english message to explain the warning')
795 ), 'warning'),
796 'list of warnings', VALUE_OPTIONAL);
801 * A pre-filled external_value class for text format.
803 * Default is FORMAT_HTML
804 * This should be used all the time in external xxx_params()/xxx_returns functions
805 * as it is the standard way to implement text format param/return values.
807 * @package core_webservice
808 * @copyright 2012 Jerome Mouneyrac
809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
810 * @since Moodle 2.3
812 class external_format_value extends external_value {
815 * Constructor
817 * @param string $textfieldname Name of the text field
818 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
819 * @param int $default Default value.
820 * @since Moodle 2.3
822 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
824 if ($default == null && $required == VALUE_DEFAULT) {
825 $default = FORMAT_HTML;
828 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
829 . FORMAT_MOODLE . ' = MOODLE, '
830 . FORMAT_PLAIN . ' = PLAIN or '
831 . FORMAT_MARKDOWN . ' = MARKDOWN)';
833 parent::__construct(PARAM_INT, $desc, $required, $default);
838 * Validate text field format against known FORMAT_XXX
840 * @param array $format the format to validate
841 * @return the validated format
842 * @throws coding_exception
843 * @since Moodle 2.3
845 function external_validate_format($format) {
846 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
847 if (!in_array($format, $allowedformats)) {
848 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
849 'The format with value=' . $format . ' is not supported by this Moodle site');
851 return $format;
855 * Format the string to be returned properly as requested by the either the web service server,
856 * either by an internally call.
857 * The caller can change the format (raw) with the external_settings singleton
858 * All web service servers must set this singleton when parsing the $_GET and $_POST.
860 * <pre>
861 * Options are the same that in {@link format_string()} with some changes:
862 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
863 * </pre>
865 * @param string $str The string to be filtered. Should be plain text, expect
866 * possibly for multilang tags.
867 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
868 * @param int $contextid The id of the context for the string (affects filters).
869 * @param array $options options array/object or courseid
870 * @return string text
871 * @since Moodle 3.0
873 function external_format_string($str, $contextid, $striplinks = true, $options = array()) {
875 // Get settings (singleton).
876 $settings = external_settings::get_instance();
877 if (empty($contextid)) {
878 throw new coding_exception('contextid is required');
881 if (!$settings->get_raw()) {
882 $context = context::instance_by_id($contextid);
883 $options['context'] = $context;
884 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
885 $str = format_string($str, $striplinks, $options);
888 return $str;
892 * Format the text to be returned properly as requested by the either the web service server,
893 * either by an internally call.
894 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
895 * All web service servers must set this singleton when parsing the $_GET and $_POST.
897 * <pre>
898 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
899 * trusted : If true the string won't be cleaned. Default false.
900 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
901 * nocache : If true the string will not be cached and will be formatted every call. Default false.
902 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
903 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
904 * Default changed because div tags are not commonly needed.
905 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
906 * context : Not used! Using contextid parameter instead.
907 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
908 * returned. Default false.
909 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
910 * format_text) true. Default changed id attributes are commonly needed.
911 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
912 * </pre>
914 * @param string $text The content that may contain ULRs in need of rewriting.
915 * @param int $textformat The text format.
916 * @param int $contextid This parameter and the next two identify the file area to use.
917 * @param string $component
918 * @param string $filearea helps identify the file area.
919 * @param int $itemid helps identify the file area.
920 * @param object/array $options text formatting options
921 * @return array text + textformat
922 * @since Moodle 2.3
923 * @since Moodle 3.2 component, filearea and itemid are optional parameters
925 function external_format_text($text, $textformat, $contextid, $component = null, $filearea = null, $itemid = null,
926 $options = null) {
927 global $CFG;
929 // Get settings (singleton).
930 $settings = external_settings::get_instance();
932 if ($component and $filearea and $settings->get_fileurl()) {
933 require_once($CFG->libdir . "/filelib.php");
934 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
937 if (!$settings->get_raw()) {
938 $options = (array)$options;
940 // If context is passed in options, check that is the same to show a debug message.
941 if (isset($options['context'])) {
942 if ((is_object($options['context']) && $options['context']->id != $contextid)
943 || (!is_object($options['context']) && $options['context'] != $contextid)) {
944 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
945 Using $contextid parameter...', DEBUG_DEVELOPER);
949 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
950 $options['para'] = isset($options['para']) ? $options['para'] : false;
951 $options['context'] = context::instance_by_id($contextid);
952 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
954 $text = format_text($text, $textformat, $options);
955 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
958 return array($text, $textformat);
962 * Generate or return an existing token for the current authenticated user.
963 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
965 * @param stdClass $service external service object
966 * @return stdClass token object
967 * @since Moodle 3.2
968 * @throws moodle_exception
970 function external_generate_token_for_current_user($service) {
971 global $DB, $USER;
973 core_user::require_active_user($USER, true, true);
975 // Check if there is any required system capability.
976 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
977 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
980 // Specific checks related to user restricted service.
981 if ($service->restrictedusers) {
982 $authoriseduser = $DB->get_record('external_services_users',
983 array('externalserviceid' => $service->id, 'userid' => $USER->id));
985 if (empty($authoriseduser)) {
986 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
989 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
990 throw new moodle_exception('invalidtimedtoken', 'webservice');
993 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
994 throw new moodle_exception('invalidiptoken', 'webservice');
998 // Check if a token has already been created for this user and this service.
999 $conditions = array(
1000 'userid' => $USER->id,
1001 'externalserviceid' => $service->id,
1002 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1004 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1006 // A bit of sanity checks.
1007 foreach ($tokens as $key => $token) {
1009 // Checks related to a specific token. (script execution continue).
1010 $unsettoken = false;
1011 // If sid is set then there must be a valid associated session no matter the token type.
1012 if (!empty($token->sid)) {
1013 if (!\core\session\manager::session_exists($token->sid)) {
1014 // This token will never be valid anymore, delete it.
1015 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1016 $unsettoken = true;
1020 // Remove token is not valid anymore.
1021 if (!empty($token->validuntil) and $token->validuntil < time()) {
1022 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1023 $unsettoken = true;
1026 // Remove token if its ip not in whitelist.
1027 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1028 $unsettoken = true;
1031 if ($unsettoken) {
1032 unset($tokens[$key]);
1036 // If some valid tokens exist then use the most recent.
1037 if (count($tokens) > 0) {
1038 $token = array_pop($tokens);
1039 } else {
1040 $context = context_system::instance();
1041 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1043 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1044 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1046 // Create a new token.
1047 $token = new stdClass;
1048 $token->token = md5(uniqid(rand(), 1));
1049 $token->userid = $USER->id;
1050 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1051 $token->contextid = context_system::instance()->id;
1052 $token->creatorid = $USER->id;
1053 $token->timecreated = time();
1054 $token->externalserviceid = $service->id;
1055 // MDL-43119 Token valid for 3 months (12 weeks).
1056 $token->validuntil = $token->timecreated + 12 * WEEKSECS;
1057 // Generate the private token, it must be transmitted only via https.
1058 $token->privatetoken = random_string(64);
1059 $token->id = $DB->insert_record('external_tokens', $token);
1061 $params = array(
1062 'objectid' => $token->id,
1063 'relateduserid' => $USER->id,
1064 'other' => array(
1065 'auto' => true
1068 $event = \core\event\webservice_token_created::create($params);
1069 $event->add_record_snapshot('external_tokens', $token);
1070 $event->trigger();
1071 } else {
1072 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1075 return $token;
1080 * Singleton to handle the external settings.
1082 * We use singleton to encapsulate the "logic"
1084 * @package core_webservice
1085 * @copyright 2012 Jerome Mouneyrac
1086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1087 * @since Moodle 2.3
1089 class external_settings {
1091 /** @var object the singleton instance */
1092 public static $instance = null;
1094 /** @var boolean Should the external function return raw text or formatted */
1095 private $raw = false;
1097 /** @var boolean Should the external function filter the text */
1098 private $filter = false;
1100 /** @var boolean Should the external function rewrite plugin file url */
1101 private $fileurl = true;
1103 /** @var string In which file should the urls be rewritten */
1104 private $file = 'webservice/pluginfile.php';
1107 * Constructor - protected - can not be instanciated
1109 protected function __construct() {
1110 if (!defined('AJAX_SCRIPT') && !defined('CLI_SCRIPT') && !defined('WS_SERVER')) {
1111 // For normal pages, the default should match the default for format_text.
1112 $this->filter = true;
1117 * Clone - private - can not be cloned
1119 private final function __clone() {
1123 * Return only one instance
1125 * @return object
1127 public static function get_instance() {
1128 if (self::$instance === null) {
1129 self::$instance = new external_settings;
1132 return self::$instance;
1136 * Set raw
1138 * @param boolean $raw
1140 public function set_raw($raw) {
1141 $this->raw = $raw;
1145 * Get raw
1147 * @return boolean
1149 public function get_raw() {
1150 return $this->raw;
1154 * Set filter
1156 * @param boolean $filter
1158 public function set_filter($filter) {
1159 $this->filter = $filter;
1163 * Get filter
1165 * @return boolean
1167 public function get_filter() {
1168 return $this->filter;
1172 * Set fileurl
1174 * @param boolean $fileurl
1176 public function set_fileurl($fileurl) {
1177 $this->fileurl = $fileurl;
1181 * Get fileurl
1183 * @return boolean
1185 public function get_fileurl() {
1186 return $this->fileurl;
1190 * Set file
1192 * @param string $file
1194 public function set_file($file) {
1195 $this->file = $file;
1199 * Get file
1201 * @return string
1203 public function get_file() {
1204 return $this->file;
1209 * Utility functions for the external API.
1211 * @package core_webservice
1212 * @copyright 2015 Juan Leyva
1213 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1214 * @since Moodle 3.0
1216 class external_util {
1219 * Validate a list of courses, returning the complete course objects for valid courses.
1221 * @param array $courseids A list of course ids
1222 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1223 * @param bool $addcontext True if the returned course object should include the full context object.
1224 * @return array An array of courses and the validation warnings
1226 public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
1227 // Delete duplicates.
1228 $courseids = array_unique($courseids);
1229 $warnings = array();
1231 // Remove courses which are not even requested.
1232 $courses = array_intersect_key($courses, array_flip($courseids));
1234 foreach ($courseids as $cid) {
1235 // Check the user can function in this context.
1236 try {
1237 $context = context_course::instance($cid);
1238 external_api::validate_context($context);
1240 if (!isset($courses[$cid])) {
1241 $courses[$cid] = get_course($cid);
1243 if ($addcontext) {
1244 $courses[$cid]->context = $context;
1246 } catch (Exception $e) {
1247 unset($courses[$cid]);
1248 $warnings[] = array(
1249 'item' => 'course',
1250 'itemid' => $cid,
1251 'warningcode' => '1',
1252 'message' => 'No access rights in course context'
1257 return array($courses, $warnings);
1261 * Returns all area files (optionally limited by itemid).
1263 * @param int $contextid context ID
1264 * @param string $component component
1265 * @param string $filearea file area
1266 * @param int $itemid item ID or all files if not specified
1267 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1268 * @return array of files, compatible with the external_files structure.
1269 * @since Moodle 3.2
1271 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1272 $files = array();
1273 $fs = get_file_storage();
1275 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1276 foreach ($areafiles as $areafile) {
1277 $file = array();
1278 $file['filename'] = $areafile->get_filename();
1279 $file['filepath'] = $areafile->get_filepath();
1280 $file['mimetype'] = $areafile->get_mimetype();
1281 $file['filesize'] = $areafile->get_filesize();
1282 $file['timemodified'] = $areafile->get_timemodified();
1283 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1284 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1285 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1286 $files[] = $file;
1289 return $files;
1294 * External structure representing a set of files.
1296 * @package core_webservice
1297 * @copyright 2016 Juan Leyva
1298 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1299 * @since Moodle 3.2
1301 class external_files extends external_multiple_structure {
1304 * Constructor
1305 * @param string $desc Description for the multiple structure.
1306 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1308 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1310 parent::__construct(
1311 new external_single_structure(
1312 array(
1313 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1314 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1315 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1316 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1317 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1318 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1320 'File.'
1322 $desc,
1323 $required