MDL-50782 Ajax: No require_login for all ajax webservice calls
[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
5593d2dc 28/**
bff11d29 29 * Returns detailed function information
4615817d 30 *
5593d2dc 31 * @param string|object $function name of external function or record from external_function
32 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
33 * MUST_EXIST means throw exception if no record or multiple records found
4615817d
JM
34 * @return stdClass description or false if not found or exception thrown
35 * @since Moodle 2.0
5593d2dc 36 */
37function external_function_info($function, $strictness=MUST_EXIST) {
38 global $DB, $CFG;
39
40 if (!is_object($function)) {
41 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
42 return false;
43 }
44 }
45
ed57d984
46 // First try class autoloading.
47 if (!class_exists($function->classname)) {
48 // Fallback to explicit include of externallib.php.
49 $function->classpath = empty($function->classpath) ? core_component::get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
50 if (!file_exists($function->classpath)) {
51 throw new coding_exception('Cannot find file with external function implementation');
52 }
53 require_once($function->classpath);
54 if (!class_exists($function->classname)) {
55 throw new coding_exception('Cannot find external class');
56 }
5593d2dc 57 }
5593d2dc 58
72f8324e 59 $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
5593d2dc 60 $function->parameters_method = $function->methodname.'_parameters';
61 $function->returns_method = $function->methodname.'_returns';
3c1aa6fd 62 $function->deprecated_method = $function->methodname.'_is_deprecated';
5593d2dc 63
64 // make sure the implementaion class is ok
65 if (!method_exists($function->classname, $function->methodname)) {
203fda8a 66 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
5593d2dc 67 }
68 if (!method_exists($function->classname, $function->parameters_method)) {
69 throw new coding_exception('Missing parameters description');
70 }
71 if (!method_exists($function->classname, $function->returns_method)) {
72 throw new coding_exception('Missing returned values description');
73 }
3c1aa6fd
DM
74 if (method_exists($function->classname, $function->deprecated_method)) {
75 if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
76 $function->deprecated = true;
77 }
78 }
72f8324e
DW
79 $function->allowed_from_ajax = false;
80 if (method_exists($function->classname, $function->ajax_method)) {
81 if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
82 $function->allowed_from_ajax = true;
83 }
84 }
5593d2dc 85
86 // fetch the parameters description
87 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
88 if (!($function->parameters_desc instanceof external_function_parameters)) {
89 throw new coding_exception('Invalid parameters description');
90 }
91
92 // fetch the return values description
93 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
94 // null means void result or result is ignored
95 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
96 throw new coding_exception('Invalid return description');
97 }
98
99 //now get the function description
4615817d 100 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
23e7b7cc 101 // easy to understand descriptions in admin UI,
5593d2dc 102 // on the other hand this is still a bit in a flux and we need to find some new naming
103 // conventions for these descriptions in lang packs
104 $function->description = null;
b0d1d941 105 $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
5593d2dc 106 if (file_exists($servicesfile)) {
107 $functions = null;
108 include($servicesfile);
109 if (isset($functions[$function->name]['description'])) {
110 $function->description = $functions[$function->name]['description'];
111 }
048f3d32
TH
112 if (isset($functions[$function->name]['testclientpath'])) {
113 $function->testclientpath = $functions[$function->name]['testclientpath'];
114 }
5d8c1987
DW
115 if (isset($functions[$function->name]['type'])) {
116 $function->type = $functions[$function->name]['type'];
117 }
118 if (isset($functions[$function->name]['loginrequired'])) {
119 $function->loginrequired = $functions[$function->name]['loginrequired'];
120 } else {
121 $function->loginrequired = true;
122 }
5593d2dc 123 }
124
125 return $function;
126}
127
9a0df45a 128/**
4615817d
JM
129 * Exception indicating user is not allowed to use external function in the current context.
130 *
131 * @package core_webservice
132 * @copyright 2009 Petr Skodak
133 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
134 * @since Moodle 2.0
9a0df45a 135 */
136class restricted_context_exception extends moodle_exception {
137 /**
138 * Constructor
4615817d
JM
139 *
140 * @since Moodle 2.0
9a0df45a 141 */
142 function __construct() {
143 parent::__construct('restrictedcontextexception', 'error');
144 }
145}
146
147/**
148 * Base class for external api methods.
4615817d
JM
149 *
150 * @package core_webservice
151 * @copyright 2009 Petr Skodak
152 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
153 * @since Moodle 2.0
9a0df45a 154 */
155class external_api {
4615817d
JM
156
157 /** @var stdClass context where the function calls will be restricted */
9a0df45a 158 private static $contextrestriction;
159
1bea0c27 160 /**
23e7b7cc 161 * Set context restriction for all following subsequent function calls.
4615817d
JM
162 *
163 * @param stdClass $context the context restriction
164 * @since Moodle 2.0
1bea0c27 165 */
2965d271 166 public static function set_context_restriction($context) {
9a0df45a 167 self::$contextrestriction = $context;
168 }
169
2965d271 170 /**
171 * This method has to be called before every operation
172 * that takes a longer time to finish!
173 *
174 * @param int $seconds max expected time the next operation needs
4615817d 175 * @since Moodle 2.0
2965d271 176 */
177 public static function set_timeout($seconds=360) {
178 $seconds = ($seconds < 300) ? 300 : $seconds;
3ef7279f 179 core_php_time_limit::raise($seconds);
2965d271 180 }
181
1bea0c27 182 /**
c9c5cc81 183 * Validates submitted function parameters, if anything is incorrect
1bea0c27 184 * invalid_parameter_exception is thrown.
1d7db36f 185 * This is a simple recursive method which is intended to be called from
186 * each implementation method of external API.
4615817d 187 *
c9c5cc81 188 * @param external_description $description description of parameters
189 * @param mixed $params the actual parameters
190 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
4615817d 191 * @since Moodle 2.0
1bea0c27 192 */
c9c5cc81 193 public static function validate_parameters(external_description $description, $params) {
04d212ce 194 if ($description instanceof external_value) {
c9c5cc81 195 if (is_array($params) or is_object($params)) {
93602569 196 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
c9c5cc81 197 }
4f0c6ad1
PS
198
199 if ($description->type == PARAM_BOOL) {
200 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
201 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
202 return (bool)$params;
203 }
204 }
93602569
JM
205 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
206 '", the server was expecting "' . $description->type . '" type';
207 return validate_param($params, $description->type, $description->allownull, $debuginfo);
4f0c2d00 208
c9c5cc81 209 } else if ($description instanceof external_single_structure) {
210 if (!is_array($params)) {
93602569
JM
211 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
212 . print_r($params, true) . '\'');
c9c5cc81 213 }
214 $result = array();
215 foreach ($description->keys as $key=>$subdesc) {
216 if (!array_key_exists($key, $params)) {
382b9cea 217 if ($subdesc->required == VALUE_REQUIRED) {
93602569 218 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
c9c5cc81 219 }
774b1b0f 220 if ($subdesc->required == VALUE_DEFAULT) {
221 try {
222 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
223 } catch (invalid_parameter_exception $e) {
93602569
JM
224 //we are only interested by exceptions returned by validate_param() and validate_parameters()
225 //(in order to build the path to the faulty attribut)
226 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
382b9cea 227 }
774b1b0f 228 }
c9c5cc81 229 } else {
559a5dbd 230 try {
231 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
232 } catch (invalid_parameter_exception $e) {
93602569
JM
233 //we are only interested by exceptions returned by validate_param() and validate_parameters()
234 //(in order to build the path to the faulty attribut)
235 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
559a5dbd 236 }
c9c5cc81 237 }
238 unset($params[$key]);
239 }
240 if (!empty($params)) {
92fe97f9 241 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
c9c5cc81 242 }
243 return $result;
1bea0c27 244
c9c5cc81 245 } else if ($description instanceof external_multiple_structure) {
246 if (!is_array($params)) {
93602569
JM
247 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
248 . print_r($params, true) . '\'');
c9c5cc81 249 }
250 $result = array();
251 foreach ($params as $param) {
252 $result[] = self::validate_parameters($description->content, $param);
253 }
254 return $result;
255
256 } else {
93602569 257 throw new invalid_parameter_exception('Invalid external api description');
c9c5cc81 258 }
1bea0c27 259 }
260
d07ff72d 261 /**
262 * Clean response
23e7b7cc
PS
263 * If a response attribute is unknown from the description, we just ignore the attribute.
264 * If a response attribute is incorrect, invalid_response_exception is thrown.
d07ff72d 265 * Note: this function is similar to validate parameters, however it is distinct because
266 * parameters validation must be distinct from cleaning return values.
4615817d 267 *
d07ff72d 268 * @param external_description $description description of the return values
269 * @param mixed $response the actual response
270 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
4615817d
JM
271 * @author 2010 Jerome Mouneyrac
272 * @since Moodle 2.0
d07ff72d 273 */
274 public static function clean_returnvalue(external_description $description, $response) {
275 if ($description instanceof external_value) {
276 if (is_array($response) or is_object($response)) {
93602569 277 throw new invalid_response_exception('Scalar type expected, array or object received.');
d07ff72d 278 }
279
280 if ($description->type == PARAM_BOOL) {
281 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
282 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
283 return (bool)$response;
284 }
285 }
93602569
JM
286 $debuginfo = 'Invalid external api response: the value is "' . $response .
287 '", the server was expecting "' . $description->type . '" type';
288 try {
289 return validate_param($response, $description->type, $description->allownull, $debuginfo);
290 } catch (invalid_parameter_exception $e) {
291 //proper exception name, to be recursively catched to build the path to the faulty attribut
292 throw new invalid_response_exception($e->debuginfo);
293 }
d07ff72d 294
295 } else if ($description instanceof external_single_structure) {
9a4c2f50
JM
296 if (!is_array($response) && !is_object($response)) {
297 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
93602569 298 print_r($response, true) . '\'');
d07ff72d 299 }
9a4c2f50
JM
300
301 // Cast objects into arrays.
302 if (is_object($response)) {
303 $response = (array) $response;
304 }
305
d07ff72d 306 $result = array();
307 foreach ($description->keys as $key=>$subdesc) {
308 if (!array_key_exists($key, $response)) {
309 if ($subdesc->required == VALUE_REQUIRED) {
93602569 310 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
d07ff72d 311 }
312 if ($subdesc instanceof external_value) {
143c0abe 313 if ($subdesc->required == VALUE_DEFAULT) {
314 try {
d07ff72d 315 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
93602569
JM
316 } catch (invalid_response_exception $e) {
317 //build the path to the faulty attribut
318 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 319 }
320 }
143c0abe 321 }
d07ff72d 322 } else {
323 try {
324 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
93602569
JM
325 } catch (invalid_response_exception $e) {
326 //build the path to the faulty attribut
327 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 328 }
329 }
330 unset($response[$key]);
331 }
332
333 return $result;
334
335 } else if ($description instanceof external_multiple_structure) {
336 if (!is_array($response)) {
93602569
JM
337 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
338 print_r($response, true) . '\'');
d07ff72d 339 }
340 $result = array();
341 foreach ($response as $param) {
342 $result[] = self::clean_returnvalue($description->content, $param);
343 }
344 return $result;
345
346 } else {
93602569 347 throw new invalid_response_exception('Invalid external api response description');
d07ff72d 348 }
349 }
350
9a0df45a 351 /**
352 * Makes sure user may execute functions in this context.
4615817d
JM
353 *
354 * @param stdClass $context
355 * @since Moodle 2.0
9a0df45a 356 */
357 protected static function validate_context($context) {
4f0c2d00
PS
358 global $CFG;
359
ab9a01f2 360 if (empty($context)) {
361 throw new invalid_parameter_exception('Context does not exist');
362 }
9a0df45a 363 if (empty(self::$contextrestriction)) {
b0c6dc1c 364 self::$contextrestriction = context_system::instance();
9a0df45a 365 }
366 $rcontext = self::$contextrestriction;
367
368 if ($rcontext->contextlevel == $context->contextlevel) {
aa7fbebd 369 if ($rcontext->id != $context->id) {
9a0df45a 370 throw new restricted_context_exception();
371 }
372 } else if ($rcontext->contextlevel > $context->contextlevel) {
373 throw new restricted_context_exception();
374 } else {
8e8891b7 375 $parents = $context->get_parent_context_ids();
9a0df45a 376 if (!in_array($rcontext->id, $parents)) {
377 throw new restricted_context_exception();
378 }
379 }
380
381 if ($context->contextlevel >= CONTEXT_COURSE) {
4f0c2d00 382 list($context, $course, $cm) = get_context_info_array($context->id);
df997f84 383 require_login($course, false, $cm, false, true);
9a0df45a 384 }
385 }
aac70ffc
AA
386
387 /**
5b23d9ad
AA
388 * Get context from passed parameters.
389 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
390 * For example, the context level can be "course" and instanceid can be courseid.
391 *
392 * See context_helper::get_all_levels() for a list of valid context levels.
aac70ffc
AA
393 *
394 * @param array $param
395 * @since Moodle 2.6
396 * @throws invalid_parameter_exception
397 * @return context
398 */
5b23d9ad 399 protected static function get_context_from_params($param) {
aac70ffc 400 $levels = context_helper::get_all_levels();
98dece22 401 if (!empty($param['contextid'])) {
aac70ffc 402 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
eac1383e 403 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
aac70ffc
AA
404 $contextlevel = "context_".$param['contextlevel'];
405 if (!array_search($contextlevel, $levels)) {
406 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
407 }
408 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
409 } else {
410 // No valid context info was found.
411 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
412 }
413 }
9a0df45a 414}
415
b038c32c 416/**
417 * Common ancestor of all parameter description classes
4615817d
JM
418 *
419 * @package core_webservice
420 * @copyright 2009 Petr Skodak
421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
422 * @since Moodle 2.0
b038c32c 423 */
424abstract class external_description {
4615817d 425 /** @var string Description of element */
b038c32c 426 public $desc;
4615817d
JM
427
428 /** @var bool Element value required, null not allowed */
b038c32c 429 public $required;
4615817d
JM
430
431 /** @var mixed Default value */
774b1b0f 432 public $default;
b038c32c 433
434 /**
435 * Contructor
4615817d 436 *
b038c32c 437 * @param string $desc
438 * @param bool $required
774b1b0f 439 * @param mixed $default
4615817d 440 * @since Moodle 2.0
b038c32c 441 */
774b1b0f 442 public function __construct($desc, $required, $default) {
b038c32c 443 $this->desc = $desc;
444 $this->required = $required;
774b1b0f 445 $this->default = $default;
b038c32c 446 }
447}
448
449/**
4615817d
JM
450 * Scalar value description class
451 *
452 * @package core_webservice
453 * @copyright 2009 Petr Skodak
454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
455 * @since Moodle 2.0
b038c32c 456 */
04d212ce 457class external_value extends external_description {
4615817d
JM
458
459 /** @var mixed Value type PARAM_XX */
b038c32c 460 public $type;
4615817d
JM
461
462 /** @var bool Allow null values */
b038c32c 463 public $allownull;
464
465 /**
466 * Constructor
4615817d 467 *
b038c32c 468 * @param mixed $type
469 * @param string $desc
470 * @param bool $required
471 * @param mixed $default
472 * @param bool $allownull
4615817d 473 * @since Moodle 2.0
b038c32c 474 */
774b1b0f 475 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
476 $default=null, $allownull=NULL_ALLOWED) {
477 parent::__construct($desc, $required, $default);
78bfb562 478 $this->type = $type;
b038c32c 479 $this->allownull = $allownull;
480 }
481}
482
483/**
484 * Associative array description class
4615817d
JM
485 *
486 * @package core_webservice
487 * @copyright 2009 Petr Skodak
488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
489 * @since Moodle 2.0
b038c32c 490 */
491class external_single_structure extends external_description {
4615817d
JM
492
493 /** @var array Description of array keys key=>external_description */
b038c32c 494 public $keys;
495
496 /**
497 * Constructor
4615817d 498 *
b038c32c 499 * @param array $keys
500 * @param string $desc
501 * @param bool $required
774b1b0f 502 * @param array $default
4615817d 503 * @since Moodle 2.0
b038c32c 504 */
774b1b0f 505 public function __construct(array $keys, $desc='',
506 $required=VALUE_REQUIRED, $default=null) {
507 parent::__construct($desc, $required, $default);
b038c32c 508 $this->keys = $keys;
509 }
510}
511
512/**
513 * Bulk array description class.
4615817d
JM
514 *
515 * @package core_webservice
516 * @copyright 2009 Petr Skodak
517 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
518 * @since Moodle 2.0
b038c32c 519 */
520class external_multiple_structure extends external_description {
4615817d
JM
521
522 /** @var external_description content */
b038c32c 523 public $content;
524
525 /**
526 * Constructor
4615817d 527 *
b038c32c 528 * @param external_description $content
529 * @param string $desc
530 * @param bool $required
774b1b0f 531 * @param array $default
4615817d 532 * @since Moodle 2.0
b038c32c 533 */
774b1b0f 534 public function __construct(external_description $content, $desc='',
535 $required=VALUE_REQUIRED, $default=null) {
536 parent::__construct($desc, $required, $default);
b038c32c 537 $this->content = $content;
538 }
539}
c29cca30 540
541/**
542 * Description of top level - PHP function parameters.
c29cca30 543 *
4615817d
JM
544 * @package core_webservice
545 * @copyright 2009 Petr Skodak
546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
547 * @since Moodle 2.0
c29cca30 548 */
549class external_function_parameters extends external_single_structure {
550}
2822f40a 551
4615817d
JM
552/**
553 * Generate a token
554 *
555 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
556 * @param stdClass|int $serviceorid service linked to the token
557 * @param int $userid user linked to the token
558 * @param stdClass|int $contextorid
559 * @param int $validuntil date when the token expired
560 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
561 * @return string generated token
562 * @author 2010 Jamie Pratt
563 * @since Moodle 2.0
564 */
2822f40a
JP
565function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
566 global $DB, $USER;
567 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
568 $numtries = 0;
569 do {
570 $numtries ++;
571 $generatedtoken = md5(uniqid(rand(),1));
572 if ($numtries > 5){
573 throw new moodle_exception('tokengenerationfailed');
574 }
575 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
365a5941 576 $newtoken = new stdClass();
2822f40a
JP
577 $newtoken->token = $generatedtoken;
578 if (!is_object($serviceorid)){
579 $service = $DB->get_record('external_services', array('id' => $serviceorid));
580 } else {
581 $service = $serviceorid;
582 }
583 if (!is_object($contextorid)){
d197ea43 584 $context = context::instance_by_id($contextorid, MUST_EXIST);
2822f40a
JP
585 } else {
586 $context = $contextorid;
587 }
588 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
589 $newtoken->externalserviceid = $service->id;
590 } else {
591 throw new moodle_exception('nocapabilitytousethisservice');
592 }
593 $newtoken->tokentype = $tokentype;
594 $newtoken->userid = $userid;
2d0acbd5
JP
595 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
596 $newtoken->sid = session_id();
597 }
4f0c2d00
PS
598
599 $newtoken->contextid = $context->id;
2822f40a
JP
600 $newtoken->creatorid = $USER->id;
601 $newtoken->timecreated = time();
602 $newtoken->validuntil = $validuntil;
603 if (!empty($iprestriction)) {
604 $newtoken->iprestriction = $iprestriction;
605 }
606 $DB->insert_record('external_tokens', $newtoken);
607 return $newtoken->token;
2d0acbd5 608}
4615817d 609
2d0acbd5 610/**
df997f84 611 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
2d0acbd5
JP
612 * with the Moodle server through web services. The token is linked to the current session for the current page request.
613 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
614 * returned token will be somehow passed into the client app being embedded in the page.
4615817d 615 *
2d0acbd5
JP
616 * @param string $servicename name of the web service. Service name as defined in db/services.php
617 * @param int $context context within which the web service can operate.
618 * @return int returns token id.
4615817d 619 * @since Moodle 2.0
2d0acbd5
JP
620 */
621function external_create_service_token($servicename, $context){
622 global $USER, $DB;
623 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
624 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
bc81eadb
JM
625}
626
627/**
628 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
629 *
630 * @param string $component name of component (moodle, mod_assignment, etc.)
631 */
632function external_delete_descriptions($component) {
633 global $DB;
634
635 $params = array($component);
636
637 $DB->delete_records_select('external_tokens',
638 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
639 $DB->delete_records_select('external_services_users',
640 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
641 $DB->delete_records_select('external_services_functions',
642 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
643 $DB->delete_records('external_services', array('component'=>$component));
644 $DB->delete_records('external_functions', array('component'=>$component));
03d38b92
Y
645}
646
647/**
93ce0e82 648 * Standard Moodle web service warnings
03d38b92 649 *
93ce0e82
JM
650 * @package core_webservice
651 * @copyright 2012 Jerome Mouneyrac
652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
653 * @since Moodle 2.3
654 */
655class external_warnings extends external_multiple_structure {
656
657 /**
658 * Constructor
659 *
660 * @since Moodle 2.3
661 */
8118dbd0
JM
662 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
663 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
93ce0e82
JM
664
665 parent::__construct(
666 new external_single_structure(
667 array(
8118dbd0
JM
668 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
669 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
670 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
93ce0e82
JM
671 'message' => new external_value(PARAM_TEXT,
672 'untranslated english message to explain the warning')
673 ), 'warning'),
674 'list of warnings', VALUE_OPTIONAL);
675 }
676}
677
678/**
679 * A pre-filled external_value class for text format.
680 *
681 * Default is FORMAT_HTML
682 * This should be used all the time in external xxx_params()/xxx_returns functions
683 * as it is the standard way to implement text format param/return values.
684 *
685 * @package core_webservice
686 * @copyright 2012 Jerome Mouneyrac
687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
688 * @since Moodle 2.3
03d38b92 689 */
93ce0e82
JM
690class external_format_value extends external_value {
691
692 /**
693 * Constructor
694 *
695 * @param string $textfieldname Name of the text field
696 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
697 * @since Moodle 2.3
698 */
699 public function __construct($textfieldname, $required = VALUE_REQUIRED) {
700
701 $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;
702
703 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
704 . FORMAT_MOODLE . ' = MOODLE, '
705 . FORMAT_PLAIN . ' = PLAIN or '
706 . FORMAT_MARKDOWN . ' = MARKDOWN)';
707
55e168e3 708 parent::__construct(PARAM_INT, $desc, $required, $default);
93ce0e82
JM
709 }
710}
711
712/**
713 * Validate text field format against known FORMAT_XXX
714 *
715 * @param array $format the format to validate
716 * @return the validated format
717 * @throws coding_exception
5bcfd504 718 * @since Moodle 2.3
93ce0e82
JM
719 */
720function external_validate_format($format) {
721 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
722 if (!in_array($format, $allowedformats)) {
723 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
724 'The format with value=' . $format . ' is not supported by this Moodle site');
725 }
726 return $format;
727}
728
729/**
730 * Format the text to be returned properly as requested by the either the web service server,
731 * either by an internally call.
732 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
733 * All web service servers must set this singleton when parsing the $_GET and $_POST.
734 *
735 * @param string $text The content that may contain ULRs in need of rewriting.
c4a15021 736 * @param int $textformat The text format.
93ce0e82
JM
737 * @param int $contextid This parameter and the next two identify the file area to use.
738 * @param string $component
739 * @param string $filearea helps identify the file area.
740 * @param int $itemid helps identify the file area.
741 * @return array text + textformat
742 * @since Moodle 2.3
743 */
744function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid) {
745 global $CFG;
746
747 // Get settings (singleton).
748 $settings = external_settings::get_instance();
749
750 if ($settings->get_fileurl()) {
ea29059e 751 require_once($CFG->libdir . "/filelib.php");
93ce0e82
JM
752 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
753 }
754
755 if (!$settings->get_raw()) {
c4a15021
JL
756 $text = format_text($text, $textformat, array('para' => false, 'filter' => $settings->get_filter()));
757 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
93ce0e82
JM
758 }
759
760 return array($text, $textformat);
761}
762
763/**
764 * Singleton to handle the external settings.
765 *
766 * We use singleton to encapsulate the "logic"
767 *
768 * @package core_webservice
769 * @copyright 2012 Jerome Mouneyrac
770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
771 * @since Moodle 2.3
772 */
773class external_settings {
774
775 /** @var object the singleton instance */
776 public static $instance = null;
777
778 /** @var boolean Should the external function return raw text or formatted */
779 private $raw = false;
780
781 /** @var boolean Should the external function filter the text */
782 private $filter = false;
783
784 /** @var boolean Should the external function rewrite plugin file url */
785 private $fileurl = true;
786
787 /** @var string In which file should the urls be rewritten */
788 private $file = 'webservice/pluginfile.php';
789
790 /**
791 * Constructor - protected - can not be instanciated
792 */
793 protected function __construct() {
794 }
795
796 /**
797 * Clone - private - can not be cloned
798 */
799 private final function __clone() {
800 }
801
802 /**
803 * Return only one instance
804 *
805 * @return object
806 */
807 public static function get_instance() {
808 if (self::$instance === null) {
809 self::$instance = new external_settings;
810 }
811
812 return self::$instance;
813 }
814
815 /**
816 * Set raw
817 *
818 * @param boolean $raw
819 */
820 public function set_raw($raw) {
821 $this->raw = $raw;
822 }
823
824 /**
825 * Get raw
826 *
827 * @return boolean
828 */
829 public function get_raw() {
830 return $this->raw;
831 }
832
833 /**
834 * Set filter
835 *
836 * @param boolean $filter
837 */
838 public function set_filter($filter) {
839 $this->filter = $filter;
840 }
841
842 /**
843 * Get filter
844 *
845 * @return boolean
846 */
847 public function get_filter() {
848 return $this->filter;
849 }
850
851 /**
852 * Set fileurl
853 *
854 * @param boolean $fileurl
855 */
856 public function set_fileurl($fileurl) {
857 $this->fileurl = $fileurl;
858 }
859
860 /**
861 * Get fileurl
862 *
863 * @return boolean
864 */
865 public function get_fileurl() {
866 return $this->fileurl;
867 }
868
869 /**
870 * Set file
871 *
872 * @param string $file
873 */
874 public function set_file($file) {
875 $this->file = $file;
876 }
877
878 /**
879 * Get file
880 *
881 * @return string
882 */
883 public function get_file() {
884 return $this->file;
885 }
50f9449f 886}