first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+586
View File
@@ -0,0 +1,586 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
use coding_exception;
use context;
use context_helper;
use context_system;
use core_component;
use core_php_time_limit;
use invalid_parameter_exception;
use invalid_response_exception;
use moodle_exception;
/**
* Base class for external api methods.
*
* @package core_webservice
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class external_api {
/** @var \stdClass context where the function calls will be restricted */
private static $contextrestriction;
/**
* Returns detailed function information
*
* @param string|\stdClass $function name of external function or record from external_function
* @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
* MUST_EXIST means throw exception if no record or multiple records found
* @return \stdClass|bool description or false if not found or exception thrown
* @throws coding_exception for any property and/or method that is missing or invalid
* @since Moodle 2.0
*/
public static function external_function_info($function, $strictness = MUST_EXIST) {
global $DB, $CFG;
if (!is_object($function)) {
if (!$function = $DB->get_record('external_functions', ['name' => $function], '*', $strictness)) {
return false;
}
}
// First try class autoloading.
if (!class_exists($function->classname)) {
// Fallback to explicit include of externallib.php.
if (empty($function->classpath)) {
$function->classpath = core_component::get_component_directory($function->component) . '/externallib.php';
} else {
$function->classpath = "{$CFG->dirroot}/{$function->classpath}";
}
if (!file_exists($function->classpath)) {
throw new coding_exception(
"Cannot find file {$function->classpath} with external function implementation " .
"for {$function->classname}::{$function->methodname}"
);
}
require_once($function->classpath);
if (!class_exists($function->classname)) {
throw new coding_exception("Cannot find external class {$function->classname}");
}
}
$function->ajax_method = "{$function->methodname}_is_allowed_from_ajax";
$function->parameters_method = "{$function->methodname}_parameters";
$function->returns_method = "{$function->methodname}_returns";
$function->deprecated_method = "{$function->methodname}_is_deprecated";
// Make sure the implementaion class is ok.
if (!method_exists($function->classname, $function->methodname)) {
throw new coding_exception(
"Missing implementation method {$function->classname}::{$function->methodname}"
);
}
if (!method_exists($function->classname, $function->parameters_method)) {
throw new coding_exception(
"Missing parameters description method {$function->classname}::{$function->parameters_method}"
);
}
if (!method_exists($function->classname, $function->returns_method)) {
throw new coding_exception(
"Missing returned values description method {$function->classname}::{$function->returns_method}"
);
}
if (method_exists($function->classname, $function->deprecated_method)) {
if (call_user_func([$function->classname, $function->deprecated_method]) === true) {
$function->deprecated = true;
}
}
$function->allowed_from_ajax = false;
// Fetch the parameters description.
$function->parameters_desc = call_user_func([$function->classname, $function->parameters_method]);
if (!($function->parameters_desc instanceof external_function_parameters)) {
throw new coding_exception(
"{$function->classname}::{$function->parameters_method} did not return a valid external_function_parameters object"
);
}
// Fetch the return values description.
$function->returns_desc = call_user_func([$function->classname, $function->returns_method]);
// Null means void result or result is ignored.
if (!is_null($function->returns_desc) && !($function->returns_desc instanceof external_description)) {
throw new coding_exception(
"{$function->classname}::{$function->returns_method} did not return a valid external_description object"
);
}
// Now get the function description.
// TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
// easy to understand descriptions in admin UI,
// on the other hand this is still a bit in a flux and we need to find some new naming
// conventions for these descriptions in lang packs.
$function->description = null;
$servicesfile = core_component::get_component_directory($function->component) . '/db/services.php';
if (file_exists($servicesfile)) {
$functions = null;
include($servicesfile);
if (isset($functions[$function->name]['description'])) {
$function->description = $functions[$function->name]['description'];
}
if (isset($functions[$function->name]['testclientpath'])) {
$function->testclientpath = $functions[$function->name]['testclientpath'];
}
if (isset($functions[$function->name]['type'])) {
$function->type = $functions[$function->name]['type'];
}
if (isset($functions[$function->name]['ajax'])) {
$function->allowed_from_ajax = $functions[$function->name]['ajax'];
} else if (method_exists($function->classname, $function->ajax_method)) {
if (call_user_func([$function->classname, $function->ajax_method]) === true) {
debugging('External function ' . $function->ajax_method . '() function is deprecated.' .
'Set ajax=>true in db/services.php instead.', DEBUG_DEVELOPER);
$function->allowed_from_ajax = true;
}
}
if (isset($functions[$function->name]['loginrequired'])) {
$function->loginrequired = $functions[$function->name]['loginrequired'];
} else {
$function->loginrequired = true;
}
if (isset($functions[$function->name]['readonlysession'])) {
$function->readonlysession = $functions[$function->name]['readonlysession'];
} else {
$function->readonlysession = false;
}
}
return $function;
}
/**
* Call an external function validating all params/returns correctly.
*
* Note that an external function may modify the state of the current page, so this wrapper
* saves and restores tha PAGE and COURSE global variables before/after calling the external function.
*
* @param string $function A webservice function name.
* @param array $args Params array (named params)
* @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
* @return array containing keys for error (bool), exception and data.
*/
public static function call_external_function($function, $args, $ajaxonly = false) {
global $PAGE, $COURSE, $CFG, $SITE;
require_once("{$CFG->libdir}/pagelib.php");
$externalfunctioninfo = static::external_function_info($function);
// Eventually this should shift into the various handlers and not be handled via config.
$readonlysession = $externalfunctioninfo->readonlysession ?? false;
if (!$readonlysession || empty($CFG->enable_read_only_sessions)) {
\core\session\manager::restart_with_write_lock($readonlysession);
}
$currentpage = $PAGE;
$currentcourse = $COURSE;
$response = [];
try {
// Taken straight from from setup.php.
if (!empty($CFG->moodlepageclass)) {
if (!empty($CFG->moodlepageclassfile)) {
require_once($CFG->moodlepageclassfile);
}
$classname = $CFG->moodlepageclass;
} else {
$classname = 'moodle_page';
}
$PAGE = new $classname();
$COURSE = clone($SITE);
if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
throw new moodle_exception('servicenotavailable', 'webservice');
}
// Do not allow access to write or delete webservices as a public user.
if ($externalfunctioninfo->loginrequired && !WS_SERVER) {
if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
throw new moodle_exception('servicerequireslogin', 'webservice');
}
if (!isloggedin()) {
throw new moodle_exception('servicerequireslogin', 'webservice');
} else {
require_sesskey();
}
}
// Validate params, this also sorts the params properly, we need the correct order in the next part.
$callable = [$externalfunctioninfo->classname, 'validate_parameters'];
$params = call_user_func(
$callable,
$externalfunctioninfo->parameters_desc,
$args
);
$params = array_values($params);
// Allow any Moodle plugin a chance to override this call. This is a convenient spot to
// make arbitrary behaviour customisations. The overriding plugin could call the 'real'
// function first and then modify the results, or it could do a completely separate
// thing.
$callbacks = get_plugins_with_function('override_webservice_execution');
$result = false;
foreach (array_values($callbacks) as $plugins) {
foreach (array_values($plugins) as $callback) {
$result = $callback($externalfunctioninfo, $params);
if ($result !== false) {
break 2;
}
}
}
// If the function was not overridden, call the real one.
if ($result === false) {
$callable = [$externalfunctioninfo->classname, $externalfunctioninfo->methodname];
$result = call_user_func_array($callable, $params);
}
// Validate the return parameters.
if ($externalfunctioninfo->returns_desc !== null) {
$callable = [$externalfunctioninfo->classname, 'clean_returnvalue'];
$result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
}
$response['error'] = false;
$response['data'] = $result;
} catch (\Throwable $e) {
$exception = get_exception_info($e);
unset($exception->a);
$exception->backtrace = format_backtrace($exception->backtrace, true);
if (!debugging('', DEBUG_DEVELOPER)) {
unset($exception->debuginfo);
unset($exception->backtrace);
}
$response['error'] = true;
$response['exception'] = $exception;
// Do not process the remaining requests.
}
$PAGE = $currentpage;
$COURSE = $currentcourse;
return $response;
}
/**
* Set context restriction for all following subsequent function calls.
*
* @param \stdClass $context the context restriction
* @since Moodle 2.0
*/
public static function set_context_restriction($context) {
self::$contextrestriction = $context;
}
/**
* This method has to be called before every operation
* that takes a longer time to finish!
*
* @param int $seconds max expected time the next operation needs
* @since Moodle 2.0
*/
public static function set_timeout($seconds = 360) {
$seconds = ($seconds < 300) ? 300 : $seconds;
core_php_time_limit::raise($seconds);
}
/**
* Validates submitted function parameters, if anything is incorrect
* invalid_parameter_exception is thrown.
* This is a simple recursive method which is intended to be called from
* each implementation method of external API.
*
* @param external_description $description description of parameters
* @param mixed $params the actual parameters
* @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
* @since Moodle 2.0
*/
public static function validate_parameters(external_description $description, $params) {
if ($params === null && $description->allownull == NULL_ALLOWED) {
return null;
}
if ($description instanceof external_value) {
if (is_array($params) || is_object($params)) {
throw new invalid_parameter_exception('Scalar type expected, array or object received.');
}
if ($description->type == PARAM_BOOL) {
// Special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here.
if (is_bool($params) || $params === 0 || $params === 1 || $params === '0' || $params === '1') {
return (bool) $params;
}
}
$debuginfo = "Invalid external api parameter: the value is \"{$params}\", ";
$debuginfo .= "the server was expecting \"{$description->type}\" type";
return validate_param($params, $description->type, $description->allownull, $debuginfo);
} else if ($description instanceof external_single_structure) {
if (!is_array($params)) {
throw new invalid_parameter_exception(
// phpcs:ignore moodle.PHP.ForbiddenFunctions.Found
"Only arrays accepted. The bad value is: '" . print_r($params, true) . "'"
);
}
$result = [];
foreach ($description->keys as $key => $subdesc) {
if (!array_key_exists($key, $params)) {
if ($subdesc->required == VALUE_REQUIRED) {
throw new invalid_parameter_exception("Missing required key in single structure: {$key}");
}
if ($subdesc->required == VALUE_DEFAULT) {
try {
$result[$key] = static::validate_parameters($subdesc, $subdesc->default);
} catch (invalid_parameter_exception $e) {
// We are only interested by exceptions returned by validate_param() and validate_parameters().
// This is used to build the path to the faulty attribute.
throw new invalid_parameter_exception("{$key} => " . $e->getMessage() . ': ' . $e->debuginfo);
}
}
} else {
try {
$result[$key] = static::validate_parameters($subdesc, $params[$key]);
} catch (invalid_parameter_exception $e) {
// We are only interested by exceptions returned by validate_param() and validate_parameters().
// This is used to build the path to the faulty attribute.
throw new invalid_parameter_exception($key . " => " . $e->getMessage() . ': ' . $e->debuginfo);
}
}
unset($params[$key]);
}
if (!empty($params)) {
throw new invalid_parameter_exception(
'Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.'
);
}
return $result;
} else if ($description instanceof external_multiple_structure) {
if (!is_array($params)) {
throw new invalid_parameter_exception(
'Only arrays accepted. The bad value is: \'' .
// phpcs:ignore moodle.PHP.ForbiddenFunctions.Found
print_r($params, true) .
"'"
);
}
$result = [];
foreach ($params as $param) {
$result[] = static::validate_parameters($description->content, $param);
}
return $result;
} else {
throw new invalid_parameter_exception('Invalid external api description');
}
}
/**
* Clean response
* If a response attribute is unknown from the description, we just ignore the attribute.
* If a response attribute is incorrect, invalid_response_exception is thrown.
* Note: this function is similar to validate parameters, however it is distinct because
* parameters validation must be distinct from cleaning return values.
*
* @param external_description $description description of the return values
* @param mixed $response the actual response
* @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
* @author 2010 Jerome Mouneyrac
* @since Moodle 2.0
*/
public static function clean_returnvalue(external_description $description, $response) {
if ($response === null && $description->allownull == NULL_ALLOWED) {
return null;
}
if ($description instanceof external_value) {
if (is_array($response) || is_object($response)) {
throw new invalid_response_exception('Scalar type expected, array or object received.');
}
if ($description->type == PARAM_BOOL) {
// Special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here.
if (is_bool($response) || $response === 0 || $response === 1 || $response === '0' || $response === '1') {
return (bool) $response;
}
}
$responsetype = gettype($response);
$debuginfo = "Invalid external api response: the value is \"{$response}\" of PHP type \"{$responsetype}\", ";
$debuginfo .= "the server was expecting \"{$description->type}\" type";
try {
return validate_param($response, $description->type, $description->allownull, $debuginfo);
} catch (invalid_parameter_exception $e) {
// Proper exception name, to be recursively catched to build the path to the faulty attribute.
throw new invalid_response_exception($e->debuginfo);
}
} else if ($description instanceof external_single_structure) {
if (!is_array($response) && !is_object($response)) {
throw new invalid_response_exception(
// phpcs:ignore moodle.PHP.ForbiddenFunctions.Found
"Only arrays/objects accepted. The bad value is: '" . print_r($response, true) . "'"
);
}
// Cast objects into arrays.
if (is_object($response)) {
$response = (array) $response;
}
$result = [];
foreach ($description->keys as $key => $subdesc) {
if (!array_key_exists($key, $response)) {
if ($subdesc->required == VALUE_REQUIRED) {
throw new invalid_response_exception(
"Error in response - Missing following required key in a single structure: {$key}"
);
}
if ($subdesc instanceof external_value) {
if ($subdesc->required == VALUE_DEFAULT) {
try {
$result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
} catch (invalid_response_exception $e) {
// Build the path to the faulty attribute.
throw new invalid_response_exception("{$key} => " . $e->getMessage() . ': ' . $e->debuginfo);
}
}
}
} else {
try {
$result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
} catch (invalid_response_exception $e) {
// Build the path to the faulty attribute.
throw new invalid_response_exception("{$key} => " . $e->getMessage() . ': ' . $e->debuginfo);
}
}
unset($response[$key]);
}
return $result;
} else if ($description instanceof external_multiple_structure) {
if (!is_array($response)) {
throw new invalid_response_exception(
// phpcs:ignore moodle.PHP.ForbiddenFunctions.Found
"Only arrays accepted. The bad value is: '" . print_r($response, true) . "'"
);
}
$result = [];
foreach ($response as $param) {
$result[] = static::clean_returnvalue($description->content, $param);
}
return $result;
} else {
throw new invalid_response_exception('Invalid external api response description');
}
}
/**
* Makes sure user may execute functions in this context.
*
* @param context $context
* @since Moodle 2.0
*/
public static function validate_context($context) {
global $PAGE;
if (empty($context)) {
throw new invalid_parameter_exception('Context does not exist');
}
if (empty(self::$contextrestriction)) {
self::$contextrestriction = context_system::instance();
}
$rcontext = self::$contextrestriction;
if ($rcontext->contextlevel == $context->contextlevel) {
if ($rcontext->id != $context->id) {
throw new restricted_context_exception();
}
} else if ($rcontext->contextlevel > $context->contextlevel) {
throw new restricted_context_exception();
} else {
$parents = $context->get_parent_context_ids();
if (!in_array($rcontext->id, $parents)) {
throw new restricted_context_exception();
}
}
$PAGE->reset_theme_and_output();
[, $course, $cm] = get_context_info_array($context->id);
require_login($course, false, $cm, false, true);
$PAGE->set_context($context);
}
/**
* Get context from passed parameters.
* The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
* For example, the context level can be "course" and instanceid can be courseid.
*
* See context_helper::get_all_levels() for a list of valid numeric context levels,
* legacy short names such as 'system', 'user', 'course' are not supported in new
* plugin capabilities.
*
* @param array $param
* @since Moodle 2.6
* @throws invalid_parameter_exception
* @return context
*/
protected static function get_context_from_params($param) {
if (!empty($param['contextid'])) {
return context::instance_by_id($param['contextid'], IGNORE_MISSING);
} else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
// Numbers and short names are supported since Moodle 4.2.
$classname = \core\context_helper::parse_external_level($param['contextlevel']);
if (!$classname) {
throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
}
return $classname::instance($param['instanceid'], IGNORE_MISSING);
} else {
// No valid context info was found.
throw new invalid_parameter_exception(
'Missing parameters, please provide either context level with instance id or contextid'
);
}
}
/**
* Returns a prepared structure to use a context parameters.
* @return external_single_structure
*/
protected static function get_context_parameters() {
$id = new external_value(
PARAM_INT,
'Context ID. Either use this value, or level and instanceid.',
VALUE_DEFAULT,
0
);
$level = new external_value(
PARAM_ALPHANUM, // Since Moodle 4.2 numeric context level values are supported too.
'Context level. To be used with instanceid.',
VALUE_DEFAULT,
''
);
$instanceid = new external_value(
PARAM_INT,
'Context instance ID. To be used with level',
VALUE_DEFAULT,
0
);
return new external_single_structure([
'contextid' => $id,
'contextlevel' => $level,
'instanceid' => $instanceid,
]);
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Common ancestor of all parameter description classes
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class external_description {
/** @var string Description of element */
public $desc;
/** @var bool Element value required, null not allowed */
public $required;
/** @var mixed Default value */
public $default;
/** @var bool Allow null values */
public $allownull;
/**
* Contructor.
*
* @param string $desc Description of element
* @param int $required Whether the element value is required. Valid values are VALUE_DEFAULT, VALUE_REQUIRED, VALUE_OPTIONAL.
* @param mixed $default The default value
* @param bool $allownull Allow null value
*/
public function __construct($desc, $required, $default, $allownull = NULL_NOT_ALLOWED) {
if (!in_array($required, [VALUE_DEFAULT, VALUE_REQUIRED, VALUE_OPTIONAL], true)) {
$requiredstr = $required;
if (is_array($required)) {
$requiredstr = "Array: " . implode(" ", $required);
}
debugging("Invalid \$required parameter value: '{$requiredstr}' .
It must be either VALUE_DEFAULT, VALUE_REQUIRED, or VALUE_OPTIONAL", DEBUG_DEVELOPER);
}
$this->desc = $desc;
$this->required = $required;
$this->default = $default;
$this->allownull = (bool)$allownull;
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* External structure representing a set of files.
*
* @package core_external
* @copyright 2016 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_files extends external_multiple_structure {
/**
* Constructor
* @param string $desc Description for the multiple structure.
* @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
*/
public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
parent::__construct(
new external_single_structure([
'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
'icon' => new external_value(PARAM_RAW,
'The relative path to the relevant file type icon based on the file\'s mime type.', VALUE_OPTIONAL),
], 'File.'),
$desc,
$required,
);
}
/**
* Return the properties ready to be used by an exporter.
*
* @return array properties
* @since Moodle 3.3
*/
public static function get_properties_for_exporter() {
return [
'filename' => [
'type' => PARAM_FILE,
'description' => 'File name.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'filepath' => [
'type' => PARAM_PATH,
'description' => 'File path.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'filesize' => [
'type' => PARAM_INT,
'description' => 'File size.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'fileurl' => [
'type' => PARAM_URL,
'description' => 'Downloadable file url.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'timemodified' => [
'type' => PARAM_INT,
'description' => 'Time modified.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'mimetype' => [
'type' => PARAM_RAW,
'description' => 'File mime type.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'isexternalfile' => [
'type' => PARAM_BOOL,
'description' => 'Whether is an external file.',
'optional' => true,
'null' => NULL_NOT_ALLOWED,
],
'repositorytype' => [
'type' => PARAM_PLUGIN,
'description' => 'The repository type for the external files.',
'optional' => true,
'null' => NULL_ALLOWED,
],
'icon' => [
'type' => PARAM_RAW,
'description' => 'Relative path to the relevant file type icon based on the file\'s mime type.',
'optional' => true,
'null' => NULL_ALLOWED,
],
];
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* A pre-filled external_value class for text format.
*
* Default is FORMAT_HTML
* This should be used all the time in external xxx_params()/xxx_returns functions
* as it is the standard way to implement text format param/return values.
*
* @package core_webservice
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.3
*/
class external_format_value extends external_value {
/**
* Constructor
*
* @param string $textfieldname Name of the text field
* @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
* @param int $default Default value.
*/
public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
// Make sure the default format's value is correct.
if ($default !== null && !in_array($default, [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN])) {
debugging("Invalid default format for $textfieldname: $default. " .
"It must be either FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, or FORMAT_MARKDOWN.", DEBUG_DEVELOPER);
$default = null;
}
if ($default == null && $required == VALUE_DEFAULT) {
$default = FORMAT_HTML;
}
$desc = sprintf(
"%s format (%s = HTML, %s = MOODLE, %s = PLAIN, or %s = MARKDOWN)",
$textfieldname,
FORMAT_HTML,
FORMAT_MOODLE,
FORMAT_PLAIN,
FORMAT_MARKDOWN,
);
parent::__construct(PARAM_INT, $desc, $required, $default);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Description of top level - PHP function parameters.
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_function_parameters extends external_single_structure {
/**
* Constructor - does extra checking to prevent top level optional parameters.
*
* @param array $keys
* @param string $desc
* @param int $required
* @param array $default
*/
public function __construct(
array $keys,
$desc = '',
$required = VALUE_REQUIRED,
$default = null
) {
global $CFG;
if ($CFG->debugdeveloper) {
foreach (array_values($keys) as $value) {
if ($value instanceof external_value) {
if ($value->required == VALUE_OPTIONAL) {
debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
break;
}
}
}
}
parent::__construct($keys, $desc, $required, $default, NULL_NOT_ALLOWED);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Bulk array description class.
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_multiple_structure extends external_description {
/** @var external_description content */
public $content;
/**
* Constructor
*
* @param external_description $content
* @param string $desc
* @param int $required
* @param array $default
* @param bool $allownull
*/
public function __construct(
external_description $content,
$desc = '',
$required = VALUE_REQUIRED,
$default = null,
$allownull = NULL_NOT_ALLOWED
) {
parent::__construct($desc, $required, $default, $allownull);
$this->content = $content;
}
}
+190
View File
@@ -0,0 +1,190 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Singleton to handle the external settings..
*
* We use singleton to encapsulate the "logic".
*
* @package core_external
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_settings {
/** @var settings|null the singleton instance */
public static $instance = null;
/** @var bool Should the external function return raw text or formatted */
private $raw = false;
/** @var bool Should the external function filter the text */
private $filter = false;
/** @var bool Should the external function rewrite plugin file url */
private $fileurl = true;
/** @var string In which file should the urls be rewritten */
private $file = 'webservice/pluginfile.php';
/** @var string The session lang */
private $lang = '';
/** @var string The timezone to use during this WS request */
private $timezone = '';
/**
* Constructor - protected - can not be instanciated
*/
protected function __construct() {
if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
// For normal pages, the default should match the default for format_text.
$this->filter = true;
// Use pluginfile.php for web requests.
$this->file = 'pluginfile.php';
}
}
/**
* Return only one instance
*
* @return self
*/
public static function get_instance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Reset the singleton instance.
*/
public static function reset(): void {
self::$instance = null;
}
/**
* Set raw
*
* @param boolean $raw
*/
public function set_raw($raw) {
$this->raw = $raw;
}
/**
* Get raw
*
* @return boolean
*/
public function get_raw() {
return $this->raw;
}
/**
* Set filter
*
* @param boolean $filter
*/
public function set_filter($filter) {
$this->filter = $filter;
}
/**
* Get filter
*
* @return boolean
*/
public function get_filter() {
return $this->filter;
}
/**
* Set fileurl
*
* @param bool $fileurl
*/
public function set_fileurl($fileurl) {
$this->fileurl = $fileurl;
}
/**
* Get fileurl
*
* @return bool
*/
public function get_fileurl() {
return $this->fileurl;
}
/**
* Set file
*
* @param string $file
*/
public function set_file($file) {
$this->file = $file;
}
/**
* Get file
*
* @return string
*/
public function get_file() {
return $this->file;
}
/**
* Set lang
*
* @param string $lang
*/
public function set_lang($lang) {
$this->lang = $lang;
}
/**
* Get lang
*
* @return string
*/
public function get_lang() {
return $this->lang;
}
/**
* Set timezone
*
* @param string $timezone
*/
public function set_timezone($timezone) {
$this->timezone = $timezone;
}
/**
* Get timezone
*
* @return string
*/
public function get_timezone() {
return $this->timezone;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Associative array description class
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_single_structure extends external_description {
/** @var array Description of array keys key=>external_description */
public $keys;
/**
* Constructor
*
* @param array $keys
* @param string $desc
* @param int $required
* @param array $default
* @param bool $allownull
*/
public function __construct(
array $keys,
$desc = '',
$required = VALUE_REQUIRED,
$default = null,
$allownull = NULL_NOT_ALLOWED
) {
parent::__construct($desc, $required, $default, $allownull);
$this->keys = $keys;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Scalar value description class.
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_value extends external_description {
/** @var mixed Value type PARAM_XX */
public $type;
/**
* Constructor for the external_value class.
*
* @param mixed $type
* @param string $desc
* @param int $required
* @param mixed $default
* @param bool $allownull
*/
public function __construct(
$type,
$desc = '',
$required = VALUE_REQUIRED,
$default = null,
$allownull = NULL_ALLOWED
) {
parent::__construct($desc, $required, $default, $allownull);
$this->type = $type;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Standard Moodle web service warnings.
*
* @package core_external
* @copyright 2012 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_warnings extends external_multiple_structure {
/**
* Constructor
*
* @param string $itemdesc
* @param string $itemiddesc
* @param string $warningcodedesc
*/
public function __construct(
$itemdesc = 'item',
$itemiddesc = 'item id',
$warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour'
) {
parent::__construct(
new external_single_structure([
'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
'message' => new external_value(PARAM_RAW, 'untranslated english message to explain the warning'),
], 'warning'),
'list of warnings',
VALUE_OPTIONAL
);
}
}
+331
View File
@@ -0,0 +1,331 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external\privacy;
use context;
use context_user;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\transform;
use core_privacy\local\request\writer;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Data provider class.
*
* @package core_external
* @copyright 2018 Frédéric Massart
* @author Frédéric Massart <fred@branchup.tech>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\subsystem\provider {
/**
* Returns metadata.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
$collection->add_database_table('external_tokens', [
'token' => 'privacy:metadata:tokens:token',
'privatetoken' => 'privacy:metadata:tokens:privatetoken',
'tokentype' => 'privacy:metadata:tokens:tokentype',
'userid' => 'privacy:metadata:tokens:userid',
'creatorid' => 'privacy:metadata:tokens:creatorid',
'iprestriction' => 'privacy:metadata:tokens:iprestriction',
'validuntil' => 'privacy:metadata:tokens:validuntil',
'timecreated' => 'privacy:metadata:tokens:timecreated',
'lastaccess' => 'privacy:metadata:tokens:lastaccess',
'name' => 'privacy:metadata:tokens:name',
], 'privacy:metadata:tokens');
$collection->add_database_table('external_services_users', [
'userid' => 'privacy:metadata:serviceusers:userid',
'iprestriction' => 'privacy:metadata:serviceusers:iprestriction',
'validuntil' => 'privacy:metadata:serviceusers:validuntil',
'timecreated' => 'privacy:metadata:serviceusers:timecreated',
], 'privacy:metadata:serviceusers');
return $collection;
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return \core_privacy\local\request\contextlist $contextlist The contextlist containing the list of contexts
* used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): \core_privacy\local\request\contextlist {
$contextlist = new \core_privacy\local\request\contextlist();
$sql = "
SELECT ctx.id
FROM {external_tokens} t
JOIN {context} ctx
ON ctx.instanceid = t.userid
AND ctx.contextlevel = :userlevel
WHERE t.userid = :userid1
OR t.creatorid = :userid2";
$contextlist->add_from_sql($sql, ['userlevel' => CONTEXT_USER, 'userid1' => $userid, 'userid2' => $userid]);
$sql = "
SELECT ctx.id
FROM {external_services_users} su
JOIN {context} ctx
ON ctx.instanceid = su.userid
AND ctx.contextlevel = :userlevel
WHERE su.userid = :userid";
$contextlist->add_from_sql($sql, ['userlevel' => CONTEXT_USER, 'userid' => $userid]);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
global $DB;
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$userid = $context->instanceid;
$hasdata = false;
$hasdata = $hasdata || $DB->record_exists_select('external_tokens', 'userid = ? OR creatorid = ?', [$userid, $userid]);
$hasdata = $hasdata || $DB->record_exists('external_services_users', ['userid' => $userid]);
if ($hasdata) {
$userlist->add_user($userid);
}
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
global $DB;
$userid = $contextlist->get_user()->id;
$contexts = array_reduce($contextlist->get_contexts(), function($carry, $context) use ($userid) {
if ($context->contextlevel == CONTEXT_USER) {
if ($context->instanceid == $userid) {
$carry['has_mine'] = true;
} else {
$carry['others'][] = $context->instanceid;
}
}
return $carry;
}, [
'has_mine' => false,
'others' => []
]);
$path = [get_string('services', 'core_external')];
// Exporting my stuff.
if ($contexts['has_mine']) {
$data = [];
// Exporting my tokens.
$sql = "
SELECT t.*, s.name as externalservicename
FROM {external_tokens} t
JOIN {external_services} s
ON s.id = t.externalserviceid
WHERE t.userid = :userid
ORDER BY t.id";
$recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
foreach ($recordset as $record) {
if (!isset($data['tokens'])) {
$data['tokens'] = [];
}
$data['tokens'][] = static::transform_token($record);
}
$recordset->close();
// Exporting the services I have access to.
$sql = "
SELECT su.*, s.name as externalservicename
FROM {external_services_users} su
JOIN {external_services} s
ON s.id = su.externalserviceid
WHERE su.userid = :userid
ORDER BY su.id";
$recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
foreach ($recordset as $record) {
if (!isset($data['services_user'])) {
$data['services_user'] = [];
}
$data['services_user'][] = [
'external_service' => $record->externalservicename,
'ip_restriction' => $record->iprestriction,
'valid_until' => $record->validuntil ? transform::datetime($record->validuntil) : null,
'created_on' => transform::datetime($record->timecreated),
];
}
$recordset->close();
if (!empty($data)) {
writer::with_context(context_user::instance($userid))->export_data($path, (object) $data);
};
}
// Exporting the tokens I created.
if (!empty($contexts['others'])) {
list($insql, $inparams) = $DB->get_in_or_equal($contexts['others'], SQL_PARAMS_NAMED);
$sql = "
SELECT t.*, s.name as externalservicename
FROM {external_tokens} t
JOIN {external_services} s
ON s.id = t.externalserviceid
WHERE t.userid $insql
AND t.creatorid = :userid1
AND t.userid <> :userid2
ORDER BY t.userid, t.id";
$params = array_merge($inparams, ['userid1' => $userid, 'userid2' => $userid]);
$recordset = $DB->get_recordset_sql($sql, $params);
static::recordset_loop_and_export($recordset, 'userid', [], function($carry, $record) {
$carry[] = static::transform_token($record);
return $carry;
}, function($userid, $data) use ($path) {
writer::with_context(context_user::instance($userid))->export_related_data($path, 'created_by_you', (object) [
'tokens' => $data
]);
});
}
}
/**
* Delete all data for all users in the specified context.
*
* @param context $context The specific context to delete data for.
*/
public static function delete_data_for_all_users_in_context(context $context) {
if ($context->contextlevel != CONTEXT_USER) {
return;
}
static::delete_user_data($context->instanceid);
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_user_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$userid = $contextlist->get_user()->id;
foreach ($contextlist as $context) {
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $userid) {
static::delete_user_data($context->instanceid);
break;
}
}
}
/**
* Delete user data.
*
* @param int $userid The user ID.
* @return void
*/
protected static function delete_user_data($userid) {
global $DB;
$DB->delete_records('external_tokens', ['userid' => $userid]);
$DB->delete_records('external_services_users', ['userid' => $userid]);
}
/**
* Transform a token entry.
*
* @param object $record The token record.
* @return array
*/
protected static function transform_token($record) {
$notexportedstr = get_string('privacy:request:notexportedsecurity', 'core_external');
return [
'external_service' => $record->externalservicename,
'token' => $notexportedstr,
'private_token' => $record->privatetoken ? $notexportedstr : null,
'ip_restriction' => $record->iprestriction,
'valid_until' => $record->validuntil ? transform::datetime($record->validuntil) : null,
'created_on' => transform::datetime($record->timecreated),
'last_access' => $record->lastaccess ? transform::datetime($record->lastaccess) : null,
'name' => $record->name,
];
}
/**
* Loop and export from a recordset.
*
* @param \moodle_recordset $recordset The recordset.
* @param string $splitkey The record key to determine when to export.
* @param mixed $initial The initial data to reduce from.
* @param callable $reducer The function to return the dataset, receives current dataset, and the current record.
* @param callable $export The function to export the dataset, receives the last value from $splitkey and the dataset.
* @return void
*/
protected static function recordset_loop_and_export(\moodle_recordset $recordset, $splitkey, $initial,
callable $reducer, callable $export) {
$data = $initial;
$lastid = null;
foreach ($recordset as $record) {
if ($lastid && $record->{$splitkey} != $lastid) {
$export($lastid, $data);
$data = $initial;
}
$data = $reducer($data, $record);
$lastid = $record->{$splitkey};
}
$recordset->close();
if (!empty($lastid)) {
$export($lastid, $data);
}
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
/**
* Exception indicating user is not allowed to use external function in the current context.
*
* @package core_external
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restricted_context_exception extends \moodle_exception {
/**
* Constructor
*/
public function __construct() {
parent::__construct('restrictedcontextexception', 'error');
}
}
+662
View File
@@ -0,0 +1,662 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_external;
use context;
use context_course;
use context_helper;
use context_system;
use core_user;
use moodle_exception;
use moodle_url;
use stdClass;
/**
* Utility functions for the external API.
*
* @package core_webservice
* @copyright 2015 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class util {
/**
* Validate a list of courses, returning the complete course objects for valid courses.
*
* Each course has an additional 'contextvalidated' field, this will be set to true unless
* you set $keepfails, in which case it will be false if validation fails for a course.
*
* @param array $courseids A list of course ids
* @param array $courses An array of courses already pre-fetched, indexed by course id.
* @param bool $addcontext True if the returned course object should include the full context object.
* @param bool $keepfails True to keep all the course objects even if validation fails
* @return array An array of courses and the validation warnings
*/
public static function validate_courses(
$courseids,
$courses = [],
$addcontext = false,
$keepfails = false
) {
global $DB;
// Delete duplicates.
$courseids = array_unique($courseids);
$warnings = [];
// Remove courses which are not even requested.
$courses = array_intersect_key($courses, array_flip($courseids));
// For any courses NOT loaded already, get them in a single query (and preload contexts)
// for performance. Preserve ordering because some tests depend on it.
$newcourseids = [];
foreach ($courseids as $cid) {
if (!array_key_exists($cid, $courses)) {
$newcourseids[] = $cid;
}
}
if ($newcourseids) {
[$listsql, $listparams] = $DB->get_in_or_equal($newcourseids);
// Load list of courses, and preload associated contexts.
$contextselect = context_helper::get_preload_record_columns_sql('x');
$newcourses = $DB->get_records_sql(
"
SELECT c.*, $contextselect
FROM {course} c
JOIN {context} x ON x.instanceid = c.id
WHERE x.contextlevel = ? AND c.id $listsql",
array_merge([CONTEXT_COURSE], $listparams)
);
foreach ($newcourseids as $cid) {
if (array_key_exists($cid, $newcourses)) {
$course = $newcourses[$cid];
context_helper::preload_from_record($course);
$courses[$course->id] = $course;
}
}
}
foreach ($courseids as $cid) {
// Check the user can function in this context.
try {
$context = context_course::instance($cid);
external_api::validate_context($context);
if ($addcontext) {
$courses[$cid]->context = $context;
}
$courses[$cid]->contextvalidated = true;
} catch (\Exception $e) {
if ($keepfails) {
$courses[$cid]->contextvalidated = false;
} else {
unset($courses[$cid]);
}
$warnings[] = [
'item' => 'course',
'itemid' => $cid,
'warningcode' => '1',
'message' => 'No access rights in course context',
];
}
}
return [$courses, $warnings];
}
/**
* Returns all area files (optionally limited by itemid).
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID or all files if not specified
* @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
* @return array of files, compatible with the external_files structure.
* @since Moodle 3.2
*/
public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
$files = [];
$fs = get_file_storage();
if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
foreach ($areafiles as $areafile) {
$file = [];
$file['filename'] = $areafile->get_filename();
$file['filepath'] = $areafile->get_filepath();
$file['mimetype'] = $areafile->get_mimetype();
$file['filesize'] = $areafile->get_filesize();
$file['timemodified'] = $areafile->get_timemodified();
$file['isexternalfile'] = $areafile->is_external_file();
if ($file['isexternalfile']) {
$file['repositorytype'] = $areafile->get_repository_type();
}
$fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
// If AJAX request, generate a standard plugin file url.
if (AJAX_SCRIPT) {
$fileurl = moodle_url::make_pluginfile_url(
$contextid,
$component,
$filearea,
$fileitemid,
$areafile->get_filepath(),
$areafile->get_filename()
);
} else { // Otherwise, generate a webservice plugin file url.
$fileurl = moodle_url::make_webservice_pluginfile_url(
$contextid,
$component,
$filearea,
$fileitemid,
$areafile->get_filepath(),
$areafile->get_filename()
);
}
$file['fileurl'] = $fileurl->out(false);
$file['icon'] = file_file_icon($areafile);
$files[] = $file;
}
}
return $files;
}
/**
* Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
* with the Moodle server through web services. The token is linked to the current session for the current page request.
* It is expected this will be called in the script generating the html page that is embedding the client app and that the
* returned token will be somehow passed into the client app being embedded in the page.
*
* @param int $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
* @param stdClass $service service linked to the token
* @param int $userid user linked to the token
* @param context $context
* @param int $validuntil date when the token expired
* @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
* @param string $name token name as a note or token identity at the table view.
* @return string generated token
*/
public static function generate_token(
int $tokentype,
stdClass $service,
int $userid,
context $context,
int $validuntil = 0,
string $iprestriction = '',
string $name = ''
): string {
global $DB, $USER, $SESSION;
// Make sure the token doesn't exist (even if it should be almost impossible with the random generation).
$numtries = 0;
do {
$numtries++;
$generatedtoken = md5(uniqid((string) rand(), true));
if ($numtries > 5) {
throw new moodle_exception('tokengenerationfailed');
}
} while ($DB->record_exists('external_tokens', ['token' => $generatedtoken]));
$newtoken = (object) [
'token' => $generatedtoken,
];
if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
$newtoken->externalserviceid = $service->id;
} else {
throw new moodle_exception('nocapabilitytousethisservice');
}
$newtoken->tokentype = $tokentype;
$newtoken->userid = $userid;
if ($tokentype == EXTERNAL_TOKEN_EMBEDDED) {
$newtoken->sid = session_id();
}
$newtoken->contextid = $context->id;
$newtoken->creatorid = $USER->id;
$newtoken->timecreated = time();
$newtoken->validuntil = $validuntil;
if (!empty($iprestriction)) {
$newtoken->iprestriction = $iprestriction;
}
// Generate the private token, it must be transmitted only via https.
$newtoken->privatetoken = random_string(64);
if (!$name) {
// Generate a token name.
$name = self::generate_token_name();
}
$newtoken->name = $name;
$tokenid = $DB->insert_record('external_tokens', $newtoken);
// Create new session to hold newly created token ID.
$SESSION->webservicenewlycreatedtoken = $tokenid;
return $newtoken->token;
}
/**
* Get a service by its id.
*
* @param int $serviceid
* @return stdClass
*/
public static function get_service_by_id(int $serviceid): stdClass {
global $DB;
return $DB->get_record('external_services', ['id' => $serviceid], '*', MUST_EXIST);
}
/**
* Get a service by its name.
*
* @param string $name The service name.
* @return stdClass
*/
public static function get_service_by_name(string $name): stdClass {
global $DB;
return $DB->get_record('external_services', ['name' => $name], '*', MUST_EXIST);
}
/**
* Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
*
* This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
* In order to protect the privatetoken, we remove it from the event params.
*
* @param stdClass $token token object
*/
public static function log_token_request(stdClass $token): void {
global $DB, $USER;
$token->privatetoken = null;
// Log token access.
$DB->set_field('external_tokens', 'lastaccess', time(), ['id' => $token->id]);
$event = \core\event\webservice_token_sent::create([
'objectid' => $token->id,
]);
$event->add_record_snapshot('external_tokens', $token);
$event->trigger();
// Check if we need to notify the user about the new login via token.
$loginip = getremoteaddr();
if ($USER->lastip === $loginip) {
return;
}
$shouldskip = WS_SERVER || CLI_SCRIPT || !NO_MOODLE_COOKIES;
if ($shouldskip && !PHPUNIT_TEST) {
return;
}
// Schedule adhoc task to sent a login notification to the user.
$task = new \core\task\send_login_notifications();
$task->set_userid($USER->id);
$logintime = time();
$task->set_custom_data([
'useragent' => \core_useragent::get_user_agent_string(),
'ismoodleapp' => \core_useragent::is_moodle_app(),
'loginip' => $loginip,
'logintime' => $logintime,
]);
$task->set_component('core');
// We need sometime so the mobile app will send to Moodle the device information after login.
$task->set_next_run_time(time() + (2 * MINSECS));
\core\task\manager::reschedule_or_queue_adhoc_task($task);
}
/**
* Generate or return an existing token for the current authenticated user.
* This function is used for creating a valid token for users authenticathing via places, including:
* - login/token.php
* - admin/tool/mobile/launch.php.
*
* @param stdClass $service external service object
* @return stdClass token object
* @throws moodle_exception
*/
public static function generate_token_for_current_user(stdClass $service) {
global $DB, $USER, $CFG;
core_user::require_active_user($USER, true, true);
// Check if there is any required system capability.
if ($service->requiredcapability && !has_capability($service->requiredcapability, context_system::instance())) {
throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
}
// Specific checks related to user restricted service.
if ($service->restrictedusers) {
$authoriseduser = $DB->get_record('external_services_users', [
'externalserviceid' => $service->id,
'userid' => $USER->id,
]);
if (empty($authoriseduser)) {
throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
}
if (!empty($authoriseduser->validuntil) && $authoriseduser->validuntil < time()) {
throw new moodle_exception('invalidtimedtoken', 'webservice');
}
if (!empty($authoriseduser->iprestriction) && !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
throw new moodle_exception('invalidiptoken', 'webservice');
}
}
// Check if a token has already been created for this user and this service.
$conditions = [
'userid' => $USER->id,
'externalserviceid' => $service->id,
'tokentype' => EXTERNAL_TOKEN_PERMANENT,
];
$tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
// A bit of sanity checks.
foreach ($tokens as $key => $token) {
// Checks related to a specific token. (script execution continue).
$unsettoken = false;
// If sid is set then there must be a valid associated session no matter the token type.
if (!empty($token->sid)) {
if (!\core\session\manager::session_exists($token->sid)) {
// This token will never be valid anymore, delete it.
$DB->delete_records('external_tokens', ['sid' => $token->sid]);
$unsettoken = true;
}
}
// Remove token is not valid anymore.
if (!empty($token->validuntil) && $token->validuntil < time()) {
$DB->delete_records('external_tokens', ['token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT]);
$unsettoken = true;
}
// Remove token if its IP is restricted.
if (isset($token->iprestriction) && !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
$unsettoken = true;
}
if ($unsettoken) {
unset($tokens[$key]);
}
}
// If some valid tokens exist then use the most recent.
if (count($tokens) > 0) {
$token = array_pop($tokens);
} else {
$context = context_system::instance();
$isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
if (
($isofficialservice && has_capability('moodle/webservice:createmobiletoken', $context)) ||
(!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))
) {
// Create a new token.
$token = new stdClass();
$token->token = md5(uniqid((string) rand(), true));
$token->userid = $USER->id;
$token->tokentype = EXTERNAL_TOKEN_PERMANENT;
$token->contextid = context_system::instance()->id;
$token->creatorid = $USER->id;
$token->timecreated = time();
$token->externalserviceid = $service->id;
// By default tokens are valid for 12 weeks.
$token->validuntil = $token->timecreated + $CFG->tokenduration;
$token->iprestriction = null;
$token->sid = null;
$token->lastaccess = null;
$token->name = self::generate_token_name();
// Generate the private token, it must be transmitted only via https.
$token->privatetoken = random_string(64);
$token->id = $DB->insert_record('external_tokens', $token);
$eventtoken = clone $token;
$eventtoken->privatetoken = null;
$params = [
'objectid' => $eventtoken->id,
'relateduserid' => $USER->id,
'other' => [
'auto' => true,
],
];
$event = \core\event\webservice_token_created::create($params);
$event->add_record_snapshot('external_tokens', $eventtoken);
$event->trigger();
} else {
throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
}
}
return $token;
}
/**
* Format the string to be returned properly as requested by the either the web service server,
* either by an internally call.
* The caller can change the format (raw) with the settings singleton
* All web service servers must set this singleton when parsing the $_GET and $_POST.
*
* <pre>
* Options are the same that in {@see format_string()} with some changes:
* filter : Can be set to false to force filters off, else observes {@see settings}.
* </pre>
*
* @param string|null $content The string to be filtered. Should be plain text, expect
* possibly for multilang tags.
* @param int|context $context The id of the context for the string or the context (affects filters).
* @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
* @param array $options options array/object or courseid
* @return string text
*/
public static function format_string(
$content,
$context,
$striplinks = true,
$options = []
) {
if ($content === null || $content === '') {
// Nothing to return.
// Note: It's common for the DB to return null, so we allow format_string to take a null,
// even though it is counter-intuitive.
return '';
}
// Get settings (singleton).
$settings = external_settings::get_instance();
if (!$settings->get_raw()) {
$options['context'] = $context;
$options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
return format_string($content, $striplinks, $options);
}
return $content;
}
/**
* Format the text to be returned properly as requested by the either the web service server,
* either by an internally call.
* The caller can change the format (raw, filter, file, fileurl) with the \core_external\settings singleton
* All web service servers must set this singleton when parsing the $_GET and $_POST.
*
* <pre>
* Options are the same that in {@see format_text()} with some changes in defaults to provide backwards compatibility:
* trusted : If true the string won't be cleaned. Default false.
* noclean : If true the string won't be cleaned only if trusted is also true. Default false.
* nocache : If true the string will not be cached and will be formatted every call. Default false.
* filter : Can be set to false to force filters off, else observes {@see \core_external\settings}.
* para : If true then the returned string will be wrapped in div tags.
* Default (different from format_text) false.
* Default changed because div tags are not commonly needed.
* newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
* context : Not used! Using contextid parameter instead.
* overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
* returned. Default false.
* allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
* format_text) true. Default changed id attributes are commonly needed.
* blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
* </pre>
*
* @param string|null $text The content that may contain ULRs in need of rewriting.
* @param string|int|null $textformat The text format.
* @param context $context This parameter and the next two identify the file area to use.
* @param string|null $component
* @param string|null $filearea helps identify the file area.
* @param int|string|null $itemid helps identify the file area.
* @param array|stdClass|null $options text formatting options
* @return array text + textformat
*/
public static function format_text(
$text,
$textformat,
$context,
$component = null,
$filearea = null,
$itemid = null,
$options = null
) {
global $CFG;
if ($text === null || $text === '') {
// Nothing to return.
// Note: It's common for the DB to return null, so we allow format_string to take nulls,
// even though it is counter-intuitive.
return ['', $textformat ?? FORMAT_MOODLE];
}
if (empty($itemid)) {
$itemid = null;
}
// Get settings (singleton).
$settings = external_settings::get_instance();
if ($component && $filearea && $settings->get_fileurl()) {
require_once($CFG->libdir . "/filelib.php");
$text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $context->id, $component, $filearea, $itemid);
}
// Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
// This is consistent with web clients that are still able to load non-cleaned text into editors, too.
if (!$settings->get_raw()) {
$options = (array) $options;
// If context is passed in options, check that is the same to show a debug message.
if (isset($options['context'])) {
if (is_int($options['context'])) {
if ($options['context'] != $context->id) {
debugging(
'Different contexts found in external_format_text parameters. $options[\'context\'] not allowed. ' .
'Using $contextid parameter...',
DEBUG_DEVELOPER
);
}
} else if ($options['context'] instanceof context) {
if ($options['context']->id != $context->id) {
debugging(
'Different contexts found in external_format_text parameters. $options[\'context\'] not allowed. ' .
'Using $contextid parameter...',
DEBUG_DEVELOPER
);
}
}
}
$options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
$options['para'] = isset($options['para']) ? $options['para'] : false;
$options['context'] = $context;
$options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
$text = format_text($text, $textformat, $options);
// Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
$textformat = FORMAT_HTML;
}
// Note: The formats defined in weblib are strings.
return [$text, $textformat];
}
/**
* Validate text field format against known FORMAT_XXX
*
* @param string $format the format to validate
* @return string the validated format
* @throws \moodle_exception
* @since Moodle 2.3
*/
public static function validate_format($format) {
$allowedformats = [FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN];
if (!in_array($format, $allowedformats)) {
throw new moodle_exception(
'formatnotsupported',
'webservice',
'',
null,
"The format with value={$format} is not supported by this Moodle site"
);
}
return $format;
}
/**
* Delete all pre-built services, related tokens, and external functions information defined for the specified component.
*
* @param string $component The frankenstyle component name
*/
public static function delete_service_descriptions(string $component): void {
global $DB;
$params = [$component];
$DB->delete_records_select(
'external_tokens',
"externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)",
$params
);
$DB->delete_records_select(
'external_services_users',
"externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)",
$params
);
$DB->delete_records_select(
'external_services_functions',
"functionname IN (SELECT name FROM {external_functions} WHERE component = ?)",
$params
);
$DB->delete_records('external_services', ['component' => $component]);
$DB->delete_records('external_functions', ['component' => $component]);
}
/**
* Generate token name.
*
* @return string
*/
public static function generate_token_name(): string {
return get_string(
'tokennameprefix',
'webservice',
random_string(5)
);
}
}