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