MDL-34011 Lesson module: fixed incorrect display of student attempt for short answer...
[moodle.git] / lib / externallib.php
blobda21ace392edd9708b83dc1c7d9063182624d5ae
1 <?php
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.
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/>.
18 /**
19 * Support for external API
21 * @package core_webservice
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * Returns detailed function information
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
34 * @return stdClass description or false if not found or exception thrown
35 * @since Moodle 2.0
37 function external_function_info($function, $strictness=MUST_EXIST) {
38 global $DB, $CFG;
40 if (!is_object($function)) {
41 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
42 return false;
46 //first find and include the ext implementation class
47 $function->classpath = empty($function->classpath) ? get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
48 if (!file_exists($function->classpath)) {
49 throw new coding_exception('Can not find file with external function implementation');
51 require_once($function->classpath);
53 $function->parameters_method = $function->methodname.'_parameters';
54 $function->returns_method = $function->methodname.'_returns';
56 // make sure the implementaion class is ok
57 if (!method_exists($function->classname, $function->methodname)) {
58 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
60 if (!method_exists($function->classname, $function->parameters_method)) {
61 throw new coding_exception('Missing parameters description');
63 if (!method_exists($function->classname, $function->returns_method)) {
64 throw new coding_exception('Missing returned values description');
67 // fetch the parameters description
68 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
69 if (!($function->parameters_desc instanceof external_function_parameters)) {
70 throw new coding_exception('Invalid parameters description');
73 // fetch the return values description
74 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
75 // null means void result or result is ignored
76 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
77 throw new coding_exception('Invalid return description');
80 //now get the function description
81 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
82 // easy to understand descriptions in admin UI,
83 // on the other hand this is still a bit in a flux and we need to find some new naming
84 // conventions for these descriptions in lang packs
85 $function->description = null;
86 $servicesfile = get_component_directory($function->component).'/db/services.php';
87 if (file_exists($servicesfile)) {
88 $functions = null;
89 include($servicesfile);
90 if (isset($functions[$function->name]['description'])) {
91 $function->description = $functions[$function->name]['description'];
93 if (isset($functions[$function->name]['testclientpath'])) {
94 $function->testclientpath = $functions[$function->name]['testclientpath'];
98 return $function;
102 * Exception indicating user is not allowed to use external function in the current context.
104 * @package core_webservice
105 * @copyright 2009 Petr Skodak
106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
107 * @since Moodle 2.0
109 class restricted_context_exception extends moodle_exception {
111 * Constructor
113 * @since Moodle 2.0
115 function __construct() {
116 parent::__construct('restrictedcontextexception', 'error');
121 * Base class for external api methods.
123 * @package core_webservice
124 * @copyright 2009 Petr Skodak
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 * @since Moodle 2.0
128 class external_api {
130 /** @var stdClass context where the function calls will be restricted */
131 private static $contextrestriction;
134 * Set context restriction for all following subsequent function calls.
136 * @param stdClass $context the context restriction
137 * @since Moodle 2.0
139 public static function set_context_restriction($context) {
140 self::$contextrestriction = $context;
144 * This method has to be called before every operation
145 * that takes a longer time to finish!
147 * @param int $seconds max expected time the next operation needs
148 * @since Moodle 2.0
150 public static function set_timeout($seconds=360) {
151 $seconds = ($seconds < 300) ? 300 : $seconds;
152 set_time_limit($seconds);
156 * Validates submitted function parameters, if anything is incorrect
157 * invalid_parameter_exception is thrown.
158 * This is a simple recursive method which is intended to be called from
159 * each implementation method of external API.
161 * @param external_description $description description of parameters
162 * @param mixed $params the actual parameters
163 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
164 * @since Moodle 2.0
166 public static function validate_parameters(external_description $description, $params) {
167 if ($description instanceof external_value) {
168 if (is_array($params) or is_object($params)) {
169 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
172 if ($description->type == PARAM_BOOL) {
173 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
174 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
175 return (bool)$params;
178 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
179 '", the server was expecting "' . $description->type . '" type';
180 return validate_param($params, $description->type, $description->allownull, $debuginfo);
182 } else if ($description instanceof external_single_structure) {
183 if (!is_array($params)) {
184 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
185 . print_r($params, true) . '\'');
187 $result = array();
188 foreach ($description->keys as $key=>$subdesc) {
189 if (!array_key_exists($key, $params)) {
190 if ($subdesc->required == VALUE_REQUIRED) {
191 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
193 if ($subdesc->required == VALUE_DEFAULT) {
194 try {
195 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
196 } catch (invalid_parameter_exception $e) {
197 //we are only interested by exceptions returned by validate_param() and validate_parameters()
198 //(in order to build the path to the faulty attribut)
199 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
202 } else {
203 try {
204 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
205 } catch (invalid_parameter_exception $e) {
206 //we are only interested by exceptions returned by validate_param() and validate_parameters()
207 //(in order to build the path to the faulty attribut)
208 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
211 unset($params[$key]);
213 if (!empty($params)) {
214 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
216 return $result;
218 } else if ($description instanceof external_multiple_structure) {
219 if (!is_array($params)) {
220 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
221 . print_r($params, true) . '\'');
223 $result = array();
224 foreach ($params as $param) {
225 $result[] = self::validate_parameters($description->content, $param);
227 return $result;
229 } else {
230 throw new invalid_parameter_exception('Invalid external api description');
235 * Clean response
236 * If a response attribute is unknown from the description, we just ignore the attribute.
237 * If a response attribute is incorrect, invalid_response_exception is thrown.
238 * Note: this function is similar to validate parameters, however it is distinct because
239 * parameters validation must be distinct from cleaning return values.
241 * @param external_description $description description of the return values
242 * @param mixed $response the actual response
243 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
244 * @author 2010 Jerome Mouneyrac
245 * @since Moodle 2.0
247 public static function clean_returnvalue(external_description $description, $response) {
248 if ($description instanceof external_value) {
249 if (is_array($response) or is_object($response)) {
250 throw new invalid_response_exception('Scalar type expected, array or object received.');
253 if ($description->type == PARAM_BOOL) {
254 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
255 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
256 return (bool)$response;
259 $debuginfo = 'Invalid external api response: the value is "' . $response .
260 '", the server was expecting "' . $description->type . '" type';
261 try {
262 return validate_param($response, $description->type, $description->allownull, $debuginfo);
263 } catch (invalid_parameter_exception $e) {
264 //proper exception name, to be recursively catched to build the path to the faulty attribut
265 throw new invalid_response_exception($e->debuginfo);
268 } else if ($description instanceof external_single_structure) {
269 if (!is_array($response)) {
270 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
271 print_r($response, true) . '\'');
273 $result = array();
274 foreach ($description->keys as $key=>$subdesc) {
275 if (!array_key_exists($key, $response)) {
276 if ($subdesc->required == VALUE_REQUIRED) {
277 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
279 if ($subdesc instanceof external_value) {
280 if ($subdesc->required == VALUE_DEFAULT) {
281 try {
282 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
283 } catch (invalid_response_exception $e) {
284 //build the path to the faulty attribut
285 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
289 } else {
290 try {
291 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
292 } catch (invalid_response_exception $e) {
293 //build the path to the faulty attribut
294 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
297 unset($response[$key]);
300 return $result;
302 } else if ($description instanceof external_multiple_structure) {
303 if (!is_array($response)) {
304 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
305 print_r($response, true) . '\'');
307 $result = array();
308 foreach ($response as $param) {
309 $result[] = self::clean_returnvalue($description->content, $param);
311 return $result;
313 } else {
314 throw new invalid_response_exception('Invalid external api response description');
319 * Makes sure user may execute functions in this context.
321 * @param stdClass $context
322 * @since Moodle 2.0
324 protected static function validate_context($context) {
325 global $CFG;
327 if (empty($context)) {
328 throw new invalid_parameter_exception('Context does not exist');
330 if (empty(self::$contextrestriction)) {
331 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
333 $rcontext = self::$contextrestriction;
335 if ($rcontext->contextlevel == $context->contextlevel) {
336 if ($rcontext->id != $context->id) {
337 throw new restricted_context_exception();
339 } else if ($rcontext->contextlevel > $context->contextlevel) {
340 throw new restricted_context_exception();
341 } else {
342 $parents = get_parent_contexts($context);
343 if (!in_array($rcontext->id, $parents)) {
344 throw new restricted_context_exception();
348 if ($context->contextlevel >= CONTEXT_COURSE) {
349 list($context, $course, $cm) = get_context_info_array($context->id);
350 require_login($course, false, $cm, false, true);
356 * Common ancestor of all parameter description classes
358 * @package core_webservice
359 * @copyright 2009 Petr Skodak
360 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
361 * @since Moodle 2.0
363 abstract class external_description {
364 /** @var string Description of element */
365 public $desc;
367 /** @var bool Element value required, null not allowed */
368 public $required;
370 /** @var mixed Default value */
371 public $default;
374 * Contructor
376 * @param string $desc
377 * @param bool $required
378 * @param mixed $default
379 * @since Moodle 2.0
381 public function __construct($desc, $required, $default) {
382 $this->desc = $desc;
383 $this->required = $required;
384 $this->default = $default;
389 * Scalar value description class
391 * @package core_webservice
392 * @copyright 2009 Petr Skodak
393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
394 * @since Moodle 2.0
396 class external_value extends external_description {
398 /** @var mixed Value type PARAM_XX */
399 public $type;
401 /** @var bool Allow null values */
402 public $allownull;
405 * Constructor
407 * @param mixed $type
408 * @param string $desc
409 * @param bool $required
410 * @param mixed $default
411 * @param bool $allownull
412 * @since Moodle 2.0
414 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
415 $default=null, $allownull=NULL_ALLOWED) {
416 parent::__construct($desc, $required, $default);
417 $this->type = $type;
418 $this->allownull = $allownull;
423 * Associative array description class
425 * @package core_webservice
426 * @copyright 2009 Petr Skodak
427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
428 * @since Moodle 2.0
430 class external_single_structure extends external_description {
432 /** @var array Description of array keys key=>external_description */
433 public $keys;
436 * Constructor
438 * @param array $keys
439 * @param string $desc
440 * @param bool $required
441 * @param array $default
442 * @since Moodle 2.0
444 public function __construct(array $keys, $desc='',
445 $required=VALUE_REQUIRED, $default=null) {
446 parent::__construct($desc, $required, $default);
447 $this->keys = $keys;
452 * Bulk array description class.
454 * @package core_webservice
455 * @copyright 2009 Petr Skodak
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 * @since Moodle 2.0
459 class external_multiple_structure extends external_description {
461 /** @var external_description content */
462 public $content;
465 * Constructor
467 * @param external_description $content
468 * @param string $desc
469 * @param bool $required
470 * @param array $default
471 * @since Moodle 2.0
473 public function __construct(external_description $content, $desc='',
474 $required=VALUE_REQUIRED, $default=null) {
475 parent::__construct($desc, $required, $default);
476 $this->content = $content;
481 * Description of top level - PHP function parameters.
483 * @package core_webservice
484 * @copyright 2009 Petr Skodak
485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
486 * @since Moodle 2.0
488 class external_function_parameters extends external_single_structure {
492 * Generate a token
494 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
495 * @param stdClass|int $serviceorid service linked to the token
496 * @param int $userid user linked to the token
497 * @param stdClass|int $contextorid
498 * @param int $validuntil date when the token expired
499 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
500 * @return string generated token
501 * @author 2010 Jamie Pratt
502 * @since Moodle 2.0
504 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
505 global $DB, $USER;
506 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
507 $numtries = 0;
508 do {
509 $numtries ++;
510 $generatedtoken = md5(uniqid(rand(),1));
511 if ($numtries > 5){
512 throw new moodle_exception('tokengenerationfailed');
514 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
515 $newtoken = new stdClass();
516 $newtoken->token = $generatedtoken;
517 if (!is_object($serviceorid)){
518 $service = $DB->get_record('external_services', array('id' => $serviceorid));
519 } else {
520 $service = $serviceorid;
522 if (!is_object($contextorid)){
523 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
524 } else {
525 $context = $contextorid;
527 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
528 $newtoken->externalserviceid = $service->id;
529 } else {
530 throw new moodle_exception('nocapabilitytousethisservice');
532 $newtoken->tokentype = $tokentype;
533 $newtoken->userid = $userid;
534 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
535 $newtoken->sid = session_id();
538 $newtoken->contextid = $context->id;
539 $newtoken->creatorid = $USER->id;
540 $newtoken->timecreated = time();
541 $newtoken->validuntil = $validuntil;
542 if (!empty($iprestriction)) {
543 $newtoken->iprestriction = $iprestriction;
545 $DB->insert_record('external_tokens', $newtoken);
546 return $newtoken->token;
550 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
551 * with the Moodle server through web services. The token is linked to the current session for the current page request.
552 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
553 * returned token will be somehow passed into the client app being embedded in the page.
555 * @param string $servicename name of the web service. Service name as defined in db/services.php
556 * @param int $context context within which the web service can operate.
557 * @return int returns token id.
558 * @since Moodle 2.0
560 function external_create_service_token($servicename, $context){
561 global $USER, $DB;
562 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
563 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
567 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
569 * @param string $component name of component (moodle, mod_assignment, etc.)
571 function external_delete_descriptions($component) {
572 global $DB;
574 $params = array($component);
576 $DB->delete_records_select('external_tokens',
577 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
578 $DB->delete_records_select('external_services_users',
579 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
580 $DB->delete_records_select('external_services_functions',
581 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
582 $DB->delete_records('external_services', array('component'=>$component));
583 $DB->delete_records('external_functions', array('component'=>$component));
587 * Standard Moodle web service warnings
589 * @package core_webservice
590 * @copyright 2012 Jerome Mouneyrac
591 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
592 * @since Moodle 2.3
594 class external_warnings extends external_multiple_structure {
597 * Constructor
599 * @since Moodle 2.3
601 public function __construct() {
603 parent::__construct(
604 new external_single_structure(
605 array(
606 'item' => new external_value(PARAM_TEXT, 'item', VALUE_OPTIONAL),
607 'itemid' => new external_value(PARAM_INT, 'item id', VALUE_OPTIONAL),
608 'warningcode' => new external_value(PARAM_ALPHANUM,
609 'the warning code can be used by the client app to implement specific behaviour'),
610 'message' => new external_value(PARAM_TEXT,
611 'untranslated english message to explain the warning')
612 ), 'warning'),
613 'list of warnings', VALUE_OPTIONAL);
618 * A pre-filled external_value class for text format.
620 * Default is FORMAT_HTML
621 * This should be used all the time in external xxx_params()/xxx_returns functions
622 * as it is the standard way to implement text format param/return values.
624 * @package core_webservice
625 * @copyright 2012 Jerome Mouneyrac
626 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
627 * @since Moodle 2.3
629 class external_format_value extends external_value {
632 * Constructor
634 * @param string $textfieldname Name of the text field
635 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
636 * @since Moodle 2.3
638 public function __construct($textfieldname, $required = VALUE_REQUIRED) {
640 $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;
642 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
643 . FORMAT_MOODLE . ' = MOODLE, '
644 . FORMAT_PLAIN . ' = PLAIN or '
645 . FORMAT_MARKDOWN . ' = MARKDOWN)';
647 parent::__construct(PARAM_INT, $desc, $required, $default);
652 * Validate text field format against known FORMAT_XXX
654 * @param array $format the format to validate
655 * @return the validated format
656 * @throws coding_exception
657 * @since 2.3
659 function external_validate_format($format) {
660 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
661 if (!in_array($format, $allowedformats)) {
662 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
663 'The format with value=' . $format . ' is not supported by this Moodle site');
665 return $format;
669 * Format the text to be returned properly as requested by the either the web service server,
670 * either by an internally call.
671 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
672 * All web service servers must set this singleton when parsing the $_GET and $_POST.
674 * @param string $text The content that may contain ULRs in need of rewriting.
675 * @param int $textformat The text format, by default FORMAT_HTML.
676 * @param int $contextid This parameter and the next two identify the file area to use.
677 * @param string $component
678 * @param string $filearea helps identify the file area.
679 * @param int $itemid helps identify the file area.
680 * @return array text + textformat
681 * @since Moodle 2.3
683 function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid) {
684 global $CFG;
686 // Get settings (singleton).
687 $settings = external_settings::get_instance();
689 if ($settings->get_fileurl()) {
690 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
693 if (!$settings->get_raw()) {
694 $textformat = FORMAT_HTML; // Force format to HTML when not raw.
695 $text = format_text($text, $textformat,
696 array('noclean' => true, 'para' => false, 'filter' => $settings->get_filter()));
699 return array($text, $textformat);
703 * Singleton to handle the external settings.
705 * We use singleton to encapsulate the "logic"
707 * @package core_webservice
708 * @copyright 2012 Jerome Mouneyrac
709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
710 * @since Moodle 2.3
712 class external_settings {
714 /** @var object the singleton instance */
715 public static $instance = null;
717 /** @var boolean Should the external function return raw text or formatted */
718 private $raw = false;
720 /** @var boolean Should the external function filter the text */
721 private $filter = false;
723 /** @var boolean Should the external function rewrite plugin file url */
724 private $fileurl = true;
726 /** @var string In which file should the urls be rewritten */
727 private $file = 'webservice/pluginfile.php';
730 * Constructor - protected - can not be instanciated
732 protected function __construct() {
736 * Clone - private - can not be cloned
738 private final function __clone() {
742 * Return only one instance
744 * @return object
746 public static function get_instance() {
747 if (self::$instance === null) {
748 self::$instance = new external_settings;
751 return self::$instance;
755 * Set raw
757 * @param boolean $raw
759 public function set_raw($raw) {
760 $this->raw = $raw;
764 * Get raw
766 * @return boolean
768 public function get_raw() {
769 return $this->raw;
773 * Set filter
775 * @param boolean $filter
777 public function set_filter($filter) {
778 $this->filter = $filter;
782 * Get filter
784 * @return boolean
786 public function get_filter() {
787 return $this->filter;
791 * Set fileurl
793 * @param boolean $fileurl
795 public function set_fileurl($fileurl) {
796 $this->fileurl = $fileurl;
800 * Get fileurl
802 * @return boolean
804 public function get_fileurl() {
805 return $this->fileurl;
809 * Set file
811 * @param string $file
813 public function set_file($file) {
814 $this->file = $file;
818 * Get file
820 * @return string
822 public function get_file() {
823 return $this->file;