Moodle release 2.8.9
[moodle.git] / lib / externallib.php
blobf69050a4366a5e6e89993be653ca33cffec6794a
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 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: ' . $function->classname);
53 require_once($function->classpath);
54 if (!class_exists($function->classname)) {
55 throw new coding_exception('Cannot find external class');
59 $function->parameters_method = $function->methodname.'_parameters';
60 $function->returns_method = $function->methodname.'_returns';
62 // make sure the implementaion class is ok
63 if (!method_exists($function->classname, $function->methodname)) {
64 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
66 if (!method_exists($function->classname, $function->parameters_method)) {
67 throw new coding_exception('Missing parameters description');
69 if (!method_exists($function->classname, $function->returns_method)) {
70 throw new coding_exception('Missing returned values description');
73 // fetch the parameters description
74 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
75 if (!($function->parameters_desc instanceof external_function_parameters)) {
76 throw new coding_exception('Invalid parameters description');
79 // fetch the return values description
80 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
81 // null means void result or result is ignored
82 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
83 throw new coding_exception('Invalid return description');
86 //now get the function description
87 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
88 // easy to understand descriptions in admin UI,
89 // on the other hand this is still a bit in a flux and we need to find some new naming
90 // conventions for these descriptions in lang packs
91 $function->description = null;
92 $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
93 if (file_exists($servicesfile)) {
94 $functions = null;
95 include($servicesfile);
96 if (isset($functions[$function->name]['description'])) {
97 $function->description = $functions[$function->name]['description'];
99 if (isset($functions[$function->name]['testclientpath'])) {
100 $function->testclientpath = $functions[$function->name]['testclientpath'];
104 return $function;
108 * Exception indicating user is not allowed to use external function in the current context.
110 * @package core_webservice
111 * @copyright 2009 Petr Skodak
112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 * @since Moodle 2.0
115 class restricted_context_exception extends moodle_exception {
117 * Constructor
119 * @since Moodle 2.0
121 function __construct() {
122 parent::__construct('restrictedcontextexception', 'error');
127 * Base class for external api methods.
129 * @package core_webservice
130 * @copyright 2009 Petr Skodak
131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
132 * @since Moodle 2.0
134 class external_api {
136 /** @var stdClass context where the function calls will be restricted */
137 private static $contextrestriction;
140 * Set context restriction for all following subsequent function calls.
142 * @param stdClass $context the context restriction
143 * @since Moodle 2.0
145 public static function set_context_restriction($context) {
146 self::$contextrestriction = $context;
150 * This method has to be called before every operation
151 * that takes a longer time to finish!
153 * @param int $seconds max expected time the next operation needs
154 * @since Moodle 2.0
156 public static function set_timeout($seconds=360) {
157 $seconds = ($seconds < 300) ? 300 : $seconds;
158 core_php_time_limit::raise($seconds);
162 * Validates submitted function parameters, if anything is incorrect
163 * invalid_parameter_exception is thrown.
164 * This is a simple recursive method which is intended to be called from
165 * each implementation method of external API.
167 * @param external_description $description description of parameters
168 * @param mixed $params the actual parameters
169 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
170 * @since Moodle 2.0
172 public static function validate_parameters(external_description $description, $params) {
173 if ($description instanceof external_value) {
174 if (is_array($params) or is_object($params)) {
175 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
178 if ($description->type == PARAM_BOOL) {
179 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
180 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
181 return (bool)$params;
184 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
185 '", the server was expecting "' . $description->type . '" type';
186 return validate_param($params, $description->type, $description->allownull, $debuginfo);
188 } else if ($description instanceof external_single_structure) {
189 if (!is_array($params)) {
190 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
191 . print_r($params, true) . '\'');
193 $result = array();
194 foreach ($description->keys as $key=>$subdesc) {
195 if (!array_key_exists($key, $params)) {
196 if ($subdesc->required == VALUE_REQUIRED) {
197 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
199 if ($subdesc->required == VALUE_DEFAULT) {
200 try {
201 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
202 } catch (invalid_parameter_exception $e) {
203 //we are only interested by exceptions returned by validate_param() and validate_parameters()
204 //(in order to build the path to the faulty attribut)
205 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
208 } else {
209 try {
210 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
211 } catch (invalid_parameter_exception $e) {
212 //we are only interested by exceptions returned by validate_param() and validate_parameters()
213 //(in order to build the path to the faulty attribut)
214 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
217 unset($params[$key]);
219 if (!empty($params)) {
220 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
222 return $result;
224 } else if ($description instanceof external_multiple_structure) {
225 if (!is_array($params)) {
226 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
227 . print_r($params, true) . '\'');
229 $result = array();
230 foreach ($params as $param) {
231 $result[] = self::validate_parameters($description->content, $param);
233 return $result;
235 } else {
236 throw new invalid_parameter_exception('Invalid external api description');
241 * Clean response
242 * If a response attribute is unknown from the description, we just ignore the attribute.
243 * If a response attribute is incorrect, invalid_response_exception is thrown.
244 * Note: this function is similar to validate parameters, however it is distinct because
245 * parameters validation must be distinct from cleaning return values.
247 * @param external_description $description description of the return values
248 * @param mixed $response the actual response
249 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
250 * @author 2010 Jerome Mouneyrac
251 * @since Moodle 2.0
253 public static function clean_returnvalue(external_description $description, $response) {
254 if ($description instanceof external_value) {
255 if (is_array($response) or is_object($response)) {
256 throw new invalid_response_exception('Scalar type expected, array or object received.');
259 if ($description->type == PARAM_BOOL) {
260 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
261 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
262 return (bool)$response;
265 $debuginfo = 'Invalid external api response: the value is "' . $response .
266 '", the server was expecting "' . $description->type . '" type';
267 try {
268 return validate_param($response, $description->type, $description->allownull, $debuginfo);
269 } catch (invalid_parameter_exception $e) {
270 //proper exception name, to be recursively catched to build the path to the faulty attribut
271 throw new invalid_response_exception($e->debuginfo);
274 } else if ($description instanceof external_single_structure) {
275 if (!is_array($response) && !is_object($response)) {
276 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
277 print_r($response, true) . '\'');
280 // Cast objects into arrays.
281 if (is_object($response)) {
282 $response = (array) $response;
285 $result = array();
286 foreach ($description->keys as $key=>$subdesc) {
287 if (!array_key_exists($key, $response)) {
288 if ($subdesc->required == VALUE_REQUIRED) {
289 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
291 if ($subdesc instanceof external_value) {
292 if ($subdesc->required == VALUE_DEFAULT) {
293 try {
294 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
295 } catch (invalid_response_exception $e) {
296 //build the path to the faulty attribut
297 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
301 } else {
302 try {
303 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
304 } catch (invalid_response_exception $e) {
305 //build the path to the faulty attribut
306 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
309 unset($response[$key]);
312 return $result;
314 } else if ($description instanceof external_multiple_structure) {
315 if (!is_array($response)) {
316 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
317 print_r($response, true) . '\'');
319 $result = array();
320 foreach ($response as $param) {
321 $result[] = self::clean_returnvalue($description->content, $param);
323 return $result;
325 } else {
326 throw new invalid_response_exception('Invalid external api response description');
331 * Makes sure user may execute functions in this context.
333 * @param stdClass $context
334 * @since Moodle 2.0
336 protected static function validate_context($context) {
337 global $CFG;
339 if (empty($context)) {
340 throw new invalid_parameter_exception('Context does not exist');
342 if (empty(self::$contextrestriction)) {
343 self::$contextrestriction = context_system::instance();
345 $rcontext = self::$contextrestriction;
347 if ($rcontext->contextlevel == $context->contextlevel) {
348 if ($rcontext->id != $context->id) {
349 throw new restricted_context_exception();
351 } else if ($rcontext->contextlevel > $context->contextlevel) {
352 throw new restricted_context_exception();
353 } else {
354 $parents = $context->get_parent_context_ids();
355 if (!in_array($rcontext->id, $parents)) {
356 throw new restricted_context_exception();
360 if ($context->contextlevel >= CONTEXT_COURSE) {
361 list($context, $course, $cm) = get_context_info_array($context->id);
362 require_login($course, false, $cm, false, true);
367 * Get context from passed parameters.
368 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
369 * For example, the context level can be "course" and instanceid can be courseid.
371 * See context_helper::get_all_levels() for a list of valid context levels.
373 * @param array $param
374 * @since Moodle 2.6
375 * @throws invalid_parameter_exception
376 * @return context
378 protected static function get_context_from_params($param) {
379 $levels = context_helper::get_all_levels();
380 if (!empty($param['contextid'])) {
381 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
382 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
383 $contextlevel = "context_".$param['contextlevel'];
384 if (!array_search($contextlevel, $levels)) {
385 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
387 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
388 } else {
389 // No valid context info was found.
390 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
396 * Common ancestor of all parameter description classes
398 * @package core_webservice
399 * @copyright 2009 Petr Skodak
400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
401 * @since Moodle 2.0
403 abstract class external_description {
404 /** @var string Description of element */
405 public $desc;
407 /** @var bool Element value required, null not allowed */
408 public $required;
410 /** @var mixed Default value */
411 public $default;
414 * Contructor
416 * @param string $desc
417 * @param bool $required
418 * @param mixed $default
419 * @since Moodle 2.0
421 public function __construct($desc, $required, $default) {
422 $this->desc = $desc;
423 $this->required = $required;
424 $this->default = $default;
429 * Scalar value description class
431 * @package core_webservice
432 * @copyright 2009 Petr Skodak
433 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
434 * @since Moodle 2.0
436 class external_value extends external_description {
438 /** @var mixed Value type PARAM_XX */
439 public $type;
441 /** @var bool Allow null values */
442 public $allownull;
445 * Constructor
447 * @param mixed $type
448 * @param string $desc
449 * @param bool $required
450 * @param mixed $default
451 * @param bool $allownull
452 * @since Moodle 2.0
454 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
455 $default=null, $allownull=NULL_ALLOWED) {
456 parent::__construct($desc, $required, $default);
457 $this->type = $type;
458 $this->allownull = $allownull;
463 * Associative array description class
465 * @package core_webservice
466 * @copyright 2009 Petr Skodak
467 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 * @since Moodle 2.0
470 class external_single_structure extends external_description {
472 /** @var array Description of array keys key=>external_description */
473 public $keys;
476 * Constructor
478 * @param array $keys
479 * @param string $desc
480 * @param bool $required
481 * @param array $default
482 * @since Moodle 2.0
484 public function __construct(array $keys, $desc='',
485 $required=VALUE_REQUIRED, $default=null) {
486 parent::__construct($desc, $required, $default);
487 $this->keys = $keys;
492 * Bulk array description class.
494 * @package core_webservice
495 * @copyright 2009 Petr Skodak
496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
497 * @since Moodle 2.0
499 class external_multiple_structure extends external_description {
501 /** @var external_description content */
502 public $content;
505 * Constructor
507 * @param external_description $content
508 * @param string $desc
509 * @param bool $required
510 * @param array $default
511 * @since Moodle 2.0
513 public function __construct(external_description $content, $desc='',
514 $required=VALUE_REQUIRED, $default=null) {
515 parent::__construct($desc, $required, $default);
516 $this->content = $content;
521 * Description of top level - PHP function parameters.
523 * @package core_webservice
524 * @copyright 2009 Petr Skodak
525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
526 * @since Moodle 2.0
528 class external_function_parameters extends external_single_structure {
531 * Constructor - does extra checking to prevent top level optional parameters.
533 * @param array $keys
534 * @param string $desc
535 * @param bool $required
536 * @param array $default
538 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
539 global $CFG;
541 if ($CFG->debugdeveloper) {
542 foreach ($keys as $key => $value) {
543 if ($value instanceof external_value) {
544 if ($value->required == VALUE_OPTIONAL) {
545 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
546 break;
551 parent::__construct($keys, $desc, $required, $default);
556 * Generate a token
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
568 function 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');
578 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
579 $newtoken = new stdClass();
580 $newtoken->token = $generatedtoken;
581 if (!is_object($serviceorid)){
582 $service = $DB->get_record('external_services', array('id' => $serviceorid));
583 } else {
584 $service = $serviceorid;
586 if (!is_object($contextorid)){
587 $context = context::instance_by_id($contextorid, MUST_EXIST);
588 } else {
589 $context = $contextorid;
591 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
592 $newtoken->externalserviceid = $service->id;
593 } else {
594 throw new moodle_exception('nocapabilitytousethisservice');
596 $newtoken->tokentype = $tokentype;
597 $newtoken->userid = $userid;
598 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
599 $newtoken->sid = session_id();
602 $newtoken->contextid = $context->id;
603 $newtoken->creatorid = $USER->id;
604 $newtoken->timecreated = time();
605 $newtoken->validuntil = $validuntil;
606 if (!empty($iprestriction)) {
607 $newtoken->iprestriction = $iprestriction;
609 $DB->insert_record('external_tokens', $newtoken);
610 return $newtoken->token;
614 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
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.
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.
622 * @since Moodle 2.0
624 function 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);
631 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
633 * @param string $component name of component (moodle, mod_assignment, etc.)
635 function external_delete_descriptions($component) {
636 global $DB;
638 $params = array($component);
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));
651 * Standard Moodle web service warnings
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
658 class external_warnings extends external_multiple_structure {
661 * Constructor
663 * @since Moodle 2.3
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') {
668 parent::__construct(
669 new external_single_structure(
670 array(
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),
674 'message' => new external_value(PARAM_TEXT,
675 'untranslated english message to explain the warning')
676 ), 'warning'),
677 'list of warnings', VALUE_OPTIONAL);
682 * A pre-filled external_value class for text format.
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.
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
693 class external_format_value extends external_value {
696 * Constructor
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
702 public function __construct($textfieldname, $required = VALUE_REQUIRED) {
704 $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;
706 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
707 . FORMAT_MOODLE . ' = MOODLE, '
708 . FORMAT_PLAIN . ' = PLAIN or '
709 . FORMAT_MARKDOWN . ' = MARKDOWN)';
711 parent::__construct(PARAM_INT, $desc, $required, $default);
716 * Validate text field format against known FORMAT_XXX
718 * @param array $format the format to validate
719 * @return the validated format
720 * @throws coding_exception
721 * @since Moodle 2.3
723 function 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');
729 return $format;
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.
738 * @param string $text The content that may contain ULRs in need of rewriting.
739 * @param int $textformat The text format.
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
747 function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid) {
748 global $CFG;
750 // Get settings (singleton).
751 $settings = external_settings::get_instance();
753 if ($settings->get_fileurl()) {
754 require_once($CFG->libdir . "/filelib.php");
755 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
758 if (!$settings->get_raw()) {
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).
763 return array($text, $textformat);
767 * Singleton to handle the external settings.
769 * We use singleton to encapsulate the "logic"
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
776 class external_settings {
778 /** @var object the singleton instance */
779 public static $instance = null;
781 /** @var boolean Should the external function return raw text or formatted */
782 private $raw = false;
784 /** @var boolean Should the external function filter the text */
785 private $filter = false;
787 /** @var boolean Should the external function rewrite plugin file url */
788 private $fileurl = true;
790 /** @var string In which file should the urls be rewritten */
791 private $file = 'webservice/pluginfile.php';
794 * Constructor - protected - can not be instanciated
796 protected function __construct() {
800 * Clone - private - can not be cloned
802 private final function __clone() {
806 * Return only one instance
808 * @return object
810 public static function get_instance() {
811 if (self::$instance === null) {
812 self::$instance = new external_settings;
815 return self::$instance;
819 * Set raw
821 * @param boolean $raw
823 public function set_raw($raw) {
824 $this->raw = $raw;
828 * Get raw
830 * @return boolean
832 public function get_raw() {
833 return $this->raw;
837 * Set filter
839 * @param boolean $filter
841 public function set_filter($filter) {
842 $this->filter = $filter;
846 * Get filter
848 * @return boolean
850 public function get_filter() {
851 return $this->filter;
855 * Set fileurl
857 * @param boolean $fileurl
859 public function set_fileurl($fileurl) {
860 $this->fileurl = $fileurl;
864 * Get fileurl
866 * @return boolean
868 public function get_fileurl() {
869 return $this->fileurl;
873 * Set file
875 * @param string $file
877 public function set_file($file) {
878 $this->file = $file;
882 * Get file
884 * @return string
886 public function get_file() {
887 return $this->file;