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