MDL-68971 webservice: errors should give enough info to find the problem
[moodle.git] / lib / externallib.php
CommitLineData
9a0df45a 1<?php
9a0df45a 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.
13//
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/>.
16
4615817d 17
9a0df45a 18/**
19 * Support for external API
20 *
4615817d
JM
21 * @package core_webservice
22 * @copyright 2009 Petr Skodak
9a0df45a 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
78bfb562 26defined('MOODLE_INTERNAL') || die();
1942103f 27
9a0df45a 28/**
4615817d
JM
29 * Exception indicating user is not allowed to use external function in the current context.
30 *
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
9a0df45a 35 */
36class restricted_context_exception extends moodle_exception {
37 /**
38 * Constructor
4615817d
JM
39 *
40 * @since Moodle 2.0
9a0df45a 41 */
42 function __construct() {
43 parent::__construct('restrictedcontextexception', 'error');
44 }
45}
46
47/**
48 * Base class for external api methods.
4615817d
JM
49 *
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
9a0df45a 54 */
55class external_api {
4615817d
JM
56
57 /** @var stdClass context where the function calls will be restricted */
9a0df45a 58 private static $contextrestriction;
59
56fa860e
DW
60 /**
61 * Returns detailed function information
62 *
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
68 */
69 public static function external_function_info($function, $strictness=MUST_EXIST) {
70 global $DB, $CFG;
71
72 if (!is_object($function)) {
73 if (!$function = $DB->get_record('external_functions', array('name' => $function), '*', $strictness)) {
74 return false;
75 }
76 }
77
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;
85 }
86 if (!file_exists($function->classpath)) {
5f26bdc5
TH
87 throw new coding_exception('Cannot find file ' . $function->classpath .
88 ' with external function implementation');
56fa860e
DW
89 }
90 require_once($function->classpath);
91 if (!class_exists($function->classname)) {
5f26bdc5 92 throw new coding_exception('Cannot find external class ' . $function->classname);
56fa860e
DW
93 }
94 }
95
96 $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
97 $function->parameters_method = $function->methodname.'_parameters';
98 $function->returns_method = $function->methodname.'_returns';
99 $function->deprecated_method = $function->methodname.'_is_deprecated';
100
101 // Make sure the implementaion class is ok.
102 if (!method_exists($function->classname, $function->methodname)) {
5f26bdc5
TH
103 throw new coding_exception('Missing implementation method ' .
104 $function->classname . '::' . $function->methodname);
56fa860e
DW
105 }
106 if (!method_exists($function->classname, $function->parameters_method)) {
5f26bdc5
TH
107 throw new coding_exception('Missing parameters description method ' .
108 $function->classname . '::' . $function->parameters_method);
56fa860e
DW
109 }
110 if (!method_exists($function->classname, $function->returns_method)) {
5f26bdc5
TH
111 throw new coding_exception('Missing returned values description method ' .
112 $function->classname . '::' . $function->returns_method);
56fa860e
DW
113 }
114 if (method_exists($function->classname, $function->deprecated_method)) {
115 if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
116 $function->deprecated = true;
117 }
118 }
119 $function->allowed_from_ajax = false;
120
121 // Fetch the parameters description.
122 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
123 if (!($function->parameters_desc instanceof external_function_parameters)) {
5f26bdc5
TH
124 throw new coding_exception($function->classname . '::' . $function->parameters_method .
125 ' did not return a valid external_function_parameters object.');
56fa860e
DW
126 }
127
128 // Fetch the return values description.
129 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
130 // Null means void result or result is ignored.
131 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
5f26bdc5
TH
132 throw new coding_exception($function->classname . '::' . $function->returns_method .
133 ' did not return a valid external_description object');
56fa860e
DW
134 }
135
136 // Now get the function description.
137
138 // TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
139 // easy to understand descriptions in admin UI,
140 // on the other hand this is still a bit in a flux and we need to find some new naming
141 // conventions for these descriptions in lang packs.
142 $function->description = null;
143 $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
144 if (file_exists($servicesfile)) {
145 $functions = null;
146 include($servicesfile);
147 if (isset($functions[$function->name]['description'])) {
148 $function->description = $functions[$function->name]['description'];
149 }
150 if (isset($functions[$function->name]['testclientpath'])) {
151 $function->testclientpath = $functions[$function->name]['testclientpath'];
152 }
153 if (isset($functions[$function->name]['type'])) {
154 $function->type = $functions[$function->name]['type'];
155 }
156 if (isset($functions[$function->name]['ajax'])) {
157 $function->allowed_from_ajax = $functions[$function->name]['ajax'];
158 } else if (method_exists($function->classname, $function->ajax_method)) {
159 if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
160 debugging('External function ' . $function->ajax_method . '() function is deprecated.' .
161 'Set ajax=>true in db/service.php instead.', DEBUG_DEVELOPER);
162 $function->allowed_from_ajax = true;
163 }
164 }
165 if (isset($functions[$function->name]['loginrequired'])) {
166 $function->loginrequired = $functions[$function->name]['loginrequired'];
167 } else {
168 $function->loginrequired = true;
169 }
4400ed3e
MN
170 if (isset($functions[$function->name]['readonlysession'])) {
171 $function->readonlysession = $functions[$function->name]['readonlysession'];
82da35fd 172 } else {
4400ed3e 173 $function->readonlysession = false;
82da35fd 174 }
56fa860e
DW
175 }
176
177 return $function;
178 }
179
180 /**
181 * Call an external function validating all params/returns correctly.
182 *
183 * Note that an external function may modify the state of the current page, so this wrapper
184 * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
185 *
186 * @param string $function A webservice function name.
187 * @param array $args Params array (named params)
188 * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
189 * @return array containing keys for error (bool), exception and data.
190 */
191 public static function call_external_function($function, $args, $ajaxonly=false) {
192 global $PAGE, $COURSE, $CFG, $SITE;
193
194 require_once($CFG->libdir . "/pagelib.php");
195
096c46bb 196 $externalfunctioninfo = static::external_function_info($function);
56fa860e 197
82da35fd 198 // Eventually this should shift into the various handlers and not be handled via config.
4400ed3e
MN
199 $readonlysession = $externalfunctioninfo->readonlysession ?? false;
200 if (!$readonlysession || empty($CFG->enable_read_only_sessions)) {
82da35fd
AE
201 \core\session\manager::restart_with_write_lock();
202 }
203
56fa860e
DW
204 $currentpage = $PAGE;
205 $currentcourse = $COURSE;
206 $response = array();
207
208 try {
e02e7f5a
DW
209 // Taken straight from from setup.php.
210 if (!empty($CFG->moodlepageclass)) {
211 if (!empty($CFG->moodlepageclassfile)) {
212 require_once($CFG->moodlepageclassfile);
213 }
214 $classname = $CFG->moodlepageclass;
215 } else {
216 $classname = 'moodle_page';
217 }
218 $PAGE = new $classname();
56fa860e
DW
219 $COURSE = clone($SITE);
220
221 if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
222 throw new moodle_exception('servicenotavailable', 'webservice');
223 }
224
b9b409cf 225 // Do not allow access to write or delete webservices as a public user.
f19beb32 226 if ($externalfunctioninfo->loginrequired && !WS_SERVER) {
56fa860e 227 if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
acf94de6 228 throw new moodle_exception('servicerequireslogin', 'webservice');
56fa860e
DW
229 }
230 if (!isloggedin()) {
acf94de6 231 throw new moodle_exception('servicerequireslogin', 'webservice');
56fa860e
DW
232 } else {
233 require_sesskey();
234 }
235 }
56fa860e
DW
236 // Validate params, this also sorts the params properly, we need the correct order in the next part.
237 $callable = array($externalfunctioninfo->classname, 'validate_parameters');
238 $params = call_user_func($callable,
239 $externalfunctioninfo->parameters_desc,
240 $args);
b5311ce4 241 $params = array_values($params);
56fa860e 242
b5311ce4 243 // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
244 // make arbitrary behaviour customisations. The overriding plugin could call the 'real'
245 // function first and then modify the results, or it could do a completely separate
246 // thing.
247 $callbacks = get_plugins_with_function('override_webservice_execution');
248 $result = false;
249 foreach ($callbacks as $plugintype => $plugins) {
250 foreach ($plugins as $plugin => $callback) {
251 $result = $callback($externalfunctioninfo, $params);
252 if ($result !== false) {
253 break;
254 }
255 }
256 }
257
258 // If the function was not overridden, call the real one.
259 if ($result === false) {
260 $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
261 $result = call_user_func_array($callable, $params);
262 }
56fa860e
DW
263
264 // Validate the return parameters.
265 if ($externalfunctioninfo->returns_desc !== null) {
266 $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
267 $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
268 }
269
270 $response['error'] = false;
271 $response['data'] = $result;
2603034e 272 } catch (Throwable $e) {
56fa860e
DW
273 $exception = get_exception_info($e);
274 unset($exception->a);
1e17258b 275 $exception->backtrace = format_backtrace($exception->backtrace, true);
56fa860e
DW
276 if (!debugging('', DEBUG_DEVELOPER)) {
277 unset($exception->debuginfo);
278 unset($exception->backtrace);
279 }
280 $response['error'] = true;
281 $response['exception'] = $exception;
282 // Do not process the remaining requests.
283 }
284
285 $PAGE = $currentpage;
286 $COURSE = $currentcourse;
287
288 return $response;
289 }
290
1bea0c27 291 /**
23e7b7cc 292 * Set context restriction for all following subsequent function calls.
4615817d
JM
293 *
294 * @param stdClass $context the context restriction
295 * @since Moodle 2.0
1bea0c27 296 */
2965d271 297 public static function set_context_restriction($context) {
9a0df45a 298 self::$contextrestriction = $context;
299 }
300
2965d271 301 /**
302 * This method has to be called before every operation
303 * that takes a longer time to finish!
304 *
305 * @param int $seconds max expected time the next operation needs
4615817d 306 * @since Moodle 2.0
2965d271 307 */
308 public static function set_timeout($seconds=360) {
309 $seconds = ($seconds < 300) ? 300 : $seconds;
3ef7279f 310 core_php_time_limit::raise($seconds);
2965d271 311 }
312
1bea0c27 313 /**
c9c5cc81 314 * Validates submitted function parameters, if anything is incorrect
1bea0c27 315 * invalid_parameter_exception is thrown.
1d7db36f 316 * This is a simple recursive method which is intended to be called from
317 * each implementation method of external API.
4615817d 318 *
c9c5cc81 319 * @param external_description $description description of parameters
320 * @param mixed $params the actual parameters
321 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
4615817d 322 * @since Moodle 2.0
1bea0c27 323 */
c9c5cc81 324 public static function validate_parameters(external_description $description, $params) {
04d212ce 325 if ($description instanceof external_value) {
c9c5cc81 326 if (is_array($params) or is_object($params)) {
93602569 327 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
c9c5cc81 328 }
4f0c6ad1
PS
329
330 if ($description->type == PARAM_BOOL) {
331 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
332 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
333 return (bool)$params;
334 }
335 }
93602569
JM
336 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
337 '", the server was expecting "' . $description->type . '" type';
338 return validate_param($params, $description->type, $description->allownull, $debuginfo);
4f0c2d00 339
c9c5cc81 340 } else if ($description instanceof external_single_structure) {
341 if (!is_array($params)) {
93602569
JM
342 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
343 . print_r($params, true) . '\'');
c9c5cc81 344 }
345 $result = array();
346 foreach ($description->keys as $key=>$subdesc) {
347 if (!array_key_exists($key, $params)) {
382b9cea 348 if ($subdesc->required == VALUE_REQUIRED) {
93602569 349 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
c9c5cc81 350 }
774b1b0f 351 if ($subdesc->required == VALUE_DEFAULT) {
352 try {
d96030ce 353 $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
774b1b0f 354 } catch (invalid_parameter_exception $e) {
93602569
JM
355 //we are only interested by exceptions returned by validate_param() and validate_parameters()
356 //(in order to build the path to the faulty attribut)
357 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
382b9cea 358 }
774b1b0f 359 }
c9c5cc81 360 } else {
559a5dbd 361 try {
d96030ce 362 $result[$key] = static::validate_parameters($subdesc, $params[$key]);
559a5dbd 363 } catch (invalid_parameter_exception $e) {
93602569
JM
364 //we are only interested by exceptions returned by validate_param() and validate_parameters()
365 //(in order to build the path to the faulty attribut)
366 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
559a5dbd 367 }
c9c5cc81 368 }
369 unset($params[$key]);
370 }
371 if (!empty($params)) {
92fe97f9 372 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
c9c5cc81 373 }
374 return $result;
1bea0c27 375
c9c5cc81 376 } else if ($description instanceof external_multiple_structure) {
377 if (!is_array($params)) {
93602569
JM
378 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
379 . print_r($params, true) . '\'');
c9c5cc81 380 }
381 $result = array();
382 foreach ($params as $param) {
d96030ce 383 $result[] = static::validate_parameters($description->content, $param);
c9c5cc81 384 }
385 return $result;
386
387 } else {
93602569 388 throw new invalid_parameter_exception('Invalid external api description');
c9c5cc81 389 }
1bea0c27 390 }
391
d07ff72d 392 /**
393 * Clean response
23e7b7cc
PS
394 * If a response attribute is unknown from the description, we just ignore the attribute.
395 * If a response attribute is incorrect, invalid_response_exception is thrown.
d07ff72d 396 * Note: this function is similar to validate parameters, however it is distinct because
397 * parameters validation must be distinct from cleaning return values.
4615817d 398 *
d07ff72d 399 * @param external_description $description description of the return values
400 * @param mixed $response the actual response
401 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
4615817d
JM
402 * @author 2010 Jerome Mouneyrac
403 * @since Moodle 2.0
d07ff72d 404 */
405 public static function clean_returnvalue(external_description $description, $response) {
406 if ($description instanceof external_value) {
407 if (is_array($response) or is_object($response)) {
93602569 408 throw new invalid_response_exception('Scalar type expected, array or object received.');
d07ff72d 409 }
410
411 if ($description->type == PARAM_BOOL) {
412 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
413 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
414 return (bool)$response;
415 }
416 }
27190655 417 $responsetype = gettype($response);
93602569 418 $debuginfo = 'Invalid external api response: the value is "' . $response .
27190655 419 '" of PHP type "' . $responsetype . '", the server was expecting "' . $description->type . '" type';
93602569
JM
420 try {
421 return validate_param($response, $description->type, $description->allownull, $debuginfo);
422 } catch (invalid_parameter_exception $e) {
423 //proper exception name, to be recursively catched to build the path to the faulty attribut
424 throw new invalid_response_exception($e->debuginfo);
425 }
d07ff72d 426
427 } else if ($description instanceof external_single_structure) {
9a4c2f50
JM
428 if (!is_array($response) && !is_object($response)) {
429 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
93602569 430 print_r($response, true) . '\'');
d07ff72d 431 }
9a4c2f50
JM
432
433 // Cast objects into arrays.
434 if (is_object($response)) {
435 $response = (array) $response;
436 }
437
d07ff72d 438 $result = array();
439 foreach ($description->keys as $key=>$subdesc) {
440 if (!array_key_exists($key, $response)) {
441 if ($subdesc->required == VALUE_REQUIRED) {
93602569 442 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
d07ff72d 443 }
444 if ($subdesc instanceof external_value) {
143c0abe 445 if ($subdesc->required == VALUE_DEFAULT) {
446 try {
d96030ce 447 $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
93602569
JM
448 } catch (invalid_response_exception $e) {
449 //build the path to the faulty attribut
450 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 451 }
452 }
143c0abe 453 }
d07ff72d 454 } else {
455 try {
d96030ce 456 $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
93602569
JM
457 } catch (invalid_response_exception $e) {
458 //build the path to the faulty attribut
459 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 460 }
461 }
462 unset($response[$key]);
463 }
464
465 return $result;
466
467 } else if ($description instanceof external_multiple_structure) {
468 if (!is_array($response)) {
93602569
JM
469 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
470 print_r($response, true) . '\'');
d07ff72d 471 }
472 $result = array();
473 foreach ($response as $param) {
d96030ce 474 $result[] = static::clean_returnvalue($description->content, $param);
d07ff72d 475 }
476 return $result;
477
478 } else {
93602569 479 throw new invalid_response_exception('Invalid external api response description');
d07ff72d 480 }
481 }
482
9a0df45a 483 /**
484 * Makes sure user may execute functions in this context.
4615817d
JM
485 *
486 * @param stdClass $context
487 * @since Moodle 2.0
9a0df45a 488 */
82f0f5e3 489 public static function validate_context($context) {
56fa860e 490 global $CFG, $PAGE;
4f0c2d00 491
ab9a01f2 492 if (empty($context)) {
493 throw new invalid_parameter_exception('Context does not exist');
494 }
9a0df45a 495 if (empty(self::$contextrestriction)) {
b0c6dc1c 496 self::$contextrestriction = context_system::instance();
9a0df45a 497 }
498 $rcontext = self::$contextrestriction;
499
500 if ($rcontext->contextlevel == $context->contextlevel) {
aa7fbebd 501 if ($rcontext->id != $context->id) {
9a0df45a 502 throw new restricted_context_exception();
503 }
504 } else if ($rcontext->contextlevel > $context->contextlevel) {
505 throw new restricted_context_exception();
506 } else {
8e8891b7 507 $parents = $context->get_parent_context_ids();
9a0df45a 508 if (!in_array($rcontext->id, $parents)) {
509 throw new restricted_context_exception();
510 }
511 }
512
56fa860e
DW
513 $PAGE->reset_theme_and_output();
514 list($unused, $course, $cm) = get_context_info_array($context->id);
515 require_login($course, false, $cm, false, true);
516 $PAGE->set_context($context);
9a0df45a 517 }
aac70ffc
AA
518
519 /**
5b23d9ad
AA
520 * Get context from passed parameters.
521 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
522 * For example, the context level can be "course" and instanceid can be courseid.
523 *
524 * See context_helper::get_all_levels() for a list of valid context levels.
aac70ffc
AA
525 *
526 * @param array $param
527 * @since Moodle 2.6
528 * @throws invalid_parameter_exception
529 * @return context
530 */
5b23d9ad 531 protected static function get_context_from_params($param) {
aac70ffc 532 $levels = context_helper::get_all_levels();
98dece22 533 if (!empty($param['contextid'])) {
aac70ffc 534 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
eac1383e 535 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
aac70ffc
AA
536 $contextlevel = "context_".$param['contextlevel'];
537 if (!array_search($contextlevel, $levels)) {
538 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
539 }
540 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
541 } else {
542 // No valid context info was found.
543 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
544 }
545 }
a60e8ba5
DW
546
547 /**
548 * Returns a prepared structure to use a context parameters.
549 * @return external_single_structure
550 */
551 protected static function get_context_parameters() {
552 $id = new external_value(
553 PARAM_INT,
554 'Context ID. Either use this value, or level and instanceid.',
555 VALUE_DEFAULT,
556 0
557 );
558 $level = new external_value(
559 PARAM_ALPHA,
560 'Context level. To be used with instanceid.',
561 VALUE_DEFAULT,
562 ''
563 );
564 $instanceid = new external_value(
565 PARAM_INT,
566 'Context instance ID. To be used with level',
567 VALUE_DEFAULT,
568 0
569 );
570 return new external_single_structure(array(
571 'contextid' => $id,
572 'contextlevel' => $level,
573 'instanceid' => $instanceid,
574 ));
575 }
576
9a0df45a 577}
578
b038c32c 579/**
580 * Common ancestor of all parameter description classes
4615817d
JM
581 *
582 * @package core_webservice
583 * @copyright 2009 Petr Skodak
584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
585 * @since Moodle 2.0
b038c32c 586 */
587abstract class external_description {
4615817d 588 /** @var string Description of element */
b038c32c 589 public $desc;
4615817d
JM
590
591 /** @var bool Element value required, null not allowed */
b038c32c 592 public $required;
4615817d
JM
593
594 /** @var mixed Default value */
774b1b0f 595 public $default;
b038c32c 596
597 /**
598 * Contructor
4615817d 599 *
b038c32c 600 * @param string $desc
601 * @param bool $required
774b1b0f 602 * @param mixed $default
4615817d 603 * @since Moodle 2.0
b038c32c 604 */
774b1b0f 605 public function __construct($desc, $required, $default) {
b038c32c 606 $this->desc = $desc;
607 $this->required = $required;
774b1b0f 608 $this->default = $default;
b038c32c 609 }
610}
611
612/**
4615817d
JM
613 * Scalar value description class
614 *
615 * @package core_webservice
616 * @copyright 2009 Petr Skodak
617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
618 * @since Moodle 2.0
b038c32c 619 */
04d212ce 620class external_value extends external_description {
4615817d
JM
621
622 /** @var mixed Value type PARAM_XX */
b038c32c 623 public $type;
4615817d
JM
624
625 /** @var bool Allow null values */
b038c32c 626 public $allownull;
627
628 /**
629 * Constructor
4615817d 630 *
b038c32c 631 * @param mixed $type
632 * @param string $desc
633 * @param bool $required
634 * @param mixed $default
635 * @param bool $allownull
4615817d 636 * @since Moodle 2.0
b038c32c 637 */
774b1b0f 638 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
639 $default=null, $allownull=NULL_ALLOWED) {
640 parent::__construct($desc, $required, $default);
78bfb562 641 $this->type = $type;
b038c32c 642 $this->allownull = $allownull;
643 }
644}
645
646/**
647 * Associative array description class
4615817d
JM
648 *
649 * @package core_webservice
650 * @copyright 2009 Petr Skodak
651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 * @since Moodle 2.0
b038c32c 653 */
654class external_single_structure extends external_description {
4615817d
JM
655
656 /** @var array Description of array keys key=>external_description */
b038c32c 657 public $keys;
658
659 /**
660 * Constructor
4615817d 661 *
b038c32c 662 * @param array $keys
663 * @param string $desc
664 * @param bool $required
774b1b0f 665 * @param array $default
4615817d 666 * @since Moodle 2.0
b038c32c 667 */
774b1b0f 668 public function __construct(array $keys, $desc='',
669 $required=VALUE_REQUIRED, $default=null) {
670 parent::__construct($desc, $required, $default);
b038c32c 671 $this->keys = $keys;
672 }
673}
674
675/**
676 * Bulk array description class.
4615817d
JM
677 *
678 * @package core_webservice
679 * @copyright 2009 Petr Skodak
680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681 * @since Moodle 2.0
b038c32c 682 */
683class external_multiple_structure extends external_description {
4615817d
JM
684
685 /** @var external_description content */
b038c32c 686 public $content;
687
688 /**
689 * Constructor
4615817d 690 *
b038c32c 691 * @param external_description $content
692 * @param string $desc
693 * @param bool $required
774b1b0f 694 * @param array $default
4615817d 695 * @since Moodle 2.0
b038c32c 696 */
774b1b0f 697 public function __construct(external_description $content, $desc='',
698 $required=VALUE_REQUIRED, $default=null) {
699 parent::__construct($desc, $required, $default);
b038c32c 700 $this->content = $content;
701 }
702}
c29cca30 703
704/**
705 * Description of top level - PHP function parameters.
c29cca30 706 *
4615817d
JM
707 * @package core_webservice
708 * @copyright 2009 Petr Skodak
709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
710 * @since Moodle 2.0
c29cca30 711 */
712class external_function_parameters extends external_single_structure {
1dc4dc98
DW
713
714 /**
715 * Constructor - does extra checking to prevent top level optional parameters.
716 *
717 * @param array $keys
718 * @param string $desc
719 * @param bool $required
720 * @param array $default
721 */
722 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
723 global $CFG;
724
725 if ($CFG->debugdeveloper) {
726 foreach ($keys as $key => $value) {
727 if ($value instanceof external_value) {
728 if ($value->required == VALUE_OPTIONAL) {
729 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
730 break;
731 }
732 }
733 }
734 }
735 parent::__construct($keys, $desc, $required, $default);
736 }
c29cca30 737}
2822f40a 738
4615817d
JM
739/**
740 * Generate a token
741 *
742 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
743 * @param stdClass|int $serviceorid service linked to the token
744 * @param int $userid user linked to the token
745 * @param stdClass|int $contextorid
746 * @param int $validuntil date when the token expired
747 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
748 * @return string generated token
749 * @author 2010 Jamie Pratt
750 * @since Moodle 2.0
751 */
2822f40a
JP
752function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
753 global $DB, $USER;
754 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
755 $numtries = 0;
756 do {
757 $numtries ++;
758 $generatedtoken = md5(uniqid(rand(),1));
759 if ($numtries > 5){
760 throw new moodle_exception('tokengenerationfailed');
761 }
762 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
365a5941 763 $newtoken = new stdClass();
2822f40a
JP
764 $newtoken->token = $generatedtoken;
765 if (!is_object($serviceorid)){
766 $service = $DB->get_record('external_services', array('id' => $serviceorid));
767 } else {
768 $service = $serviceorid;
769 }
770 if (!is_object($contextorid)){
d197ea43 771 $context = context::instance_by_id($contextorid, MUST_EXIST);
2822f40a
JP
772 } else {
773 $context = $contextorid;
774 }
775 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
776 $newtoken->externalserviceid = $service->id;
777 } else {
778 throw new moodle_exception('nocapabilitytousethisservice');
779 }
780 $newtoken->tokentype = $tokentype;
781 $newtoken->userid = $userid;
2d0acbd5
JP
782 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
783 $newtoken->sid = session_id();
784 }
4f0c2d00
PS
785
786 $newtoken->contextid = $context->id;
2822f40a
JP
787 $newtoken->creatorid = $USER->id;
788 $newtoken->timecreated = time();
789 $newtoken->validuntil = $validuntil;
790 if (!empty($iprestriction)) {
791 $newtoken->iprestriction = $iprestriction;
792 }
956232db
DP
793 // Generate the private token, it must be transmitted only via https.
794 $newtoken->privatetoken = random_string(64);
2822f40a
JP
795 $DB->insert_record('external_tokens', $newtoken);
796 return $newtoken->token;
2d0acbd5 797}
4615817d 798
2d0acbd5 799/**
df997f84 800 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
2d0acbd5
JP
801 * with the Moodle server through web services. The token is linked to the current session for the current page request.
802 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
803 * returned token will be somehow passed into the client app being embedded in the page.
4615817d 804 *
2d0acbd5
JP
805 * @param string $servicename name of the web service. Service name as defined in db/services.php
806 * @param int $context context within which the web service can operate.
807 * @return int returns token id.
4615817d 808 * @since Moodle 2.0
2d0acbd5
JP
809 */
810function external_create_service_token($servicename, $context){
811 global $USER, $DB;
812 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
813 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
bc81eadb
JM
814}
815
816/**
817 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
818 *
819 * @param string $component name of component (moodle, mod_assignment, etc.)
820 */
821function external_delete_descriptions($component) {
822 global $DB;
823
824 $params = array($component);
825
826 $DB->delete_records_select('external_tokens',
827 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
828 $DB->delete_records_select('external_services_users',
829 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
830 $DB->delete_records_select('external_services_functions',
831 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
832 $DB->delete_records('external_services', array('component'=>$component));
833 $DB->delete_records('external_functions', array('component'=>$component));
03d38b92
Y
834}
835
836/**
93ce0e82 837 * Standard Moodle web service warnings
03d38b92 838 *
93ce0e82
JM
839 * @package core_webservice
840 * @copyright 2012 Jerome Mouneyrac
841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
842 * @since Moodle 2.3
843 */
844class external_warnings extends external_multiple_structure {
845
846 /**
847 * Constructor
848 *
849 * @since Moodle 2.3
850 */
8118dbd0
JM
851 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
852 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
93ce0e82
JM
853
854 parent::__construct(
855 new external_single_structure(
856 array(
8118dbd0
JM
857 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
858 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
859 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
93ce0e82
JM
860 'message' => new external_value(PARAM_TEXT,
861 'untranslated english message to explain the warning')
862 ), 'warning'),
863 'list of warnings', VALUE_OPTIONAL);
864 }
865}
866
867/**
868 * A pre-filled external_value class for text format.
869 *
870 * Default is FORMAT_HTML
871 * This should be used all the time in external xxx_params()/xxx_returns functions
872 * as it is the standard way to implement text format param/return values.
873 *
874 * @package core_webservice
875 * @copyright 2012 Jerome Mouneyrac
876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
877 * @since Moodle 2.3
03d38b92 878 */
93ce0e82
JM
879class external_format_value extends external_value {
880
881 /**
882 * Constructor
883 *
884 * @param string $textfieldname Name of the text field
885 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
14968ca9 886 * @param int $default Default value.
93ce0e82
JM
887 * @since Moodle 2.3
888 */
14968ca9 889 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
93ce0e82 890
14968ca9
DW
891 if ($default == null && $required == VALUE_DEFAULT) {
892 $default = FORMAT_HTML;
893 }
93ce0e82
JM
894
895 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
896 . FORMAT_MOODLE . ' = MOODLE, '
897 . FORMAT_PLAIN . ' = PLAIN or '
898 . FORMAT_MARKDOWN . ' = MARKDOWN)';
899
55e168e3 900 parent::__construct(PARAM_INT, $desc, $required, $default);
93ce0e82
JM
901 }
902}
903
904/**
905 * Validate text field format against known FORMAT_XXX
906 *
907 * @param array $format the format to validate
908 * @return the validated format
909 * @throws coding_exception
5bcfd504 910 * @since Moodle 2.3
93ce0e82
JM
911 */
912function external_validate_format($format) {
913 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
914 if (!in_array($format, $allowedformats)) {
915 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
916 'The format with value=' . $format . ' is not supported by this Moodle site');
917 }
918 return $format;
919}
920
9764aab9
DW
921/**
922 * Format the string to be returned properly as requested by the either the web service server,
923 * either by an internally call.
924 * The caller can change the format (raw) with the external_settings singleton
925 * All web service servers must set this singleton when parsing the $_GET and $_POST.
926 *
1d014075
FM
927 * <pre>
928 * Options are the same that in {@link format_string()} with some changes:
929 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
930 * </pre>
931 *
9764aab9
DW
932 * @param string $str The string to be filtered. Should be plain text, expect
933 * possibly for multilang tags.
934 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
0377e78e 935 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
9764aab9
DW
936 * @param array $options options array/object or courseid
937 * @return string text
938 * @since Moodle 3.0
939 */
0377e78e 940function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
9764aab9
DW
941
942 // Get settings (singleton).
943 $settings = external_settings::get_instance();
0377e78e 944 if (empty($contextorid)) {
9764aab9
DW
945 throw new coding_exception('contextid is required');
946 }
947
948 if (!$settings->get_raw()) {
0377e78e
RW
949 if (is_object($contextorid) && is_a($contextorid, 'context')) {
950 $context = $contextorid;
951 } else {
952 $context = context::instance_by_id($contextorid);
953 }
9764aab9 954 $options['context'] = $context;
1d014075 955 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
9764aab9
DW
956 $str = format_string($str, $striplinks, $options);
957 }
958
959 return $str;
960}
961
93ce0e82
JM
962/**
963 * Format the text to be returned properly as requested by the either the web service server,
964 * either by an internally call.
965 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
966 * All web service servers must set this singleton when parsing the $_GET and $_POST.
967 *
19a131ed
PFO
968 * <pre>
969 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
970 * trusted : If true the string won't be cleaned. Default false.
971 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
972 * nocache : If true the string will not be cached and will be formatted every call. Default false.
1d014075 973 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
19a131ed
PFO
974 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
975 * Default changed because div tags are not commonly needed.
976 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
977 * context : Not used! Using contextid parameter instead.
978 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
979 * returned. Default false.
980 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
981 * format_text) true. Default changed id attributes are commonly needed.
977804ed 982 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
19a131ed
PFO
983 * </pre>
984 *
93ce0e82 985 * @param string $text The content that may contain ULRs in need of rewriting.
c4a15021 986 * @param int $textformat The text format.
0377e78e 987 * @param context|int $contextorid This parameter and the next two identify the file area to use.
93ce0e82
JM
988 * @param string $component
989 * @param string $filearea helps identify the file area.
990 * @param int $itemid helps identify the file area.
19a131ed 991 * @param object/array $options text formatting options
93ce0e82
JM
992 * @return array text + textformat
993 * @since Moodle 2.3
833be5e4 994 * @since Moodle 3.2 component, filearea and itemid are optional parameters
93ce0e82 995 */
0377e78e 996function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
833be5e4 997 $options = null) {
93ce0e82
JM
998 global $CFG;
999
1000 // Get settings (singleton).
1001 $settings = external_settings::get_instance();
1002
0377e78e
RW
1003 if (is_object($contextorid) && is_a($contextorid, 'context')) {
1004 $context = $contextorid;
1005 $contextid = $context->id;
1006 } else {
1007 $context = null;
1008 $contextid = $contextorid;
1009 }
1010
833be5e4 1011 if ($component and $filearea and $settings->get_fileurl()) {
ea29059e 1012 require_once($CFG->libdir . "/filelib.php");
93ce0e82
JM
1013 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
1014 }
1015
4b82c15c
DM
1016 // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
1017 // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
1018
93ce0e82 1019 if (!$settings->get_raw()) {
19a131ed
PFO
1020 $options = (array)$options;
1021
1022 // If context is passed in options, check that is the same to show a debug message.
1023 if (isset($options['context'])) {
1024 if ((is_object($options['context']) && $options['context']->id != $contextid)
b1a9804a 1025 || (!is_object($options['context']) && $options['context'] != $contextid)) {
19a131ed
PFO
1026 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
1027 Using $contextid parameter...', DEBUG_DEVELOPER);
1028 }
1029 }
1030
1d014075 1031 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
19a131ed 1032 $options['para'] = isset($options['para']) ? $options['para'] : false;
0377e78e 1033 $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
19a131ed
PFO
1034 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
1035
1036 $text = format_text($text, $textformat, $options);
c4a15021 1037 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
93ce0e82
JM
1038 }
1039
1040 return array($text, $textformat);
1041}
1042
0a90f624
JL
1043/**
1044 * Generate or return an existing token for the current authenticated user.
1045 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
1046 *
1047 * @param stdClass $service external service object
1048 * @return stdClass token object
1049 * @since Moodle 3.2
1050 * @throws moodle_exception
1051 */
1052function external_generate_token_for_current_user($service) {
993e8175 1053 global $DB, $USER, $CFG;
0a90f624
JL
1054
1055 core_user::require_active_user($USER, true, true);
1056
1057 // Check if there is any required system capability.
1058 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1059 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1060 }
1061
1062 // Specific checks related to user restricted service.
1063 if ($service->restrictedusers) {
1064 $authoriseduser = $DB->get_record('external_services_users',
1065 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1066
1067 if (empty($authoriseduser)) {
1068 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1069 }
1070
1071 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1072 throw new moodle_exception('invalidtimedtoken', 'webservice');
1073 }
1074
1075 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1076 throw new moodle_exception('invalidiptoken', 'webservice');
1077 }
1078 }
1079
1080 // Check if a token has already been created for this user and this service.
1081 $conditions = array(
1082 'userid' => $USER->id,
1083 'externalserviceid' => $service->id,
1084 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1085 );
1086 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1087
1088 // A bit of sanity checks.
1089 foreach ($tokens as $key => $token) {
1090
1091 // Checks related to a specific token. (script execution continue).
1092 $unsettoken = false;
1093 // If sid is set then there must be a valid associated session no matter the token type.
1094 if (!empty($token->sid)) {
1095 if (!\core\session\manager::session_exists($token->sid)) {
1096 // This token will never be valid anymore, delete it.
1097 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1098 $unsettoken = true;
1099 }
1100 }
1101
1102 // Remove token is not valid anymore.
1103 if (!empty($token->validuntil) and $token->validuntil < time()) {
1104 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1105 $unsettoken = true;
1106 }
1107
1108 // Remove token if its ip not in whitelist.
1109 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1110 $unsettoken = true;
1111 }
1112
1113 if ($unsettoken) {
1114 unset($tokens[$key]);
1115 }
1116 }
1117
1118 // If some valid tokens exist then use the most recent.
1119 if (count($tokens) > 0) {
1120 $token = array_pop($tokens);
1121 } else {
1122 $context = context_system::instance();
1123 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1124
1125 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1126 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1127
1128 // Create a new token.
1129 $token = new stdClass;
1130 $token->token = md5(uniqid(rand(), 1));
1131 $token->userid = $USER->id;
1132 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1133 $token->contextid = context_system::instance()->id;
1134 $token->creatorid = $USER->id;
1135 $token->timecreated = time();
1136 $token->externalserviceid = $service->id;
993e8175
JL
1137 // By default tokens are valid for 12 weeks.
1138 $token->validuntil = $token->timecreated + $CFG->tokenduration;
56c84137
JL
1139 $token->iprestriction = null;
1140 $token->sid = null;
1141 $token->lastaccess = null;
69cbe359
JL
1142 // Generate the private token, it must be transmitted only via https.
1143 $token->privatetoken = random_string(64);
0a90f624
JL
1144 $token->id = $DB->insert_record('external_tokens', $token);
1145
56c84137
JL
1146 $eventtoken = clone $token;
1147 $eventtoken->privatetoken = null;
0a90f624 1148 $params = array(
56c84137 1149 'objectid' => $eventtoken->id,
0a90f624
JL
1150 'relateduserid' => $USER->id,
1151 'other' => array(
1152 'auto' => true
1153 )
1154 );
1155 $event = \core\event\webservice_token_created::create($params);
56c84137 1156 $event->add_record_snapshot('external_tokens', $eventtoken);
0a90f624
JL
1157 $event->trigger();
1158 } else {
1159 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1160 }
1161 }
1162 return $token;
1163}
1164
a947ecd6
JL
1165/**
1166 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1167 *
1168 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1169 * In order to protect the privatetoken, we remove it from the event params.
1170 *
1171 * @param stdClass $token token object
1172 * @since Moodle 3.2
1173 */
1174function external_log_token_request($token) {
1175 global $DB;
1176
1177 $token->privatetoken = null;
1178
1179 // Log token access.
1180 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1181
1182 $params = array(
1183 'objectid' => $token->id,
1184 );
1185 $event = \core\event\webservice_token_sent::create($params);
1186 $event->add_record_snapshot('external_tokens', $token);
1187 $event->trigger();
1188}
0a90f624 1189
93ce0e82
JM
1190/**
1191 * Singleton to handle the external settings.
1192 *
1193 * We use singleton to encapsulate the "logic"
1194 *
1195 * @package core_webservice
1196 * @copyright 2012 Jerome Mouneyrac
1197 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1198 * @since Moodle 2.3
1199 */
1200class external_settings {
1201
1202 /** @var object the singleton instance */
1203 public static $instance = null;
1204
1205 /** @var boolean Should the external function return raw text or formatted */
1206 private $raw = false;
1207
1208 /** @var boolean Should the external function filter the text */
1209 private $filter = false;
1210
1211 /** @var boolean Should the external function rewrite plugin file url */
1212 private $fileurl = true;
1213
1214 /** @var string In which file should the urls be rewritten */
1215 private $file = 'webservice/pluginfile.php';
1216
bb14a488
JL
1217 /** @var string The session lang */
1218 private $lang = '';
1219
93ce0e82
JM
1220 /**
1221 * Constructor - protected - can not be instanciated
1222 */
1223 protected function __construct() {
34773ccf 1224 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
9764aab9
DW
1225 // For normal pages, the default should match the default for format_text.
1226 $this->filter = true;
1d772481
AA
1227 // Use pluginfile.php for web requests.
1228 $this->file = 'pluginfile.php';
9764aab9 1229 }
93ce0e82
JM
1230 }
1231
1232 /**
1233 * Clone - private - can not be cloned
1234 */
1235 private final function __clone() {
1236 }
1237
1238 /**
1239 * Return only one instance
1240 *
9743b2d4 1241 * @return \external_settings
93ce0e82
JM
1242 */
1243 public static function get_instance() {
1244 if (self::$instance === null) {
1245 self::$instance = new external_settings;
1246 }
1247
1248 return self::$instance;
1249 }
1250
1251 /**
1252 * Set raw
1253 *
1254 * @param boolean $raw
1255 */
1256 public function set_raw($raw) {
1257 $this->raw = $raw;
1258 }
1259
1260 /**
1261 * Get raw
1262 *
1263 * @return boolean
1264 */
1265 public function get_raw() {
1266 return $this->raw;
1267 }
1268
1269 /**
1270 * Set filter
1271 *
1272 * @param boolean $filter
1273 */
1274 public function set_filter($filter) {
1275 $this->filter = $filter;
1276 }
1277
1278 /**
1279 * Get filter
1280 *
1281 * @return boolean
1282 */
1283 public function get_filter() {
1284 return $this->filter;
1285 }
1286
1287 /**
1288 * Set fileurl
1289 *
1290 * @param boolean $fileurl
1291 */
1292 public function set_fileurl($fileurl) {
1293 $this->fileurl = $fileurl;
1294 }
1295
1296 /**
1297 * Get fileurl
1298 *
1299 * @return boolean
1300 */
1301 public function get_fileurl() {
1302 return $this->fileurl;
1303 }
1304
1305 /**
1306 * Set file
1307 *
1308 * @param string $file
1309 */
1310 public function set_file($file) {
1311 $this->file = $file;
1312 }
1313
1314 /**
1315 * Get file
1316 *
1317 * @return string
1318 */
1319 public function get_file() {
1320 return $this->file;
1321 }
bb14a488
JL
1322
1323 /**
1324 * Set lang
1325 *
1326 * @param string $lang
1327 */
1328 public function set_lang($lang) {
1329 $this->lang = $lang;
1330 }
1331
1332 /**
1333 * Get lang
1334 *
1335 * @return string
1336 */
1337 public function get_lang() {
1338 return $this->lang;
1339 }
50f9449f 1340}
82f0f5e3
JL
1341
1342/**
1343 * Utility functions for the external API.
1344 *
1345 * @package core_webservice
1346 * @copyright 2015 Juan Leyva
1347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1348 * @since Moodle 3.0
1349 */
1350class external_util {
1351
1352 /**
1353 * Validate a list of courses, returning the complete course objects for valid courses.
1354 *
107ab4b9 1355 * Each course has an additional 'contextvalidated' field, this will be set to true unless
1356 * you set $keepfails, in which case it will be false if validation fails for a course.
1357 *
82f0f5e3 1358 * @param array $courseids A list of course ids
b80ede13 1359 * @param array $courses An array of courses already pre-fetched, indexed by course id.
e2002009 1360 * @param bool $addcontext True if the returned course object should include the full context object.
107ab4b9 1361 * @param bool $keepfails True to keep all the course objects even if validation fails
82f0f5e3
JL
1362 * @return array An array of courses and the validation warnings
1363 */
107ab4b9 1364 public static function validate_courses($courseids, $courses = array(), $addcontext = false,
1365 $keepfails = false) {
1366 global $DB;
1367
82f0f5e3
JL
1368 // Delete duplicates.
1369 $courseids = array_unique($courseids);
82f0f5e3
JL
1370 $warnings = array();
1371
4b11af96 1372 // Remove courses which are not even requested.
107ab4b9 1373 $courses = array_intersect_key($courses, array_flip($courseids));
1374
1375 // For any courses NOT loaded already, get them in a single query (and preload contexts)
1376 // for performance. Preserve ordering because some tests depend on it.
1377 $newcourseids = [];
1378 foreach ($courseids as $cid) {
1379 if (!array_key_exists($cid, $courses)) {
1380 $newcourseids[] = $cid;
1381 }
1382 }
1383 if ($newcourseids) {
1384 list ($listsql, $listparams) = $DB->get_in_or_equal($newcourseids);
1385
1386 // Load list of courses, and preload associated contexts.
1387 $contextselect = context_helper::get_preload_record_columns_sql('x');
1388 $newcourses = $DB->get_records_sql("
1389 SELECT c.*, $contextselect
1390 FROM {course} c
65b10696 1391 JOIN {context} x ON x.instanceid = c.id
107ab4b9 1392 WHERE x.contextlevel = ? AND c.id $listsql",
1393 array_merge([CONTEXT_COURSE], $listparams));
1394 foreach ($newcourseids as $cid) {
1395 if (array_key_exists($cid, $newcourses)) {
1396 $course = $newcourses[$cid];
1397 context_helper::preload_from_record($course);
1398 $courses[$course->id] = $course;
1399 }
1400 }
1401 }
4b11af96 1402
82f0f5e3
JL
1403 foreach ($courseids as $cid) {
1404 // Check the user can function in this context.
1405 try {
1406 $context = context_course::instance($cid);
1407 external_api::validate_context($context);
4b11af96 1408
e2002009
JL
1409 if ($addcontext) {
1410 $courses[$cid]->context = $context;
1411 }
107ab4b9 1412 $courses[$cid]->contextvalidated = true;
82f0f5e3 1413 } catch (Exception $e) {
107ab4b9 1414 if ($keepfails) {
1415 $courses[$cid]->contextvalidated = false;
1416 } else {
1417 unset($courses[$cid]);
1418 }
82f0f5e3
JL
1419 $warnings[] = array(
1420 'item' => 'course',
1421 'itemid' => $cid,
1422 'warningcode' => '1',
1423 'message' => 'No access rights in course context'
1424 );
1425 }
1426 }
1427
1428 return array($courses, $warnings);
1429 }
1430
ae584b3b
JL
1431 /**
1432 * Returns all area files (optionally limited by itemid).
1433 *
1434 * @param int $contextid context ID
1435 * @param string $component component
1436 * @param string $filearea file area
1437 * @param int $itemid item ID or all files if not specified
1438 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1439 * @return array of files, compatible with the external_files structure.
1440 * @since Moodle 3.2
1441 */
1442 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1443 $files = array();
1444 $fs = get_file_storage();
1445
1446 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1447 foreach ($areafiles as $areafile) {
1448 $file = array();
1449 $file['filename'] = $areafile->get_filename();
1450 $file['filepath'] = $areafile->get_filepath();
1451 $file['mimetype'] = $areafile->get_mimetype();
1452 $file['filesize'] = $areafile->get_filesize();
1453 $file['timemodified'] = $areafile->get_timemodified();
1104a9fa
JL
1454 $file['isexternalfile'] = $areafile->is_external_file();
1455 if ($file['isexternalfile']) {
1456 $file['repositorytype'] = $areafile->get_repository_type();
1457 }
ae584b3b
JL
1458 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1459 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1460 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1461 $files[] = $file;
1462 }
1463 }
1464 return $files;
1465 }
1466}
1467
1468/**
1469 * External structure representing a set of files.
1470 *
1471 * @package core_webservice
1472 * @copyright 2016 Juan Leyva
1473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1474 * @since Moodle 3.2
1475 */
1476class external_files extends external_multiple_structure {
1477
1478 /**
1479 * Constructor
1480 * @param string $desc Description for the multiple structure.
1481 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1482 */
1483 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1484
1485 parent::__construct(
1486 new external_single_structure(
1487 array(
1488 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1489 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1490 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1491 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1492 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1493 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1104a9fa
JL
1494 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1495 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
ae584b3b
JL
1496 ),
1497 'File.'
1498 ),
1499 $desc,
1500 $required
1501 );
1502 }
44acbb81
JL
1503
1504 /**
1505 * Return the properties ready to be used by an exporter.
1506 *
1507 * @return array properties
1508 * @since Moodle 3.3
1509 */
1510 public static function get_properties_for_exporter() {
1511 return [
1512 'filename' => array(
1513 'type' => PARAM_FILE,
1514 'description' => 'File name.',
1515 'optional' => true,
1516 'null' => NULL_NOT_ALLOWED,
1517 ),
1518 'filepath' => array(
1519 'type' => PARAM_PATH,
1520 'description' => 'File path.',
1521 'optional' => true,
1522 'null' => NULL_NOT_ALLOWED,
1523 ),
1524 'filesize' => array(
1525 'type' => PARAM_INT,
1526 'description' => 'File size.',
1527 'optional' => true,
1528 'null' => NULL_NOT_ALLOWED,
1529 ),
1530 'fileurl' => array(
1531 'type' => PARAM_URL,
1532 'description' => 'Downloadable file url.',
1533 'optional' => true,
1534 'null' => NULL_NOT_ALLOWED,
1535 ),
1536 'timemodified' => array(
1537 'type' => PARAM_INT,
1538 'description' => 'Time modified.',
1539 'optional' => true,
1540 'null' => NULL_NOT_ALLOWED,
1541 ),
1542 'mimetype' => array(
1543 'type' => PARAM_RAW,
1544 'description' => 'File mime type.',
1545 'optional' => true,
1546 'null' => NULL_NOT_ALLOWED,
1547 ),
1104a9fa
JL
1548 'isexternalfile' => array(
1549 'type' => PARAM_BOOL,
1550 'description' => 'Whether is an external file.',
1551 'optional' => true,
1552 'null' => NULL_NOT_ALLOWED,
1553 ),
1554 'repositorytype' => array(
1555 'type' => PARAM_PLUGIN,
1556 'description' => 'The repository type for the external files.',
1557 'optional' => true,
1558 'null' => NULL_ALLOWED,
1559 ),
44acbb81
JL
1560 ];
1561 }
82f0f5e3 1562}