weekly release 3.2dev
[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);
242 if (!debugging('', DEBUG_DEVELOPER)) {
243 unset($exception->debuginfo);
244 unset($exception->backtrace);
245 }
246 $response['error'] = true;
247 $response['exception'] = $exception;
248 // Do not process the remaining requests.
249 }
250
251 $PAGE = $currentpage;
252 $COURSE = $currentcourse;
253
254 return $response;
255 }
256
1bea0c27 257 /**
23e7b7cc 258 * Set context restriction for all following subsequent function calls.
4615817d
JM
259 *
260 * @param stdClass $context the context restriction
261 * @since Moodle 2.0
1bea0c27 262 */
2965d271 263 public static function set_context_restriction($context) {
9a0df45a 264 self::$contextrestriction = $context;
265 }
266
2965d271 267 /**
268 * This method has to be called before every operation
269 * that takes a longer time to finish!
270 *
271 * @param int $seconds max expected time the next operation needs
4615817d 272 * @since Moodle 2.0
2965d271 273 */
274 public static function set_timeout($seconds=360) {
275 $seconds = ($seconds < 300) ? 300 : $seconds;
3ef7279f 276 core_php_time_limit::raise($seconds);
2965d271 277 }
278
1bea0c27 279 /**
c9c5cc81 280 * Validates submitted function parameters, if anything is incorrect
1bea0c27 281 * invalid_parameter_exception is thrown.
1d7db36f 282 * This is a simple recursive method which is intended to be called from
283 * each implementation method of external API.
4615817d 284 *
c9c5cc81 285 * @param external_description $description description of parameters
286 * @param mixed $params the actual parameters
287 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
4615817d 288 * @since Moodle 2.0
1bea0c27 289 */
c9c5cc81 290 public static function validate_parameters(external_description $description, $params) {
04d212ce 291 if ($description instanceof external_value) {
c9c5cc81 292 if (is_array($params) or is_object($params)) {
93602569 293 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
c9c5cc81 294 }
4f0c6ad1
PS
295
296 if ($description->type == PARAM_BOOL) {
297 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
298 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
299 return (bool)$params;
300 }
301 }
93602569
JM
302 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
303 '", the server was expecting "' . $description->type . '" type';
304 return validate_param($params, $description->type, $description->allownull, $debuginfo);
4f0c2d00 305
c9c5cc81 306 } else if ($description instanceof external_single_structure) {
307 if (!is_array($params)) {
93602569
JM
308 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
309 . print_r($params, true) . '\'');
c9c5cc81 310 }
311 $result = array();
312 foreach ($description->keys as $key=>$subdesc) {
313 if (!array_key_exists($key, $params)) {
382b9cea 314 if ($subdesc->required == VALUE_REQUIRED) {
93602569 315 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
c9c5cc81 316 }
774b1b0f 317 if ($subdesc->required == VALUE_DEFAULT) {
318 try {
319 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
320 } catch (invalid_parameter_exception $e) {
93602569
JM
321 //we are only interested by exceptions returned by validate_param() and validate_parameters()
322 //(in order to build the path to the faulty attribut)
323 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
382b9cea 324 }
774b1b0f 325 }
c9c5cc81 326 } else {
559a5dbd 327 try {
328 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
329 } catch (invalid_parameter_exception $e) {
93602569
JM
330 //we are only interested by exceptions returned by validate_param() and validate_parameters()
331 //(in order to build the path to the faulty attribut)
332 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
559a5dbd 333 }
c9c5cc81 334 }
335 unset($params[$key]);
336 }
337 if (!empty($params)) {
92fe97f9 338 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
c9c5cc81 339 }
340 return $result;
1bea0c27 341
c9c5cc81 342 } else if ($description instanceof external_multiple_structure) {
343 if (!is_array($params)) {
93602569
JM
344 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
345 . print_r($params, true) . '\'');
c9c5cc81 346 }
347 $result = array();
348 foreach ($params as $param) {
349 $result[] = self::validate_parameters($description->content, $param);
350 }
351 return $result;
352
353 } else {
93602569 354 throw new invalid_parameter_exception('Invalid external api description');
c9c5cc81 355 }
1bea0c27 356 }
357
d07ff72d 358 /**
359 * Clean response
23e7b7cc
PS
360 * If a response attribute is unknown from the description, we just ignore the attribute.
361 * If a response attribute is incorrect, invalid_response_exception is thrown.
d07ff72d 362 * Note: this function is similar to validate parameters, however it is distinct because
363 * parameters validation must be distinct from cleaning return values.
4615817d 364 *
d07ff72d 365 * @param external_description $description description of the return values
366 * @param mixed $response the actual response
367 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
4615817d
JM
368 * @author 2010 Jerome Mouneyrac
369 * @since Moodle 2.0
d07ff72d 370 */
371 public static function clean_returnvalue(external_description $description, $response) {
372 if ($description instanceof external_value) {
373 if (is_array($response) or is_object($response)) {
93602569 374 throw new invalid_response_exception('Scalar type expected, array or object received.');
d07ff72d 375 }
376
377 if ($description->type == PARAM_BOOL) {
378 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
379 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
380 return (bool)$response;
381 }
382 }
93602569
JM
383 $debuginfo = 'Invalid external api response: the value is "' . $response .
384 '", the server was expecting "' . $description->type . '" type';
385 try {
386 return validate_param($response, $description->type, $description->allownull, $debuginfo);
387 } catch (invalid_parameter_exception $e) {
388 //proper exception name, to be recursively catched to build the path to the faulty attribut
389 throw new invalid_response_exception($e->debuginfo);
390 }
d07ff72d 391
392 } else if ($description instanceof external_single_structure) {
9a4c2f50
JM
393 if (!is_array($response) && !is_object($response)) {
394 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
93602569 395 print_r($response, true) . '\'');
d07ff72d 396 }
9a4c2f50
JM
397
398 // Cast objects into arrays.
399 if (is_object($response)) {
400 $response = (array) $response;
401 }
402
d07ff72d 403 $result = array();
404 foreach ($description->keys as $key=>$subdesc) {
405 if (!array_key_exists($key, $response)) {
406 if ($subdesc->required == VALUE_REQUIRED) {
93602569 407 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
d07ff72d 408 }
409 if ($subdesc instanceof external_value) {
143c0abe 410 if ($subdesc->required == VALUE_DEFAULT) {
411 try {
d07ff72d 412 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
93602569
JM
413 } catch (invalid_response_exception $e) {
414 //build the path to the faulty attribut
415 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 416 }
417 }
143c0abe 418 }
d07ff72d 419 } else {
420 try {
421 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
93602569
JM
422 } catch (invalid_response_exception $e) {
423 //build the path to the faulty attribut
424 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 425 }
426 }
427 unset($response[$key]);
428 }
429
430 return $result;
431
432 } else if ($description instanceof external_multiple_structure) {
433 if (!is_array($response)) {
93602569
JM
434 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
435 print_r($response, true) . '\'');
d07ff72d 436 }
437 $result = array();
438 foreach ($response as $param) {
439 $result[] = self::clean_returnvalue($description->content, $param);
440 }
441 return $result;
442
443 } else {
93602569 444 throw new invalid_response_exception('Invalid external api response description');
d07ff72d 445 }
446 }
447
9a0df45a 448 /**
449 * Makes sure user may execute functions in this context.
4615817d
JM
450 *
451 * @param stdClass $context
452 * @since Moodle 2.0
9a0df45a 453 */
82f0f5e3 454 public static function validate_context($context) {
56fa860e 455 global $CFG, $PAGE;
4f0c2d00 456
ab9a01f2 457 if (empty($context)) {
458 throw new invalid_parameter_exception('Context does not exist');
459 }
9a0df45a 460 if (empty(self::$contextrestriction)) {
b0c6dc1c 461 self::$contextrestriction = context_system::instance();
9a0df45a 462 }
463 $rcontext = self::$contextrestriction;
464
465 if ($rcontext->contextlevel == $context->contextlevel) {
aa7fbebd 466 if ($rcontext->id != $context->id) {
9a0df45a 467 throw new restricted_context_exception();
468 }
469 } else if ($rcontext->contextlevel > $context->contextlevel) {
470 throw new restricted_context_exception();
471 } else {
8e8891b7 472 $parents = $context->get_parent_context_ids();
9a0df45a 473 if (!in_array($rcontext->id, $parents)) {
474 throw new restricted_context_exception();
475 }
476 }
477
56fa860e
DW
478 $PAGE->reset_theme_and_output();
479 list($unused, $course, $cm) = get_context_info_array($context->id);
480 require_login($course, false, $cm, false, true);
481 $PAGE->set_context($context);
9a0df45a 482 }
aac70ffc
AA
483
484 /**
5b23d9ad
AA
485 * Get context from passed parameters.
486 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
487 * For example, the context level can be "course" and instanceid can be courseid.
488 *
489 * See context_helper::get_all_levels() for a list of valid context levels.
aac70ffc
AA
490 *
491 * @param array $param
492 * @since Moodle 2.6
493 * @throws invalid_parameter_exception
494 * @return context
495 */
5b23d9ad 496 protected static function get_context_from_params($param) {
aac70ffc 497 $levels = context_helper::get_all_levels();
98dece22 498 if (!empty($param['contextid'])) {
aac70ffc 499 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
eac1383e 500 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
aac70ffc
AA
501 $contextlevel = "context_".$param['contextlevel'];
502 if (!array_search($contextlevel, $levels)) {
503 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
504 }
505 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
506 } else {
507 // No valid context info was found.
508 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
509 }
510 }
9a0df45a 511}
512
b038c32c 513/**
514 * Common ancestor of all parameter description classes
4615817d
JM
515 *
516 * @package core_webservice
517 * @copyright 2009 Petr Skodak
518 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
519 * @since Moodle 2.0
b038c32c 520 */
521abstract class external_description {
4615817d 522 /** @var string Description of element */
b038c32c 523 public $desc;
4615817d
JM
524
525 /** @var bool Element value required, null not allowed */
b038c32c 526 public $required;
4615817d
JM
527
528 /** @var mixed Default value */
774b1b0f 529 public $default;
b038c32c 530
531 /**
532 * Contructor
4615817d 533 *
b038c32c 534 * @param string $desc
535 * @param bool $required
774b1b0f 536 * @param mixed $default
4615817d 537 * @since Moodle 2.0
b038c32c 538 */
774b1b0f 539 public function __construct($desc, $required, $default) {
b038c32c 540 $this->desc = $desc;
541 $this->required = $required;
774b1b0f 542 $this->default = $default;
b038c32c 543 }
544}
545
546/**
4615817d
JM
547 * Scalar value description class
548 *
549 * @package core_webservice
550 * @copyright 2009 Petr Skodak
551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 * @since Moodle 2.0
b038c32c 553 */
04d212ce 554class external_value extends external_description {
4615817d
JM
555
556 /** @var mixed Value type PARAM_XX */
b038c32c 557 public $type;
4615817d
JM
558
559 /** @var bool Allow null values */
b038c32c 560 public $allownull;
561
562 /**
563 * Constructor
4615817d 564 *
b038c32c 565 * @param mixed $type
566 * @param string $desc
567 * @param bool $required
568 * @param mixed $default
569 * @param bool $allownull
4615817d 570 * @since Moodle 2.0
b038c32c 571 */
774b1b0f 572 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
573 $default=null, $allownull=NULL_ALLOWED) {
574 parent::__construct($desc, $required, $default);
78bfb562 575 $this->type = $type;
b038c32c 576 $this->allownull = $allownull;
577 }
578}
579
580/**
581 * Associative array description class
4615817d
JM
582 *
583 * @package core_webservice
584 * @copyright 2009 Petr Skodak
585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
586 * @since Moodle 2.0
b038c32c 587 */
588class external_single_structure extends external_description {
4615817d
JM
589
590 /** @var array Description of array keys key=>external_description */
b038c32c 591 public $keys;
592
593 /**
594 * Constructor
4615817d 595 *
b038c32c 596 * @param array $keys
597 * @param string $desc
598 * @param bool $required
774b1b0f 599 * @param array $default
4615817d 600 * @since Moodle 2.0
b038c32c 601 */
774b1b0f 602 public function __construct(array $keys, $desc='',
603 $required=VALUE_REQUIRED, $default=null) {
604 parent::__construct($desc, $required, $default);
b038c32c 605 $this->keys = $keys;
606 }
607}
608
609/**
610 * Bulk array description class.
4615817d
JM
611 *
612 * @package core_webservice
613 * @copyright 2009 Petr Skodak
614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
615 * @since Moodle 2.0
b038c32c 616 */
617class external_multiple_structure extends external_description {
4615817d
JM
618
619 /** @var external_description content */
b038c32c 620 public $content;
621
622 /**
623 * Constructor
4615817d 624 *
b038c32c 625 * @param external_description $content
626 * @param string $desc
627 * @param bool $required
774b1b0f 628 * @param array $default
4615817d 629 * @since Moodle 2.0
b038c32c 630 */
774b1b0f 631 public function __construct(external_description $content, $desc='',
632 $required=VALUE_REQUIRED, $default=null) {
633 parent::__construct($desc, $required, $default);
b038c32c 634 $this->content = $content;
635 }
636}
c29cca30 637
638/**
639 * Description of top level - PHP function parameters.
c29cca30 640 *
4615817d
JM
641 * @package core_webservice
642 * @copyright 2009 Petr Skodak
643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
644 * @since Moodle 2.0
c29cca30 645 */
646class external_function_parameters extends external_single_structure {
1dc4dc98
DW
647
648 /**
649 * Constructor - does extra checking to prevent top level optional parameters.
650 *
651 * @param array $keys
652 * @param string $desc
653 * @param bool $required
654 * @param array $default
655 */
656 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
657 global $CFG;
658
659 if ($CFG->debugdeveloper) {
660 foreach ($keys as $key => $value) {
661 if ($value instanceof external_value) {
662 if ($value->required == VALUE_OPTIONAL) {
663 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
664 break;
665 }
666 }
667 }
668 }
669 parent::__construct($keys, $desc, $required, $default);
670 }
c29cca30 671}
2822f40a 672
4615817d
JM
673/**
674 * Generate a token
675 *
676 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
677 * @param stdClass|int $serviceorid service linked to the token
678 * @param int $userid user linked to the token
679 * @param stdClass|int $contextorid
680 * @param int $validuntil date when the token expired
681 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
682 * @return string generated token
683 * @author 2010 Jamie Pratt
684 * @since Moodle 2.0
685 */
2822f40a
JP
686function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
687 global $DB, $USER;
688 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
689 $numtries = 0;
690 do {
691 $numtries ++;
692 $generatedtoken = md5(uniqid(rand(),1));
693 if ($numtries > 5){
694 throw new moodle_exception('tokengenerationfailed');
695 }
696 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
365a5941 697 $newtoken = new stdClass();
2822f40a
JP
698 $newtoken->token = $generatedtoken;
699 if (!is_object($serviceorid)){
700 $service = $DB->get_record('external_services', array('id' => $serviceorid));
701 } else {
702 $service = $serviceorid;
703 }
704 if (!is_object($contextorid)){
d197ea43 705 $context = context::instance_by_id($contextorid, MUST_EXIST);
2822f40a
JP
706 } else {
707 $context = $contextorid;
708 }
709 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
710 $newtoken->externalserviceid = $service->id;
711 } else {
712 throw new moodle_exception('nocapabilitytousethisservice');
713 }
714 $newtoken->tokentype = $tokentype;
715 $newtoken->userid = $userid;
2d0acbd5
JP
716 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
717 $newtoken->sid = session_id();
718 }
4f0c2d00
PS
719
720 $newtoken->contextid = $context->id;
2822f40a
JP
721 $newtoken->creatorid = $USER->id;
722 $newtoken->timecreated = time();
723 $newtoken->validuntil = $validuntil;
724 if (!empty($iprestriction)) {
725 $newtoken->iprestriction = $iprestriction;
726 }
727 $DB->insert_record('external_tokens', $newtoken);
728 return $newtoken->token;
2d0acbd5 729}
4615817d 730
2d0acbd5 731/**
df997f84 732 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
2d0acbd5
JP
733 * with the Moodle server through web services. The token is linked to the current session for the current page request.
734 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
735 * returned token will be somehow passed into the client app being embedded in the page.
4615817d 736 *
2d0acbd5
JP
737 * @param string $servicename name of the web service. Service name as defined in db/services.php
738 * @param int $context context within which the web service can operate.
739 * @return int returns token id.
4615817d 740 * @since Moodle 2.0
2d0acbd5
JP
741 */
742function external_create_service_token($servicename, $context){
743 global $USER, $DB;
744 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
745 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
bc81eadb
JM
746}
747
748/**
749 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
750 *
751 * @param string $component name of component (moodle, mod_assignment, etc.)
752 */
753function external_delete_descriptions($component) {
754 global $DB;
755
756 $params = array($component);
757
758 $DB->delete_records_select('external_tokens',
759 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
760 $DB->delete_records_select('external_services_users',
761 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
762 $DB->delete_records_select('external_services_functions',
763 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
764 $DB->delete_records('external_services', array('component'=>$component));
765 $DB->delete_records('external_functions', array('component'=>$component));
03d38b92
Y
766}
767
768/**
93ce0e82 769 * Standard Moodle web service warnings
03d38b92 770 *
93ce0e82
JM
771 * @package core_webservice
772 * @copyright 2012 Jerome Mouneyrac
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
774 * @since Moodle 2.3
775 */
776class external_warnings extends external_multiple_structure {
777
778 /**
779 * Constructor
780 *
781 * @since Moodle 2.3
782 */
8118dbd0
JM
783 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
784 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
93ce0e82
JM
785
786 parent::__construct(
787 new external_single_structure(
788 array(
8118dbd0
JM
789 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
790 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
791 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
93ce0e82
JM
792 'message' => new external_value(PARAM_TEXT,
793 'untranslated english message to explain the warning')
794 ), 'warning'),
795 'list of warnings', VALUE_OPTIONAL);
796 }
797}
798
799/**
800 * A pre-filled external_value class for text format.
801 *
802 * Default is FORMAT_HTML
803 * This should be used all the time in external xxx_params()/xxx_returns functions
804 * as it is the standard way to implement text format param/return values.
805 *
806 * @package core_webservice
807 * @copyright 2012 Jerome Mouneyrac
808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
809 * @since Moodle 2.3
03d38b92 810 */
93ce0e82
JM
811class external_format_value extends external_value {
812
813 /**
814 * Constructor
815 *
816 * @param string $textfieldname Name of the text field
817 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
818 * @since Moodle 2.3
819 */
820 public function __construct($textfieldname, $required = VALUE_REQUIRED) {
821
822 $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;
823
824 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
825 . FORMAT_MOODLE . ' = MOODLE, '
826 . FORMAT_PLAIN . ' = PLAIN or '
827 . FORMAT_MARKDOWN . ' = MARKDOWN)';
828
55e168e3 829 parent::__construct(PARAM_INT, $desc, $required, $default);
93ce0e82
JM
830 }
831}
832
833/**
834 * Validate text field format against known FORMAT_XXX
835 *
836 * @param array $format the format to validate
837 * @return the validated format
838 * @throws coding_exception
5bcfd504 839 * @since Moodle 2.3
93ce0e82
JM
840 */
841function external_validate_format($format) {
842 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
843 if (!in_array($format, $allowedformats)) {
844 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
845 'The format with value=' . $format . ' is not supported by this Moodle site');
846 }
847 return $format;
848}
849
9764aab9
DW
850/**
851 * Format the string to be returned properly as requested by the either the web service server,
852 * either by an internally call.
853 * The caller can change the format (raw) with the external_settings singleton
854 * All web service servers must set this singleton when parsing the $_GET and $_POST.
855 *
1d014075
FM
856 * <pre>
857 * Options are the same that in {@link format_string()} with some changes:
858 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
859 * </pre>
860 *
9764aab9
DW
861 * @param string $str The string to be filtered. Should be plain text, expect
862 * possibly for multilang tags.
863 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
864 * @param int $contextid The id of the context for the string (affects filters).
865 * @param array $options options array/object or courseid
866 * @return string text
867 * @since Moodle 3.0
868 */
869function external_format_string($str, $contextid, $striplinks = true, $options = array()) {
870
871 // Get settings (singleton).
872 $settings = external_settings::get_instance();
873 if (empty($contextid)) {
874 throw new coding_exception('contextid is required');
875 }
876
877 if (!$settings->get_raw()) {
878 $context = context::instance_by_id($contextid);
879 $options['context'] = $context;
1d014075 880 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
9764aab9
DW
881 $str = format_string($str, $striplinks, $options);
882 }
883
884 return $str;
885}
886
93ce0e82
JM
887/**
888 * Format the text to be returned properly as requested by the either the web service server,
889 * either by an internally call.
890 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
891 * All web service servers must set this singleton when parsing the $_GET and $_POST.
892 *
19a131ed
PFO
893 * <pre>
894 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
895 * trusted : If true the string won't be cleaned. Default false.
896 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
897 * nocache : If true the string will not be cached and will be formatted every call. Default false.
1d014075 898 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
19a131ed
PFO
899 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
900 * Default changed because div tags are not commonly needed.
901 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
902 * context : Not used! Using contextid parameter instead.
903 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
904 * returned. Default false.
905 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
906 * format_text) true. Default changed id attributes are commonly needed.
907 * </pre>
908 *
93ce0e82 909 * @param string $text The content that may contain ULRs in need of rewriting.
c4a15021 910 * @param int $textformat The text format.
93ce0e82
JM
911 * @param int $contextid This parameter and the next two identify the file area to use.
912 * @param string $component
913 * @param string $filearea helps identify the file area.
914 * @param int $itemid helps identify the file area.
19a131ed 915 * @param object/array $options text formatting options
93ce0e82
JM
916 * @return array text + textformat
917 * @since Moodle 2.3
918 */
19a131ed 919function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid, $options = null) {
93ce0e82
JM
920 global $CFG;
921
922 // Get settings (singleton).
923 $settings = external_settings::get_instance();
924
925 if ($settings->get_fileurl()) {
ea29059e 926 require_once($CFG->libdir . "/filelib.php");
93ce0e82
JM
927 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
928 }
929
930 if (!$settings->get_raw()) {
19a131ed
PFO
931 $options = (array)$options;
932
933 // If context is passed in options, check that is the same to show a debug message.
934 if (isset($options['context'])) {
935 if ((is_object($options['context']) && $options['context']->id != $contextid)
b1a9804a 936 || (!is_object($options['context']) && $options['context'] != $contextid)) {
19a131ed
PFO
937 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
938 Using $contextid parameter...', DEBUG_DEVELOPER);
939 }
940 }
941
1d014075 942 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
19a131ed
PFO
943 $options['para'] = isset($options['para']) ? $options['para'] : false;
944 $options['context'] = context::instance_by_id($contextid);
945 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
946
947 $text = format_text($text, $textformat, $options);
c4a15021 948 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
93ce0e82
JM
949 }
950
951 return array($text, $textformat);
952}
953
954/**
955 * Singleton to handle the external settings.
956 *
957 * We use singleton to encapsulate the "logic"
958 *
959 * @package core_webservice
960 * @copyright 2012 Jerome Mouneyrac
961 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
962 * @since Moodle 2.3
963 */
964class external_settings {
965
966 /** @var object the singleton instance */
967 public static $instance = null;
968
969 /** @var boolean Should the external function return raw text or formatted */
970 private $raw = false;
971
972 /** @var boolean Should the external function filter the text */
973 private $filter = false;
974
975 /** @var boolean Should the external function rewrite plugin file url */
976 private $fileurl = true;
977
978 /** @var string In which file should the urls be rewritten */
979 private $file = 'webservice/pluginfile.php';
980
981 /**
982 * Constructor - protected - can not be instanciated
983 */
984 protected function __construct() {
9764aab9
DW
985 if (!defined('AJAX_SCRIPT') && !defined('CLI_SCRIPT') && !defined('WS_SERVER')) {
986 // For normal pages, the default should match the default for format_text.
987 $this->filter = true;
988 }
93ce0e82
JM
989 }
990
991 /**
992 * Clone - private - can not be cloned
993 */
994 private final function __clone() {
995 }
996
997 /**
998 * Return only one instance
999 *
1000 * @return object
1001 */
1002 public static function get_instance() {
1003 if (self::$instance === null) {
1004 self::$instance = new external_settings;
1005 }
1006
1007 return self::$instance;
1008 }
1009
1010 /**
1011 * Set raw
1012 *
1013 * @param boolean $raw
1014 */
1015 public function set_raw($raw) {
1016 $this->raw = $raw;
1017 }
1018
1019 /**
1020 * Get raw
1021 *
1022 * @return boolean
1023 */
1024 public function get_raw() {
1025 return $this->raw;
1026 }
1027
1028 /**
1029 * Set filter
1030 *
1031 * @param boolean $filter
1032 */
1033 public function set_filter($filter) {
1034 $this->filter = $filter;
1035 }
1036
1037 /**
1038 * Get filter
1039 *
1040 * @return boolean
1041 */
1042 public function get_filter() {
1043 return $this->filter;
1044 }
1045
1046 /**
1047 * Set fileurl
1048 *
1049 * @param boolean $fileurl
1050 */
1051 public function set_fileurl($fileurl) {
1052 $this->fileurl = $fileurl;
1053 }
1054
1055 /**
1056 * Get fileurl
1057 *
1058 * @return boolean
1059 */
1060 public function get_fileurl() {
1061 return $this->fileurl;
1062 }
1063
1064 /**
1065 * Set file
1066 *
1067 * @param string $file
1068 */
1069 public function set_file($file) {
1070 $this->file = $file;
1071 }
1072
1073 /**
1074 * Get file
1075 *
1076 * @return string
1077 */
1078 public function get_file() {
1079 return $this->file;
1080 }
50f9449f 1081}
82f0f5e3
JL
1082
1083/**
1084 * Utility functions for the external API.
1085 *
1086 * @package core_webservice
1087 * @copyright 2015 Juan Leyva
1088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1089 * @since Moodle 3.0
1090 */
1091class external_util {
1092
1093 /**
1094 * Validate a list of courses, returning the complete course objects for valid courses.
1095 *
1096 * @param array $courseids A list of course ids
b80ede13 1097 * @param array $courses An array of courses already pre-fetched, indexed by course id.
82f0f5e3
JL
1098 * @return array An array of courses and the validation warnings
1099 */
4b11af96 1100 public static function validate_courses($courseids, $courses = array()) {
82f0f5e3
JL
1101 // Delete duplicates.
1102 $courseids = array_unique($courseids);
82f0f5e3
JL
1103 $warnings = array();
1104
4b11af96
FM
1105 // Remove courses which are not even requested.
1106 $courses = array_intersect_key($courses, array_flip($courseids));
1107
82f0f5e3
JL
1108 foreach ($courseids as $cid) {
1109 // Check the user can function in this context.
1110 try {
1111 $context = context_course::instance($cid);
1112 external_api::validate_context($context);
4b11af96
FM
1113
1114 if (!isset($courses[$cid])) {
1115 $courses[$cid] = get_course($cid);
1116 }
82f0f5e3 1117 } catch (Exception $e) {
4b11af96 1118 unset($courses[$cid]);
82f0f5e3
JL
1119 $warnings[] = array(
1120 'item' => 'course',
1121 'itemid' => $cid,
1122 'warningcode' => '1',
1123 'message' => 'No access rights in course context'
1124 );
1125 }
1126 }
1127
1128 return array($courses, $warnings);
1129 }
1130
1131}