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
+72
View File
@@ -0,0 +1,72 @@
<?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/>.
/**
* Web services API documentation
*
* @package webservice
* @copyright 2011 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Jerome Mouneyrac
*/
use core_external\external_api;
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/webservice/lib.php');
admin_externalpage_setup('webservicedocumentation');
// TODO: MDL-76078 - Incorrect inter-communication, core cannot have plugin dependencies like this.
//display the documentation for all documented protocols,
//regardless if they are activated or not
$protocols = array();
$protocols['rest'] = true;
$protocols['xmlrpc'] = true;
/// Check if we are in printable mode
$printableformat = optional_param('print', false, PARAM_BOOL);
/// OUTPUT
echo $OUTPUT->header();
// Get all the function descriptions.
$functions = $DB->get_records('external_functions', [], 'name');
$functiondescs = [];
foreach ($functions as $function) {
// Skip invalid or otherwise incorrectly defined functions, otherwise the entire page is rendered inaccessible.
try {
$functiondescs[$function->name] = external_api::external_function_info($function);
} catch (Throwable $exception) {
echo $OUTPUT->notification($exception->getMessage(), \core\output\notification::NOTIFY_ERROR);
}
}
$renderer = $PAGE->get_renderer('core', 'webservice');
echo $renderer->documentation_html($functiondescs,
$printableformat, $protocols, array(), $PAGE->url);
/// trigger browser print operation
if (!empty($printableformat)) {
$PAGE->requires->js_function_call('window.print', array());
}
echo $OUTPUT->footer();
+223
View File
@@ -0,0 +1,223 @@
<?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/>.
/**
* Web services admin UI forms
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once $CFG->libdir . '/formslib.php';
/**
* Display the authorised user settings form
* Including IP Restriction, Valid until and (TODO) capability
*/
class external_service_authorised_user_settings_form extends moodleform {
function definition() {
$mform = $this->_form;
$data = $this->_customdata;
$mform->addElement('header', 'serviceusersettings',
get_string('serviceusersettings', 'webservice'));
$mform->addElement('text', 'iprestriction',
get_string('iprestriction', 'webservice'));
$mform->addHelpButton('iprestriction', 'iprestriction', 'webservice');
$mform->setType('iprestriction', PARAM_RAW_TRIMMED);
$mform->addElement('date_selector', 'validuntil',
get_string('validuntil', 'webservice'), array('optional' => true));
$mform->addHelpButton('validuntil', 'validuntil', 'webservice');
$mform->setType('validuntil', PARAM_INT);
$this->add_action_buttons(true, get_string('updateusersettings', 'webservice'));
$this->set_data($data);
}
}
class external_service_form extends moodleform {
function definition() {
$mform = $this->_form;
$service = isset($this->_customdata) ? $this->_customdata : new stdClass();
$mform->addElement('header', 'extservice',
get_string('externalservice', 'webservice'));
$mform->addElement('text', 'name', get_string('name'));
$mform->addRule('name', get_string('required'), 'required', null, 'client');
$mform->setType('name', PARAM_TEXT);
$mform->addElement('text', 'shortname', get_string('shortname'), 'maxlength="255" size="20"');
$mform->setType('shortname', PARAM_TEXT);
if (!empty($service->id)) {
$mform->hardFreeze('shortname');
$mform->setConstants('shortname', $service->shortname);
}
$mform->addElement('advcheckbox', 'enabled', get_string('enabled', 'webservice'));
$mform->setType('enabled', PARAM_BOOL);
$mform->addElement('advcheckbox', 'restrictedusers',
get_string('restrictedusers', 'webservice'));
$mform->addHelpButton('restrictedusers', 'restrictedusers', 'webservice');
$mform->setType('restrictedusers', PARAM_BOOL);
// Can users download files?
$mform->addElement('advcheckbox', 'downloadfiles', get_string('downloadfiles', 'webservice'));
$mform->setAdvanced('downloadfiles');
$mform->addHelpButton('downloadfiles', 'downloadfiles', 'webservice');
$mform->setType('downloadfiles', PARAM_BOOL);
// Can users upload files?
$mform->addElement('advcheckbox', 'uploadfiles', get_string('uploadfiles', 'webservice'));
$mform->setAdvanced('uploadfiles');
$mform->addHelpButton('uploadfiles', 'uploadfiles', 'webservice');
/// needed to select automatically the 'No required capability" option
$currentcapabilityexist = false;
if (empty($service->requiredcapability)) {
$service->requiredcapability = "norequiredcapability";
$currentcapabilityexist = true;
}
// Prepare the list of capabilities to choose from
$systemcontext = context_system::instance();
$allcapabilities = $systemcontext->get_capabilities();
$capabilitychoices = array();
$capabilitychoices['norequiredcapability'] = get_string('norequiredcapability',
'webservice');
foreach ($allcapabilities as $cap) {
$capabilitychoices[$cap->name] = $cap->name . ': '
. get_capability_string($cap->name);
if (!empty($service->requiredcapability)
&& $service->requiredcapability == $cap->name) {
$currentcapabilityexist = true;
}
}
$mform->addElement('searchableselector', 'requiredcapability',
get_string('requiredcapability', 'webservice'), $capabilitychoices);
$mform->addHelpButton('requiredcapability', 'requiredcapability', 'webservice');
$mform->setAdvanced('requiredcapability');
$mform->setType('requiredcapability', PARAM_RAW);
/// display notification error if the current requiredcapability doesn't exist anymore
if (empty($currentcapabilityexist)) {
global $OUTPUT;
$mform->addElement('static', 'capabilityerror', '',
$OUTPUT->notification(get_string('selectedcapabilitydoesntexit',
'webservice', $service->requiredcapability)));
$service->requiredcapability = "norequiredcapability";
}
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
if (!empty($service->id)) {
$buttonlabel = get_string('savechanges');
} else {
$buttonlabel = get_string('addaservice', 'webservice');
}
$this->add_action_buttons(true, $buttonlabel);
$this->set_data($service);
}
function definition_after_data() {
$mform = $this->_form;
$service = $this->_customdata;
if (!empty($service->component)) {
// built-in components must not be modified except the enabled flag!!
$mform->hardFreeze('name,requiredcapability,restrictedusers');
}
}
function validation($data, $files) {
global $DB;
$errors = parent::validation($data, $files);
// Add field validation check for duplicate name.
if ($webservice = $DB->get_record('external_services', array('name' => $data['name']))) {
if (empty($data['id']) || $webservice->id != $data['id']) {
$errors['name'] = get_string('nameexists', 'webservice');
}
}
// Add field validation check for duplicate shortname.
// Allow duplicated "empty" shortnames.
if (!empty($data['shortname'])) {
if ($service = $DB->get_record('external_services', array('shortname' => $data['shortname']), '*', IGNORE_MULTIPLE)) {
if (empty($data['id']) || $service->id != $data['id']) {
$errors['shortname'] = get_string('shortnametaken', 'webservice', $service->name);
}
}
}
return $errors;
}
}
class external_service_functions_form extends moodleform {
function definition() {
global $CFG;
$mform = $this->_form;
$data = $this->_customdata;
$mform->addElement('header', 'addfunction', get_string('addfunctions', 'webservice'));
require_once($CFG->dirroot . "/webservice/lib.php");
$webservicemanager = new webservice();
$functions = $webservicemanager->get_not_associated_external_functions($data['id']);
//we add the descriptions to the functions
foreach ($functions as $functionid => $functionname) {
//retrieve full function information (including the description)
$function = \core_external\external_api::external_function_info($functionname);
if (empty($function->deprecated)) {
$functions[$functionid] = $function->name . ':' . $function->description;
} else {
// Exclude the deprecated ones.
unset($functions[$functionid]);
}
}
$mform->addElement('searchableselector', 'fids', get_string('name'),
$functions, array('multiple'));
$mform->addRule('fids', get_string('required'), 'required', null, 'client');
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'action');
$mform->setType('action', PARAM_ALPHANUMEXT);
$this->add_action_buttons(true, get_string('addfunctions', 'webservice'));
$this->set_data($data);
}
}
+127
View File
@@ -0,0 +1,127 @@
<?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/>.
/**
* Web services admin library
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->dirroot . '/user/selector/lib.php');
/*
* This class displays either all the Moodle users allowed to use a service,
* either all the other Moodle users.
*/
class service_user_selector extends user_selector_base {
protected $serviceid;
protected $displayallowedusers; //set to true if the selector displays the
//allowed users on this service
//, set to false if the selector displays the
// other users (false is the default default)
public function __construct($name, $options) {
parent::__construct($name, $options);
if (!empty($options['serviceid'])) {
$this->serviceid = $options['serviceid'];
} else {
throw new moodle_exception('serviceidnotfound');
}
$this->displayallowedusers = !empty($options['displayallowedusers']);
}
/**
* Find allowed or not allowed users of a service (depend of $this->displayallowedusers)
* @global object $DB
* @param <type> $search
* @return array
*/
public function find_users($search) {
global $DB;
//by default wherecondition retrieves all users except the deleted, not
//confirmed and guest
list($wherecondition, $params) = $this->search_sql($search, 'u');
$params['serviceid'] = $this->serviceid;
$fields = 'SELECT ' . $this->required_fields_sql('u');
$countfields = 'SELECT COUNT(1)';
if ($this->displayallowedusers) {
///the following SQL retrieve all users that are allowed to the serviceid
$sql = " FROM {user} u, {external_services_users} esu
WHERE $wherecondition
AND u.deleted = 0
AND esu.userid = u.id
AND esu.externalserviceid = :serviceid";
}
else {
///the following SQL retrieve all users that are not allowed to the serviceid
$sql = " FROM {user} u WHERE $wherecondition AND u.deleted = 0
AND NOT EXISTS (SELECT esu.userid FROM {external_services_users} esu
WHERE esu.externalserviceid = :serviceid
AND esu.userid = u.id)";
}
list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);
$order = ' ORDER BY ' . $sort;
if (!$this->is_validating()) {
$potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
if ($potentialmemberscount > $this->maxusersperpage) {
return $this->too_many_results($search, $potentialmemberscount);
}
}
$availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams));
if (empty($availableusers)) {
return array();
}
if ($search) {
$groupname = ($this->displayallowedusers) ?
get_string('serviceusersmatching', 'webservice', $search)
: get_string('potusersmatching', 'webservice', $search);
}
else {
$groupname = ($this->displayallowedusers) ?
get_string('serviceusers', 'webservice')
: get_string('potusers', 'webservice');
}
return array($groupname => $availableusers);
}
/**
* This options are automatically used by the AJAX search
* @global object $CFG
* @return object options pass to the constructor when AJAX search call a new selector
*/
protected function get_options() {
global $CFG;
$options = parent::get_options();
$options['file'] = $CFG->admin.'/webservice/lib.php'; //need to be set, otherwise
// the /user/selector/search.php
//will fail to find this user_selector class
$options['serviceid'] = $this->serviceid;
$options['displayallowedusers'] = $this->displayallowedusers;
return $options;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?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/>.
/**
* Web services protocols admin UI
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/tablelib.php');
$PAGE->set_url('/' . $CFG->admin . '/webservice/protocols.php');
//TODO: disable the blocks here or better make the page layout default to no blocks!
require_admin();
$returnurl = $CFG->wwwroot . "/" . $CFG->admin . "/settings.php?section=webserviceprotocols";
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$webservice = optional_param('webservice', '', PARAM_SAFEDIR);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
// Get currently installed and enabled auth plugins.
$availablewebservices = core_component::get_plugin_list('webservice');
if (!empty($webservice) and empty($availablewebservices[$webservice])) {
redirect($returnurl);
}
// Process actions.
if (!confirm_sesskey()) {
redirect($returnurl);
}
$enabled = ($action == 'enable');
$class = \core_plugin_manager::resolve_plugininfo_class('webservice');
$class::enable_plugin($webservice, $enabled);
redirect($returnurl);
+121
View File
@@ -0,0 +1,121 @@
<?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/>.
/**
* Web services admin UI
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once('forms.php');
require_once($CFG->dirroot . '/webservice/lib.php');
admin_externalpage_setup('externalservice');
//define nav bar
$node = $PAGE->settingsnav->find('externalservice', navigation_node::TYPE_SETTING);
$newnode = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node && $newnode) {
$node->display = false;
$newnode->make_active();
}
$PAGE->navbar->add(get_string('externalservices', 'webservice'),
new moodle_url('/admin/settings.php', ['section' => 'externalservices']));
$PAGE->set_primary_active_tab('siteadminnode');
//Retrieve few general parameters
$id = required_param('id', PARAM_INT);
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$webservicemanager = new webservice;
$renderer = $PAGE->get_renderer('core', 'webservice');
$returnurl = $CFG->wwwroot . "/" . $CFG->admin . "/settings.php?section=externalservices";
$service = $id ? $webservicemanager->get_external_service_by_id($id, MUST_EXIST) : null;
/// DELETE operation
if ($action == 'delete' and confirm_sesskey() and $service and empty($service->component)) {
//Display confirmation Page
if (!$confirm) {
echo $OUTPUT->header();
echo $renderer->admin_remove_service_confirmation($service);
echo $OUTPUT->footer();
die;
}
//The user has confirmed the deletion, delete and redirect
$webservicemanager->delete_service($service->id);
$params = array(
'objectid' => $service->id
);
$event = \core\event\webservice_service_deleted::create($params);
$event->add_record_snapshot('external_services', $service);
$event->trigger();
redirect($returnurl);
}
/// EDIT/CREATE/CANCEL operations => at the end redirect to add function page / main service page
$mform = new external_service_form(null, $service);
if ($mform->is_cancelled()) {
redirect($returnurl);
} else if ($servicedata = $mform->get_data()) {
$servicedata = (object) $servicedata;
if (!empty($servicedata->requiredcapability) && $servicedata->requiredcapability == "norequiredcapability") {
$servicedata->requiredcapability = "";
}
//create operation
if (empty($servicedata->id)) {
$servicedata->id = $webservicemanager->add_external_service($servicedata);
$params = array(
'objectid' => $servicedata->id
);
$event = \core\event\webservice_service_created::create($params);
$event->trigger();
//redirect to the 'add functions to service' page
$addfunctionpage = new moodle_url(
$CFG->wwwroot . '/' . $CFG->admin . '/webservice/service_functions.php',
array('id' => $servicedata->id));
$returnurl = $addfunctionpage->out(false);
} else {
//update operation
$webservicemanager->update_external_service($servicedata);
$params = array(
'objectid' => $servicedata->id
);
$event = \core\event\webservice_service_updated::create($params);
$event->trigger();
}
redirect($returnurl);
}
if ($id == 0) {
$PAGE->navbar->add(get_string('addexternalservice', 'webservice'), $PAGE->url);
} else {
$PAGE->navbar->add(get_string('editexternalservice', 'webservice'), $PAGE->url);
}
//OUTPUT edit/create form
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
+124
View File
@@ -0,0 +1,124 @@
<?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/>.
/**
* Web services function UI
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/webservice/lib.php');
require_once('forms.php');
$serviceid = required_param('id', PARAM_INT);
$functionid = optional_param('fid', 0, PARAM_INT);
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
admin_externalpage_setup('externalservicefunctions');
//define nav bar
$PAGE->set_url('/' . $CFG->admin . '/webservice/service_functions.php', array('id' => $serviceid));
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
$node->make_active();
}
$PAGE->set_primary_active_tab('siteadminnode');
$PAGE->navbar->add(get_string('externalservices', 'webservice'),
new moodle_url('/admin/settings.php', ['section' => 'externalservices']));
$PAGE->navbar->add(get_string('functions', 'webservice'),
new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php', array('id' => $serviceid)));
$service = $DB->get_record('external_services', array('id' => $serviceid), '*', MUST_EXIST);
$webservicemanager = new webservice();
$renderer = $PAGE->get_renderer('core', 'webservice');
$functionlisturl = new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php',
array('id' => $serviceid));
// Add or Delete operations
switch ($action) {
case 'add':
$PAGE->navbar->add(get_string('addfunctions', 'webservice'));
/// Add function operation
if (confirm_sesskey() and $service and empty($service->component)) {
$mform = new external_service_functions_form(null,
array('action' => 'add', 'id' => $service->id));
//cancelled add operation, redirect to function list page
if ($mform->is_cancelled()) {
redirect($functionlisturl);
}
//add the function to the service then redirect to function list page
if ($data = $mform->get_data()) {
ignore_user_abort(true); // no interruption here!
foreach ($data->fids as $fid) {
$function = $webservicemanager->get_external_function_by_id(
$fid, MUST_EXIST);
// make sure the function is not there yet
if (!$webservicemanager->service_function_exists($function->name,
$service->id)) {
$webservicemanager->add_external_function_to_service(
$function->name, $service->id);
}
}
redirect($functionlisturl);
}
//Add function operation page output
echo $OUTPUT->header();
echo $OUTPUT->heading($service->name);
$mform->display();
echo $OUTPUT->footer();
die;
}
break;
case 'delete':
$PAGE->navbar->add(get_string('removefunction', 'webservice'));
/// Delete function operation
if (confirm_sesskey() and $service and empty($service->component)) {
//check that the function to remove exists
$function = $webservicemanager->get_external_function_by_id(
$functionid, MUST_EXIST);
//display confirmation page
if (!$confirm) {
echo $OUTPUT->header();
echo $renderer->admin_remove_service_function_confirmation($function, $service);
echo $OUTPUT->footer();
die;
}
//or remove the function from the service, then redirect to the function list
$webservicemanager->remove_external_function_from_service($function->name,
$service->id);
redirect($functionlisturl);
}
break;
}
/// OUTPUT function list page
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('addservicefunction', 'webservice', $service->name));
$functions = $webservicemanager->get_external_functions(array($service->id));
echo $renderer->admin_service_function_list($functions, $service);
echo $OUTPUT->footer();
@@ -0,0 +1,80 @@
<?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/>.
/**
* Web services user settings UI
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/webservice/lib.php');
require_once($CFG->dirroot . '/' . $CFG->admin . '/webservice/forms.php');
$serviceid = required_param('serviceid', PARAM_INT);
$userid = required_param('userid', PARAM_INT);
admin_externalpage_setup('externalserviceusersettings');
//define nav bar
$PAGE->set_url('/admin/webservice/service_user_settings.php', ['serviceid' => $serviceid, 'userid' => $userid]);
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
$node->make_active();
}
$returnurl = new moodle_url('/admin/webservice/service_users.php', ['id' => $serviceid]);
$PAGE->navbar->add(get_string('serviceusers', 'webservice'), $returnurl);
$PAGE->navbar->add(get_string('serviceusersettings', 'webservice'));
$formaction = new moodle_url('', array('id' => $serviceid, 'userid' => $userid));
$webservicemanager = new webservice();
$serviceuser = $webservicemanager->get_ws_authorised_user($serviceid, $userid);
$usersettingsform = new external_service_authorised_user_settings_form($formaction, $serviceuser);
$settingsformdata = $usersettingsform->get_data();
if ($usersettingsform->is_cancelled()) {
redirect($returnurl);
} else if (!empty($settingsformdata) and confirm_sesskey()) {
/// save user settings (administrator clicked on update button)
$settingsformdata = (object)$settingsformdata;
$serviceuserinfo = new stdClass();
$serviceuserinfo->id = $serviceuser->serviceuserid;
$serviceuserinfo->iprestriction = $settingsformdata->iprestriction;
$serviceuserinfo->validuntil = $settingsformdata->validuntil;
$webservicemanager->update_ws_authorised_user($serviceuserinfo);
//TODO: assign capability
//display successful notification
$notification = $OUTPUT->notification(get_string('usersettingssaved', 'webservice'), 'notifysuccess');
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('serviceusersettings', 'webservice'), 3, 'main');
if (!empty($notification)) {
echo $notification;
}
$usersettingsform->display();
echo $OUTPUT->footer();
+123
View File
@@ -0,0 +1,123 @@
<?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/>.
/**
* Web services services UI
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/' . $CFG->admin . '/webservice/lib.php');
require_once($CFG->dirroot . '/webservice/lib.php');
$id = required_param('id', PARAM_INT);
admin_externalpage_setup('externalserviceusers');
//define nav bar
$PAGE->set_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $id));
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
$node->make_active();
}
$PAGE->navbar->add(get_string('serviceusers', 'webservice'),
new moodle_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $id)));
$webservicemanager = new webservice();
/// Get the user_selector we will need.
$potentialuserselector = new service_user_selector('addselect',
array('serviceid' => $id, 'displayallowedusers' => 0));
$alloweduserselector = new service_user_selector('removeselect',
array('serviceid' => $id, 'displayallowedusers' => 1));
/// Process incoming user assignments to the service
if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
$userstoassign = $potentialuserselector->get_selected_users();
if (!empty($userstoassign)) {
foreach ($userstoassign as $adduser) {
$serviceuser = new stdClass();
$serviceuser->externalserviceid = $id;
$serviceuser->userid = $adduser->id;
$webservicemanager->add_ws_authorised_user($serviceuser);
$params = array(
'objectid' => $serviceuser->externalserviceid,
'relateduserid' => $serviceuser->userid
);
$event = \core\event\webservice_service_user_added::create($params);
$event->trigger();
}
$potentialuserselector->invalidate_selected_users();
$alloweduserselector->invalidate_selected_users();
}
}
/// Process removing user assignments to the service
if (optional_param('remove', false, PARAM_BOOL) && confirm_sesskey()) {
$userstoremove = $alloweduserselector->get_selected_users();
if (!empty($userstoremove)) {
foreach ($userstoremove as $removeuser) {
$webservicemanager->remove_ws_authorised_user($removeuser, $id);
$params = array(
'objectid' => $id,
'relateduserid' => $removeuser->id
);
$event = \core\event\webservice_service_user_removed::create($params);
$event->trigger();
}
$potentialuserselector->invalidate_selected_users();
$alloweduserselector->invalidate_selected_users();
}
}
/// Print the form.
/// display the UI
$renderer = $PAGE->get_renderer('core', 'webservice');
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('selectauthorisedusers', 'webservice'), 3, 'main');
$selectoroptions = new stdClass();
$selectoroptions->serviceid = $id;
$selectoroptions->alloweduserselector = $alloweduserselector;
$selectoroptions->potentialuserselector = $potentialuserselector;
echo $renderer->admin_authorised_user_selector($selectoroptions);
/// get the missing capabilities for all users (will be displayed into the renderer)
$allowedusers = $webservicemanager->get_ws_authorised_users($id);
$usersmissingcaps = $webservicemanager->get_missing_capabilities_by_users($allowedusers, $id);
//add the missing capabilities to the allowed users object to be displayed by renderer
foreach ($allowedusers as &$alloweduser) {
if (!is_siteadmin($alloweduser->id) and array_key_exists($alloweduser->id, $usersmissingcaps)) {
$alloweduser->missingcapabilities = $usersmissingcaps[$alloweduser->id];
}
}
/// display the list of allowed users with their options (ip/timecreated / validuntil...)
//check that the user has the service required capability (if needed)
if (!empty($allowedusers)) {
$renderer = $PAGE->get_renderer('core', 'webservice');
echo $OUTPUT->heading(get_string('serviceuserssettings', 'webservice'), 3, 'main');
echo $renderer->admin_authorised_user_list($allowedusers, $id);
}
echo $OUTPUT->footer();
+169
View File
@@ -0,0 +1,169 @@
<?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/>.
/**
* Web service test client.
*
* @package webservice
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @author Petr Skoda (skodak)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require('../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot . "/" . $CFG->admin . "/webservice/testclient_forms.php");
$function = optional_param('function', '', PARAM_PLUGIN);
$protocol = optional_param('protocol', '', PARAM_ALPHA);
$authmethod = optional_param('authmethod', '', PARAM_ALPHA);
$PAGE->set_url('/' . $CFG->admin . '/webservice/testclient.php');
$PAGE->navbar->ignore_active(true);
$PAGE->navbar->add(get_string('administrationsite'));
$PAGE->navbar->add(get_string('development', 'admin'));
$PAGE->navbar->add(get_string('testclient', 'webservice'),
new moodle_url('/' . $CFG->admin . '/webservice/testclient.php'));
if (!empty($function)) {
$PAGE->navbar->add($function);
}
admin_externalpage_setup('testclient');
// list of all available functions for testing
$allfunctions = $DB->get_records('external_functions', array(), 'name ASC');
$functions = array();
foreach ($allfunctions as $f) {
$finfo = \core_external\external_api::external_function_info($f);
if (!empty($finfo->testclientpath) and file_exists($CFG->dirroot.'/'.$finfo->testclientpath)) {
//some plugins may want to have own test client forms
include_once($CFG->dirroot.'/'.$finfo->testclientpath);
}
$class = $f->name.'_testclient_form';
if (class_exists($class)) {
$functions[$f->name] = $f->name;
continue;
}
}
// Allow only functions available for testing.
if (!isset($functions[$function])) {
$function = '';
}
// list all enabled webservices
$available_protocols = core_component::get_plugin_list('webservice');
$active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
$protocols = array();
foreach ($active_protocols as $p) {
if (empty($available_protocols[$p])) {
continue;
}
include_once($available_protocols[$p].'/locallib.php');
if (!class_exists('webservice_'.$p.'_test_client')) {
// test client support not implemented
continue;
}
$protocols[$p] = get_string('pluginname', 'webservice_'.$p);
}
// Allow only protocols supporting the test client.
if (!isset($protocols[$protocol])) {
$protocol = '';
}
if (!$function or !$protocol) {
$mform = new webservice_test_client_form(null, array($functions, $protocols));
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('testclient', 'webservice'));
echo $OUTPUT->box_start();
$url = new moodle_url('/' . $CFG->admin . '/settings.php?section=debugging');
$atag =html_writer::start_tag('a', array('href' => $url)).get_string('debug', 'admin').html_writer::end_tag('a');
$descparams = new stdClass();
$descparams->atag = $atag;
$descparams->mode = get_string('debugnormal', 'admin');
echo get_string('testclientdescription', 'webservice', $descparams);
echo $OUTPUT->box_end();
$mform->display();
echo $OUTPUT->footer();
die;
}
$class = $function.'_testclient_form';
$mform = new $class(null, array('authmethod' => $authmethod));
$mform->set_data(array('function'=>$function, 'protocol'=>$protocol));
if ($mform->is_cancelled()) {
redirect('testclient.php');
} else if ($data = $mform->get_data()) {
$functioninfo = \core_external\external_api::external_function_info($function);
// first load lib of selected protocol
require_once("$CFG->dirroot/webservice/$protocol/locallib.php");
$testclientclass = "webservice_{$protocol}_test_client";
if (!class_exists($testclientclass)) {
throw new coding_exception('Missing WS test class in protocol '.$protocol);
}
$testclient = new $testclientclass();
$serverurl = "$CFG->wwwroot/webservice/$protocol/";
if ($authmethod == 'simple') {
$serverurl .= 'simpleserver.php';
$serverurl .= '?wsusername='.urlencode($data->wsusername);
$serverurl .= '&wspassword='.urlencode($data->wspassword);
} else if ($authmethod == 'token') {
$serverurl .= 'server.php';
$serverurl .= '?wstoken='.urlencode($data->token);
}
// now get the function parameters
$params = $mform->get_params();
// now test the parameters, this also fixes PHP data types
$params = \core_external\external_api::validate_parameters($functioninfo->parameters_desc, $params);
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('pluginname', 'webservice_'.$protocol).': '.$function);
echo 'URL: '.s($serverurl);
echo $OUTPUT->box_start();
try {
$response = $testclient->simpletest($serverurl, $function, $params);
echo str_replace("\n", '<br />', s(var_export($response, true)));
} catch (Exception $ex) {
//TODO: handle exceptions and faults without exposing of the sensitive information such as debug traces!
echo str_replace("\n", '<br />', s($ex));
}
echo $OUTPUT->box_end();
$mform->display();
echo $OUTPUT->footer();
die;
} else {
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('pluginname', 'webservice_'.$protocol).': '.$function);
$mform->display();
echo $OUTPUT->footer();
die;
}
+352
View File
@@ -0,0 +1,352 @@
<?php
require_once($CFG->libdir.'/formslib.php');
class webservice_test_client_form extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form;
list($functions, $protocols) = $this->_customdata;
$mform->addElement('header', 'wstestclienthdr', get_string('testclient', 'webservice'));
$authmethod = array('simple' => 'simple', 'token' => 'token');
$mform->addElement('select', 'authmethod', get_string('authmethod', 'webservice'), $authmethod);
$mform->setType('simple', PARAM_ALPHA);
$mform->addElement('select', 'protocol', get_string('protocol', 'webservice'), $protocols);
$mform->setType('protocol', PARAM_ALPHA);
$mform->addElement('select', 'function', get_string('function', 'webservice'), $functions);
$mform->setType('function', PARAM_PLUGIN);
$this->add_action_buttons(false, get_string('select'));
}
}
// === Test client forms ===
/**
* Base class for implementations of WS test client forms.
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2017 Marina Glancy
*/
abstract class webservice_test_client_base_form extends moodleform {
/**
* Definition of the parameters used by this WS function
*/
abstract protected function test_client_definition();
/**
* The form definition.
*/
public function definition() {
$mform = $this->_form;
$mform->addElement('header', 'wstestclienthdr', get_string('testclient', 'webservice'));
// Note: these values are intentionally PARAM_RAW - we want users to test any rubbish as parameters.
$data = $this->_customdata;
if ($data['authmethod'] == 'simple') {
$mform->addElement('text', 'wsusername', 'wsusername');
$mform->setType('wsusername', core_user::get_property_type('username'));
$mform->addElement('text', 'wspassword', 'wspassword');
$mform->setType('wspassword', core_user::get_property_type('password'));
} else if ($data['authmethod'] == 'token') {
$mform->addElement('text', 'token', 'token');
$mform->setType('token', PARAM_RAW_TRIMMED);
}
$mform->addElement('hidden', 'authmethod', $data['authmethod']);
$mform->setType('authmethod', PARAM_ALPHA);
$mform->addElement('hidden', 'function');
$mform->setType('function', PARAM_PLUGIN);
$mform->addElement('hidden', 'protocol');
$mform->setType('protocol', PARAM_ALPHA);
$this->test_client_definition();
$this->add_action_buttons(true, get_string('execute', 'webservice'));
}
/**
* Get the parameters that the user submitted using the form.
* @return array|null
*/
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
return array_diff_key((array)$data, ['submitbutton' => 1, 'protocol' => 1, 'function' => 1,
'wsusername' => 1, 'wspassword' => 1, 'token' => 1, 'authmethod' => 1]);
}
}
/**
* Form class for create_categories() web service function test.
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2012 Fabio Souto
*/
class core_course_create_categories_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
$mform = $this->_form;
$mform->addElement('text', 'name[0]', 'name[0]');
$mform->addElement('text', 'parent[0]', 'parent[0]');
$mform->addElement('text', 'idnumber[0]', 'idnumber[0]');
$mform->addElement('text', 'description[0]', 'description[0]');
$mform->addElement('text', 'name[1]', 'name[1]');
$mform->addElement('text', 'parent[1]', 'parent[1]');
$mform->addElement('text', 'idnumber[1]', 'idnumber[1]');
$mform->addElement('text', 'description[1]', 'description[1]');
$mform->setType('name', PARAM_TEXT);
$mform->setType('parent', PARAM_INT);
$mform->setType('idnumber', PARAM_RAW);
$mform->setType('description', PARAM_RAW);
}
/**
* Get the parameters that the user submitted using the form.
* @return array|null
*/
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
$params = array();
$params['categories'] = array();
for ($i=0; $i<10; $i++) {
if (empty($data->name[$i])) {
continue;
}
$params['categories'][] = array('name'=>$data->name[$i], 'parent'=>$data->parent[$i],
'idnumber'=>$data->idnumber[$i], 'description'=>$data->description[$i]);
}
return $params;
}
}
/**
* Form class for delete_categories() web service function test.
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2012 Fabio Souto
*/
class core_course_delete_categories_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
$mform = $this->_form;
$mform->addElement('text', 'id[0]', 'id[0]');
$mform->addElement('text', 'newparent[0]', 'newparent[0]');
$mform->addElement('text', 'recursive[0]', 'recursive[0]');
$mform->addElement('text', 'id[1]', 'id[1]');
$mform->addElement('text', 'newparent[1]', 'newparent[1]');
$mform->addElement('text', 'recursive[1]', 'recursive[1]');
$mform->setType('id', PARAM_INT);
$mform->setType('newparent', PARAM_INT);
$mform->setType('recursive', PARAM_BOOL);
}
/**
* Get the parameters that the user submitted using the form.
* @return array|null
*/
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
$params = array();
$params['categories'] = array();
for ($i=0; $i<10; $i++) {
if (empty($data->id[$i])) {
continue;
}
$attrs = array();
$attrs['id'] = $data->id[$i];
if (!empty($data->newparent[$i])) {
$attrs['newparent'] = $data->newparent[$i];
}
if (!empty($data->recursive[$i])) {
$attrs['recursive'] = $data->recursive[$i];
}
$params['categories'][] = $attrs;
}
return $params;
}
}
/**
* Form class for create_categories() web service function test.
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2012 Fabio Souto
*/
class core_course_update_categories_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
$mform = $this->_form;
$mform->addElement('text', 'id[0]', 'id[0]');
$mform->addElement('text', 'name[0]', 'name[0]');
$mform->addElement('text', 'parent[0]', 'parent[0]');
$mform->addElement('text', 'idnumber[0]', 'idnumber[0]');
$mform->addElement('text', 'description[0]', 'description[0]');
$mform->addElement('text', 'id[1]', 'id[1]');
$mform->addElement('text', 'name[1]', 'name[1]');
$mform->addElement('text', 'parent[1]', 'parent[1]');
$mform->addElement('text', 'idnumber[1]', 'idnumber[1]');
$mform->addElement('text', 'description[1]', 'description[1]');
$mform->setType('id', PARAM_INT);
$mform->setType('name', PARAM_TEXT);
$mform->setType('parent', PARAM_INT);
$mform->setType('idnumber', PARAM_RAW);
$mform->setType('description', PARAM_RAW);
}
/**
* Get the parameters that the user submitted using the form.
* @return array|null
*/
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
$params = array();
$params['categories'] = array();
for ($i=0; $i<10; $i++) {
if (empty($data->id[$i])) {
continue;
}
$attrs = array();
$attrs['id'] = $data->id[$i];
if (!empty($data->name[$i])) {
$attrs['name'] = $data->name[$i];
}
if (!empty($data->parent[$i])) {
$attrs['parent'] = $data->parent[$i];
}
if (!empty($data->idnumber[$i])) {
$attrs['idnumber'] = $data->idnumber[$i];
}
if (!empty($data->description[$i])) {
$attrs['description'] = $data->description[$i];
}
$params['categories'][] = $attrs;
}
return $params;
}
}
/**
* Test class for WS function core_fetch_notifications
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2017 Marina Glancy
*/
class core_fetch_notifications_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
$mform = $this->_form;
$mform->addElement('text', 'contextid', 'contextid');
$mform->setType('contextid', PARAM_INT);
$mform->setDefault('contextid', context_system::instance()->id);
}
}
/**
* Test class for WS function get_site_info
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2017 Marina Glancy
*/
class core_webservice_get_site_info_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
}
}
/**
* Test class for WS function core_get_string
*
* @package core_webservice
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright 2017 Marina Glancy
*/
class core_get_string_testclient_form extends webservice_test_client_base_form {
/**
* The form definition.
*/
protected function test_client_definition() {
$mform = $this->_form;
$mform->addElement('text', 'stringid', 'stringid');
$mform->setType('stringid', PARAM_STRINGID);
$mform->addElement('text', 'component', 'component');
$mform->setType('component', PARAM_COMPONENT);
$mform->addElement('text', 'lang', 'lang');
$mform->setType('lang', PARAM_LANG);
$mform->addElement('text', 'stringparams_name[1]', 'Parameter 1 name');
$mform->setType('stringparams_name[1]', PARAM_ALPHANUMEXT);
$mform->addElement('text', 'stringparams_value[1]', 'Parameter 1 value');
$mform->setType('stringparams_value[1]', PARAM_RAW);
$mform->addElement('text', 'stringparams_name[2]', 'Parameter 2 name');
$mform->setType('stringparams_name[2]', PARAM_ALPHANUMEXT);
$mform->addElement('text', 'stringparams_value[2]', 'Parameter 2 value');
$mform->setType('stringparams_value[2]', PARAM_RAW);
$mform->addElement('text', 'stringparams_name[3]', 'Parameter 3 name');
$mform->setType('stringparams_name[3]', PARAM_ALPHANUMEXT);
$mform->addElement('text', 'stringparams_value[3]', 'Parameter 3 value');
$mform->setType('stringparams_value[3]', PARAM_RAW);
$mform->addElement('static', 'paramnote', '', 'If a parameter is not an object, only specify "Parameter 1 value"');
}
/**
* Get the parameters that the user submitted using the form.
* @return array|null
*/
public function get_params() {
$params = parent::get_params();
if ($params === null) {
return null;
}
$params['stringparams'] = [];
for ($idx = 1; $idx <= 3; $idx++) {
$name = isset($params['stringparams_name'][$idx]) ? strval($params['stringparams_name'][$idx]) : '';
$value = isset($params['stringparams_value'][$idx]) ? strval($params['stringparams_value'][$idx]) : '';
if ($name !== '' || $value !== '') {
if ($name === '') {
$params['stringparams'][] = ['value' => $value];
} else {
$params['stringparams'][] = ['name' => $name, 'value' => $value];
}
}
}
unset($params['stringparams_name']);
unset($params['stringparams_value']);
return $params;
}
}
+190
View File
@@ -0,0 +1,190 @@
<?php
// This file is part of Moodle - https://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/>.
/**
* Web services / external tokens management UI.
*
* @package core_webservice
* @category admin
* @copyright 2009 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require(__DIR__ . '/../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/webservice/lib.php');
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$tokenid = optional_param('tokenid', '', PARAM_SAFEDIR);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$fname = optional_param('fname', '', PARAM_ALPHANUM);
$fusers = optional_param_array('fusers', [], PARAM_INT);
$fservices = optional_param_array('fservices', [], PARAM_INT);
admin_externalpage_setup('webservicetokens');
$PAGE->set_primary_active_tab('siteadminnode');
$PAGE->navbar->add(get_string('managetokens', 'webservice'),
new moodle_url('/admin/webservice/tokens.php'));
if ($action === 'create') {
$PAGE->navbar->add(get_string('createtoken', 'webservice'), $PAGE->url);
$webservicemanager = new webservice();
$mform = new \core_webservice\token_form(null, ['action' => 'create']);
$data = $mform->get_data();
if ($mform->is_cancelled()) {
redirect($PAGE->url);
} else if ($data) {
ignore_user_abort(true);
// Check the user is allowed for the service.
$selectedservice = $webservicemanager->get_external_service_by_id($data->service);
if ($selectedservice->restrictedusers) {
$restricteduser = $webservicemanager->get_ws_authorised_user($data->service, $data->user);
if (empty($restricteduser)) {
$errormsg = $OUTPUT->notification(get_string('usernotallowed', 'webservice', $selectedservice->name));
}
}
$user = \core_user::get_user($data->user, '*', MUST_EXIST);
\core_user::require_active_user($user);
// Generate the token.
if (empty($errormsg)) {
\core_external\util::generate_token(
EXTERNAL_TOKEN_PERMANENT,
\core_external\util::get_service_by_id($data->service),
$data->user,
context_system::instance(),
$data->validuntil,
$data->iprestriction,
$data->name
);
redirect($PAGE->url);
}
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('createtoken', 'webservice'));
if (!empty($errormsg)) {
echo $errormsg;
}
$mform->display();
echo $OUTPUT->footer();
die();
}
if ($action === 'delete') {
$PAGE->navbar->add(get_string('deletetoken', 'webservice'), $PAGE->url);
$webservicemanager = new webservice();
$token = $webservicemanager->get_token_by_id_with_details($tokenid);
if ($token->creatorid != $USER->id) {
require_capability('moodle/webservice:managealltokens', context_system::instance());
}
if ($confirm && confirm_sesskey()) {
$webservicemanager->delete_user_ws_token($token->id);
redirect($PAGE->url);
}
echo $OUTPUT->header();
echo $OUTPUT->confirm(
get_string('deletetokenconfirm', 'webservice', [
'user' => $token->firstname . ' ' . $token->lastname,
'service' => $token->name,
]),
new single_button(new moodle_url('/admin/webservice/tokens.php', [
'tokenid' => $token->id,
'action' => 'delete',
'confirm' => 1,
'sesskey' => sesskey(),
]), get_string('delete')),
$PAGE->url
);
echo $OUTPUT->footer();
die();
}
// Pre-populate the form with the values that come as a part of the URL - typically when using the table_sql control
// links.
$filterdata = (object)[
'name' => $fname,
'users' => $fusers,
'services' => $fservices,
];
$filter = new \core_webservice\token_filter($PAGE->url, $filterdata);
$filter->set_data($filterdata);
if ($filter->is_submitted()) {
$filterdata = $filter->get_data();
if (isset($filterdata->resetbutton)) {
redirect($PAGE->url);
}
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('managetokens', 'core_webservice'));
echo html_writer::div($OUTPUT->render(new single_button(new moodle_url($PAGE->url, ['action' => 'create']),
get_string('createtoken', 'core_webservice'), 'get', single_button::BUTTON_PRIMARY)), 'my-3');
if (!empty($SESSION->webservicenewlycreatedtoken)) {
$webservicemanager = new webservice();
$newtoken = $webservicemanager->get_created_by_user_ws_token(
$USER->id,
$SESSION->webservicenewlycreatedtoken
);
if ($newtoken) {
// Unset the session variable.
unset($SESSION->webservicenewlycreatedtoken);
// Display the newly created token.
echo $OUTPUT->render_from_template(
'core_admin/webservice_token_new', ['token' => $newtoken->token, 'tokenname' => $newtoken->tokenname]
);
}
}
$filter->display();
$table = new \core_webservice\token_table('webservicetokens', $filterdata);
// In order to not lose the filter form values by clicking the table control links, make them part of the table's baseurl.
$baseurl = new moodle_url($PAGE->url, ['fname' => $filterdata->name]);
foreach ($filterdata->users as $i => $userid) {
$baseurl->param("fusers[{$i}]", $userid);
}
foreach ($filterdata->services as $i => $serviceid) {
$baseurl->param("fservices[{$i}]", $serviceid);
}
$table->define_baseurl($baseurl);
$table->attributes['class'] = 'admintable generaltable';
$table->out(30, false);
echo $OUTPUT->footer();