2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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();
29 * Exception indicating user is not allowed to use external function in the current context.
31 * @package core_webservice
32 * @copyright 2009 Petr Skodak
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class restricted_context_exception
extends moodle_exception
{
42 function __construct() {
43 parent
::__construct('restrictedcontextexception', 'error');
48 * Base class for external api methods.
50 * @package core_webservice
51 * @copyright 2009 Petr Skodak
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 /** @var stdClass context where the function calls will be restricted */
58 private static $contextrestriction;
61 * Returns detailed function information
63 * @param string|object $function name of external function or record from external_function
64 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
65 * MUST_EXIST means throw exception if no record or multiple records found
66 * @return stdClass description or false if not found or exception thrown
69 public static function external_function_info($function, $strictness=MUST_EXIST
) {
72 if (!is_object($function)) {
73 if (!$function = $DB->get_record('external_functions', array('name' => $function), '*', $strictness)) {
78 // First try class autoloading.
79 if (!class_exists($function->classname
)) {
80 // Fallback to explicit include of externallib.php.
81 if (empty($function->classpath
)) {
82 $function->classpath
= core_component
::get_component_directory($function->component
).'/externallib.php';
84 $function->classpath
= $CFG->dirroot
.'/'.$function->classpath
;
86 if (!file_exists($function->classpath
)) {
87 throw new coding_exception('Cannot find file with external function implementation');
89 require_once($function->classpath
);
90 if (!class_exists($function->classname
)) {
91 throw new coding_exception('Cannot find external class');
95 $function->ajax_method
= $function->methodname
.'_is_allowed_from_ajax';
96 $function->parameters_method
= $function->methodname
.'_parameters';
97 $function->returns_method
= $function->methodname
.'_returns';
98 $function->deprecated_method
= $function->methodname
.'_is_deprecated';
100 // Make sure the implementaion class is ok.
101 if (!method_exists($function->classname
, $function->methodname
)) {
102 throw new coding_exception('Missing implementation method of '.$function->classname
.'::'.$function->methodname
);
104 if (!method_exists($function->classname
, $function->parameters_method
)) {
105 throw new coding_exception('Missing parameters description');
107 if (!method_exists($function->classname
, $function->returns_method
)) {
108 throw new coding_exception('Missing returned values description');
110 if (method_exists($function->classname
, $function->deprecated_method
)) {
111 if (call_user_func(array($function->classname
, $function->deprecated_method
)) === true) {
112 $function->deprecated
= true;
115 $function->allowed_from_ajax
= false;
117 // Fetch the parameters description.
118 $function->parameters_desc
= call_user_func(array($function->classname
, $function->parameters_method
));
119 if (!($function->parameters_desc
instanceof external_function_parameters
)) {
120 throw new coding_exception('Invalid parameters description');
123 // Fetch the return values description.
124 $function->returns_desc
= call_user_func(array($function->classname
, $function->returns_method
));
125 // Null means void result or result is ignored.
126 if (!is_null($function->returns_desc
) and !($function->returns_desc
instanceof external_description
)) {
127 throw new coding_exception('Invalid return description');
130 // Now get the function description.
132 // TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
133 // easy to understand descriptions in admin UI,
134 // on the other hand this is still a bit in a flux and we need to find some new naming
135 // conventions for these descriptions in lang packs.
136 $function->description
= null;
137 $servicesfile = core_component
::get_component_directory($function->component
).'/db/services.php';
138 if (file_exists($servicesfile)) {
140 include($servicesfile);
141 if (isset($functions[$function->name
]['description'])) {
142 $function->description
= $functions[$function->name
]['description'];
144 if (isset($functions[$function->name
]['testclientpath'])) {
145 $function->testclientpath
= $functions[$function->name
]['testclientpath'];
147 if (isset($functions[$function->name
]['type'])) {
148 $function->type
= $functions[$function->name
]['type'];
150 if (isset($functions[$function->name
]['ajax'])) {
151 $function->allowed_from_ajax
= $functions[$function->name
]['ajax'];
152 } else if (method_exists($function->classname
, $function->ajax_method
)) {
153 if (call_user_func(array($function->classname
, $function->ajax_method
)) === true) {
154 debugging('External function ' . $function->ajax_method
. '() function is deprecated.' .
155 'Set ajax=>true in db/service.php instead.', DEBUG_DEVELOPER
);
156 $function->allowed_from_ajax
= true;
159 if (isset($functions[$function->name
]['loginrequired'])) {
160 $function->loginrequired
= $functions[$function->name
]['loginrequired'];
162 $function->loginrequired
= true;
170 * Call an external function validating all params/returns correctly.
172 * Note that an external function may modify the state of the current page, so this wrapper
173 * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
175 * @param string $function A webservice function name.
176 * @param array $args Params array (named params)
177 * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
178 * @return array containing keys for error (bool), exception and data.
180 public static function call_external_function($function, $args, $ajaxonly=false) {
181 global $PAGE, $COURSE, $CFG, $SITE;
183 require_once($CFG->libdir
. "/pagelib.php");
185 $externalfunctioninfo = self
::external_function_info($function);
187 $currentpage = $PAGE;
188 $currentcourse = $COURSE;
192 // Taken straight from from setup.php.
193 if (!empty($CFG->moodlepageclass
)) {
194 if (!empty($CFG->moodlepageclassfile
)) {
195 require_once($CFG->moodlepageclassfile
);
197 $classname = $CFG->moodlepageclass
;
199 $classname = 'moodle_page';
201 $PAGE = new $classname();
202 $COURSE = clone($SITE);
204 if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax
) {
205 throw new moodle_exception('servicenotavailable', 'webservice');
208 // Do not allow access to write or delete webservices as a public user.
209 if ($externalfunctioninfo->loginrequired
) {
210 if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES
&& !PHPUNIT_TEST
) {
211 throw new moodle_exception('servicenotavailable', 'webservice');
214 throw new moodle_exception('servicenotavailable', 'webservice');
220 // Validate params, this also sorts the params properly, we need the correct order in the next part.
221 $callable = array($externalfunctioninfo->classname
, 'validate_parameters');
222 $params = call_user_func($callable,
223 $externalfunctioninfo->parameters_desc
,
227 $callable = array($externalfunctioninfo->classname
, $externalfunctioninfo->methodname
);
228 $result = call_user_func_array($callable,
229 array_values($params));
231 // Validate the return parameters.
232 if ($externalfunctioninfo->returns_desc
!== null) {
233 $callable = array($externalfunctioninfo->classname
, 'clean_returnvalue');
234 $result = call_user_func($callable, $externalfunctioninfo->returns_desc
, $result);
237 $response['error'] = false;
238 $response['data'] = $result;
239 } catch (Exception
$e) {
240 $exception = get_exception_info($e);
241 unset($exception->a
);
242 $exception->backtrace
= format_backtrace($exception->backtrace
, true);
243 if (!debugging('', DEBUG_DEVELOPER
)) {
244 unset($exception->debuginfo
);
245 unset($exception->backtrace
);
247 $response['error'] = true;
248 $response['exception'] = $exception;
249 // Do not process the remaining requests.
252 $PAGE = $currentpage;
253 $COURSE = $currentcourse;
259 * Set context restriction for all following subsequent function calls.
261 * @param stdClass $context the context restriction
264 public static function set_context_restriction($context) {
265 self
::$contextrestriction = $context;
269 * This method has to be called before every operation
270 * that takes a longer time to finish!
272 * @param int $seconds max expected time the next operation needs
275 public static function set_timeout($seconds=360) {
276 $seconds = ($seconds < 300) ?
300 : $seconds;
277 core_php_time_limit
::raise($seconds);
281 * Validates submitted function parameters, if anything is incorrect
282 * invalid_parameter_exception is thrown.
283 * This is a simple recursive method which is intended to be called from
284 * each implementation method of external API.
286 * @param external_description $description description of parameters
287 * @param mixed $params the actual parameters
288 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
291 public static function validate_parameters(external_description
$description, $params) {
292 if ($description instanceof external_value
) {
293 if (is_array($params) or is_object($params)) {
294 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
297 if ($description->type
== PARAM_BOOL
) {
298 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
299 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
300 return (bool)$params;
303 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
304 '", the server was expecting "' . $description->type
. '" type';
305 return validate_param($params, $description->type
, $description->allownull
, $debuginfo);
307 } else if ($description instanceof external_single_structure
) {
308 if (!is_array($params)) {
309 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
310 . print_r($params, true) . '\'');
313 foreach ($description->keys
as $key=>$subdesc) {
314 if (!array_key_exists($key, $params)) {
315 if ($subdesc->required
== VALUE_REQUIRED
) {
316 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
318 if ($subdesc->required
== VALUE_DEFAULT
) {
320 $result[$key] = self
::validate_parameters($subdesc, $subdesc->default);
321 } catch (invalid_parameter_exception
$e) {
322 //we are only interested by exceptions returned by validate_param() and validate_parameters()
323 //(in order to build the path to the faulty attribut)
324 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo
);
329 $result[$key] = self
::validate_parameters($subdesc, $params[$key]);
330 } catch (invalid_parameter_exception
$e) {
331 //we are only interested by exceptions returned by validate_param() and validate_parameters()
332 //(in order to build the path to the faulty attribut)
333 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo
);
336 unset($params[$key]);
338 if (!empty($params)) {
339 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
343 } else if ($description instanceof external_multiple_structure
) {
344 if (!is_array($params)) {
345 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
346 . print_r($params, true) . '\'');
349 foreach ($params as $param) {
350 $result[] = self
::validate_parameters($description->content
, $param);
355 throw new invalid_parameter_exception('Invalid external api description');
361 * If a response attribute is unknown from the description, we just ignore the attribute.
362 * If a response attribute is incorrect, invalid_response_exception is thrown.
363 * Note: this function is similar to validate parameters, however it is distinct because
364 * parameters validation must be distinct from cleaning return values.
366 * @param external_description $description description of the return values
367 * @param mixed $response the actual response
368 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
369 * @author 2010 Jerome Mouneyrac
372 public static function clean_returnvalue(external_description
$description, $response) {
373 if ($description instanceof external_value
) {
374 if (is_array($response) or is_object($response)) {
375 throw new invalid_response_exception('Scalar type expected, array or object received.');
378 if ($description->type
== PARAM_BOOL
) {
379 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
380 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
381 return (bool)$response;
384 $debuginfo = 'Invalid external api response: the value is "' . $response .
385 '", the server was expecting "' . $description->type
. '" type';
387 return validate_param($response, $description->type
, $description->allownull
, $debuginfo);
388 } catch (invalid_parameter_exception
$e) {
389 //proper exception name, to be recursively catched to build the path to the faulty attribut
390 throw new invalid_response_exception($e->debuginfo
);
393 } else if ($description instanceof external_single_structure
) {
394 if (!is_array($response) && !is_object($response)) {
395 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
396 print_r($response, true) . '\'');
399 // Cast objects into arrays.
400 if (is_object($response)) {
401 $response = (array) $response;
405 foreach ($description->keys
as $key=>$subdesc) {
406 if (!array_key_exists($key, $response)) {
407 if ($subdesc->required
== VALUE_REQUIRED
) {
408 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
410 if ($subdesc instanceof external_value
) {
411 if ($subdesc->required
== VALUE_DEFAULT
) {
413 $result[$key] = self
::clean_returnvalue($subdesc, $subdesc->default);
414 } catch (invalid_response_exception
$e) {
415 //build the path to the faulty attribut
416 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo
);
422 $result[$key] = self
::clean_returnvalue($subdesc, $response[$key]);
423 } catch (invalid_response_exception
$e) {
424 //build the path to the faulty attribut
425 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo
);
428 unset($response[$key]);
433 } else if ($description instanceof external_multiple_structure
) {
434 if (!is_array($response)) {
435 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
436 print_r($response, true) . '\'');
439 foreach ($response as $param) {
440 $result[] = self
::clean_returnvalue($description->content
, $param);
445 throw new invalid_response_exception('Invalid external api response description');
450 * Makes sure user may execute functions in this context.
452 * @param stdClass $context
455 public static function validate_context($context) {
458 if (empty($context)) {
459 throw new invalid_parameter_exception('Context does not exist');
461 if (empty(self
::$contextrestriction)) {
462 self
::$contextrestriction = context_system
::instance();
464 $rcontext = self
::$contextrestriction;
466 if ($rcontext->contextlevel
== $context->contextlevel
) {
467 if ($rcontext->id
!= $context->id
) {
468 throw new restricted_context_exception();
470 } else if ($rcontext->contextlevel
> $context->contextlevel
) {
471 throw new restricted_context_exception();
473 $parents = $context->get_parent_context_ids();
474 if (!in_array($rcontext->id
, $parents)) {
475 throw new restricted_context_exception();
479 $PAGE->reset_theme_and_output();
480 list($unused, $course, $cm) = get_context_info_array($context->id
);
481 require_login($course, false, $cm, false, true);
482 $PAGE->set_context($context);
486 * Get context from passed parameters.
487 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
488 * For example, the context level can be "course" and instanceid can be courseid.
490 * See context_helper::get_all_levels() for a list of valid context levels.
492 * @param array $param
494 * @throws invalid_parameter_exception
497 protected static function get_context_from_params($param) {
498 $levels = context_helper
::get_all_levels();
499 if (!empty($param['contextid'])) {
500 return context
::instance_by_id($param['contextid'], IGNORE_MISSING
);
501 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
502 $contextlevel = "context_".$param['contextlevel'];
503 if (!array_search($contextlevel, $levels)) {
504 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
506 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING
);
508 // No valid context info was found.
509 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
515 * Common ancestor of all parameter description classes
517 * @package core_webservice
518 * @copyright 2009 Petr Skodak
519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
522 abstract class external_description
{
523 /** @var string Description of element */
526 /** @var bool Element value required, null not allowed */
529 /** @var mixed Default value */
535 * @param string $desc
536 * @param bool $required
537 * @param mixed $default
540 public function __construct($desc, $required, $default) {
542 $this->required
= $required;
543 $this->default = $default;
548 * Scalar value description class
550 * @package core_webservice
551 * @copyright 2009 Petr Skodak
552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
555 class external_value
extends external_description
{
557 /** @var mixed Value type PARAM_XX */
560 /** @var bool Allow null values */
567 * @param string $desc
568 * @param bool $required
569 * @param mixed $default
570 * @param bool $allownull
573 public function __construct($type, $desc='', $required=VALUE_REQUIRED
,
574 $default=null, $allownull=NULL_ALLOWED
) {
575 parent
::__construct($desc, $required, $default);
577 $this->allownull
= $allownull;
582 * Associative array description class
584 * @package core_webservice
585 * @copyright 2009 Petr Skodak
586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
589 class external_single_structure
extends external_description
{
591 /** @var array Description of array keys key=>external_description */
598 * @param string $desc
599 * @param bool $required
600 * @param array $default
603 public function __construct(array $keys, $desc='',
604 $required=VALUE_REQUIRED
, $default=null) {
605 parent
::__construct($desc, $required, $default);
611 * Bulk array description class.
613 * @package core_webservice
614 * @copyright 2009 Petr Skodak
615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
618 class external_multiple_structure
extends external_description
{
620 /** @var external_description content */
626 * @param external_description $content
627 * @param string $desc
628 * @param bool $required
629 * @param array $default
632 public function __construct(external_description
$content, $desc='',
633 $required=VALUE_REQUIRED
, $default=null) {
634 parent
::__construct($desc, $required, $default);
635 $this->content
= $content;
640 * Description of top level - PHP function parameters.
642 * @package core_webservice
643 * @copyright 2009 Petr Skodak
644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 class external_function_parameters
extends external_single_structure
{
650 * Constructor - does extra checking to prevent top level optional parameters.
653 * @param string $desc
654 * @param bool $required
655 * @param array $default
657 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED
, $default=null) {
660 if ($CFG->debugdeveloper
) {
661 foreach ($keys as $key => $value) {
662 if ($value instanceof external_value
) {
663 if ($value->required
== VALUE_OPTIONAL
) {
664 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER
);
670 parent
::__construct($keys, $desc, $required, $default);
677 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
678 * @param stdClass|int $serviceorid service linked to the token
679 * @param int $userid user linked to the token
680 * @param stdClass|int $contextorid
681 * @param int $validuntil date when the token expired
682 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
683 * @return string generated token
684 * @author 2010 Jamie Pratt
687 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
689 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
693 $generatedtoken = md5(uniqid(rand(),1));
695 throw new moodle_exception('tokengenerationfailed');
697 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
698 $newtoken = new stdClass();
699 $newtoken->token
= $generatedtoken;
700 if (!is_object($serviceorid)){
701 $service = $DB->get_record('external_services', array('id' => $serviceorid));
703 $service = $serviceorid;
705 if (!is_object($contextorid)){
706 $context = context
::instance_by_id($contextorid, MUST_EXIST
);
708 $context = $contextorid;
710 if (empty($service->requiredcapability
) ||
has_capability($service->requiredcapability
, $context, $userid)) {
711 $newtoken->externalserviceid
= $service->id
;
713 throw new moodle_exception('nocapabilitytousethisservice');
715 $newtoken->tokentype
= $tokentype;
716 $newtoken->userid
= $userid;
717 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED
){
718 $newtoken->sid
= session_id();
721 $newtoken->contextid
= $context->id
;
722 $newtoken->creatorid
= $USER->id
;
723 $newtoken->timecreated
= time();
724 $newtoken->validuntil
= $validuntil;
725 if (!empty($iprestriction)) {
726 $newtoken->iprestriction
= $iprestriction;
728 $DB->insert_record('external_tokens', $newtoken);
729 return $newtoken->token
;
733 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
734 * with the Moodle server through web services. The token is linked to the current session for the current page request.
735 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
736 * returned token will be somehow passed into the client app being embedded in the page.
738 * @param string $servicename name of the web service. Service name as defined in db/services.php
739 * @param int $context context within which the web service can operate.
740 * @return int returns token id.
743 function external_create_service_token($servicename, $context){
745 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST
);
746 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED
, $service, $USER->id
, $context, 0);
750 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
752 * @param string $component name of component (moodle, mod_assignment, etc.)
754 function external_delete_descriptions($component) {
757 $params = array($component);
759 $DB->delete_records_select('external_tokens',
760 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
761 $DB->delete_records_select('external_services_users',
762 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
763 $DB->delete_records_select('external_services_functions',
764 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
765 $DB->delete_records('external_services', array('component'=>$component));
766 $DB->delete_records('external_functions', array('component'=>$component));
770 * Standard Moodle web service warnings
772 * @package core_webservice
773 * @copyright 2012 Jerome Mouneyrac
774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
777 class external_warnings
extends external_multiple_structure
{
784 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
785 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
788 new external_single_structure(
790 'item' => new external_value(PARAM_TEXT
, $itemdesc, VALUE_OPTIONAL
),
791 'itemid' => new external_value(PARAM_INT
, $itemiddesc, VALUE_OPTIONAL
),
792 'warningcode' => new external_value(PARAM_ALPHANUM
, $warningcodedesc),
793 'message' => new external_value(PARAM_TEXT
,
794 'untranslated english message to explain the warning')
796 'list of warnings', VALUE_OPTIONAL
);
801 * A pre-filled external_value class for text format.
803 * Default is FORMAT_HTML
804 * This should be used all the time in external xxx_params()/xxx_returns functions
805 * as it is the standard way to implement text format param/return values.
807 * @package core_webservice
808 * @copyright 2012 Jerome Mouneyrac
809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
812 class external_format_value
extends external_value
{
817 * @param string $textfieldname Name of the text field
818 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
821 public function __construct($textfieldname, $required = VALUE_REQUIRED
) {
823 $default = ($required == VALUE_DEFAULT
) ? FORMAT_HTML
: null;
825 $desc = $textfieldname . ' format (' . FORMAT_HTML
. ' = HTML, '
826 . FORMAT_MOODLE
. ' = MOODLE, '
827 . FORMAT_PLAIN
. ' = PLAIN or '
828 . FORMAT_MARKDOWN
. ' = MARKDOWN)';
830 parent
::__construct(PARAM_INT
, $desc, $required, $default);
835 * Validate text field format against known FORMAT_XXX
837 * @param array $format the format to validate
838 * @return the validated format
839 * @throws coding_exception
842 function external_validate_format($format) {
843 $allowedformats = array(FORMAT_HTML
, FORMAT_MOODLE
, FORMAT_PLAIN
, FORMAT_MARKDOWN
);
844 if (!in_array($format, $allowedformats)) {
845 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
846 'The format with value=' . $format . ' is not supported by this Moodle site');
852 * Format the string to be returned properly as requested by the either the web service server,
853 * either by an internally call.
854 * The caller can change the format (raw) with the external_settings singleton
855 * All web service servers must set this singleton when parsing the $_GET and $_POST.
858 * Options are the same that in {@link format_string()} with some changes:
859 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
862 * @param string $str The string to be filtered. Should be plain text, expect
863 * possibly for multilang tags.
864 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
865 * @param int $contextid The id of the context for the string (affects filters).
866 * @param array $options options array/object or courseid
867 * @return string text
870 function external_format_string($str, $contextid, $striplinks = true, $options = array()) {
872 // Get settings (singleton).
873 $settings = external_settings
::get_instance();
874 if (empty($contextid)) {
875 throw new coding_exception('contextid is required');
878 if (!$settings->get_raw()) {
879 $context = context
::instance_by_id($contextid);
880 $options['context'] = $context;
881 $options['filter'] = isset($options['filter']) && !$options['filter'] ?
false : $settings->get_filter();
882 $str = format_string($str, $striplinks, $options);
889 * Format the text to be returned properly as requested by the either the web service server,
890 * either by an internally call.
891 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
892 * All web service servers must set this singleton when parsing the $_GET and $_POST.
895 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
896 * trusted : If true the string won't be cleaned. Default false.
897 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
898 * nocache : If true the string will not be cached and will be formatted every call. Default false.
899 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
900 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
901 * Default changed because div tags are not commonly needed.
902 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
903 * context : Not used! Using contextid parameter instead.
904 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
905 * returned. Default false.
906 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
907 * format_text) true. Default changed id attributes are commonly needed.
908 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
911 * @param string $text The content that may contain ULRs in need of rewriting.
912 * @param int $textformat The text format.
913 * @param int $contextid This parameter and the next two identify the file area to use.
914 * @param string $component
915 * @param string $filearea helps identify the file area.
916 * @param int $itemid helps identify the file area.
917 * @param object/array $options text formatting options
918 * @return array text + textformat
921 function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid, $options = null) {
924 // Get settings (singleton).
925 $settings = external_settings
::get_instance();
927 if ($settings->get_fileurl()) {
928 require_once($CFG->libdir
. "/filelib.php");
929 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
932 if (!$settings->get_raw()) {
933 $options = (array)$options;
935 // If context is passed in options, check that is the same to show a debug message.
936 if (isset($options['context'])) {
937 if ((is_object($options['context']) && $options['context']->id
!= $contextid)
938 ||
(!is_object($options['context']) && $options['context'] != $contextid)) {
939 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
940 Using $contextid parameter...', DEBUG_DEVELOPER
);
944 $options['filter'] = isset($options['filter']) && !$options['filter'] ?
false : $settings->get_filter();
945 $options['para'] = isset($options['para']) ?
$options['para'] : false;
946 $options['context'] = context
::instance_by_id($contextid);
947 $options['allowid'] = isset($options['allowid']) ?
$options['allowid'] : true;
949 $text = format_text($text, $textformat, $options);
950 $textformat = FORMAT_HTML
; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
953 return array($text, $textformat);
957 * Singleton to handle the external settings.
959 * We use singleton to encapsulate the "logic"
961 * @package core_webservice
962 * @copyright 2012 Jerome Mouneyrac
963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
966 class external_settings
{
968 /** @var object the singleton instance */
969 public static $instance = null;
971 /** @var boolean Should the external function return raw text or formatted */
972 private $raw = false;
974 /** @var boolean Should the external function filter the text */
975 private $filter = false;
977 /** @var boolean Should the external function rewrite plugin file url */
978 private $fileurl = true;
980 /** @var string In which file should the urls be rewritten */
981 private $file = 'webservice/pluginfile.php';
984 * Constructor - protected - can not be instanciated
986 protected function __construct() {
987 if ((AJAX_SCRIPT
== false) && (CLI_SCRIPT
== false) && (WS_SERVER
== false)) {
988 // For normal pages, the default should match the default for format_text.
989 $this->filter
= true;
990 // Use pluginfile.php for web requests.
991 $this->file
= 'pluginfile.php';
996 * Clone - private - can not be cloned
998 private final function __clone() {
1002 * Return only one instance
1004 * @return \external_settings
1006 public static function get_instance() {
1007 if (self
::$instance === null) {
1008 self
::$instance = new external_settings
;
1011 return self
::$instance;
1017 * @param boolean $raw
1019 public function set_raw($raw) {
1028 public function get_raw() {
1035 * @param boolean $filter
1037 public function set_filter($filter) {
1038 $this->filter
= $filter;
1046 public function get_filter() {
1047 return $this->filter
;
1053 * @param boolean $fileurl
1055 public function set_fileurl($fileurl) {
1056 $this->fileurl
= $fileurl;
1064 public function get_fileurl() {
1065 return $this->fileurl
;
1071 * @param string $file
1073 public function set_file($file) {
1074 $this->file
= $file;
1082 public function get_file() {
1088 * Utility functions for the external API.
1090 * @package core_webservice
1091 * @copyright 2015 Juan Leyva
1092 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1095 class external_util
{
1098 * Validate a list of courses, returning the complete course objects for valid courses.
1100 * @param array $courseids A list of course ids
1101 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1102 * @return array An array of courses and the validation warnings
1104 public static function validate_courses($courseids, $courses = array()) {
1105 // Delete duplicates.
1106 $courseids = array_unique($courseids);
1107 $warnings = array();
1109 // Remove courses which are not even requested.
1110 $courses = array_intersect_key($courses, array_flip($courseids));
1112 foreach ($courseids as $cid) {
1113 // Check the user can function in this context.
1115 $context = context_course
::instance($cid);
1116 external_api
::validate_context($context);
1118 if (!isset($courses[$cid])) {
1119 $courses[$cid] = get_course($cid);
1121 } catch (Exception
$e) {
1122 unset($courses[$cid]);
1123 $warnings[] = array(
1126 'warningcode' => '1',
1127 'message' => 'No access rights in course context'
1132 return array($courses, $warnings);