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