MDL-75318 core: External services for sharing course to MoodleNet

This commit is contained in:
Safat 2023-06-01 00:54:43 +10:00
parent 933ab5201f
commit 17b565f957
9 changed files with 573 additions and 13 deletions

View File

@ -69,8 +69,9 @@ class moodlenet_auth_check extends external_api {
// Check capability.
$coursecontext = context_course::instance($courseid);
$usercanshare = utilities::can_user_share($coursecontext, $USER->id);
if (!$usercanshare) {
$usercanshareactivity = utilities::can_user_share($coursecontext, $USER->id, 'activity');
$usercansharecourse = utilities::can_user_share($coursecontext, $USER->id, 'course');
if (!$usercanshareactivity && !$usercansharecourse) {
return self::return_errors($courseid, 'errorpermission',
get_string('nopermissions', 'error', get_string('moodlenet:sharetomoodlenet', 'moodle')));
}

View File

@ -80,21 +80,13 @@ class moodlenet_get_share_info_activity extends external_api {
}
$warnings = [];
$supporturl = '';
$supporturl = utilities::get_support_url();
$issuerid = get_config('moodlenet', 'oauthservice');
if (empty($issuerid)) {
return self::return_errors(0, 'errorissuernotset', get_string('moodlenet:issuerisnotset', 'moodle'));
}
if ($CFG->supportavailability && $CFG->supportavailability != CONTACT_SUPPORT_DISABLED) {
if (!empty($CFG->supportpage)) {
$supporturl = $CFG->supportpage;
} else {
$supporturl = $CFG->wwwroot . '/user/contactsitesupport.php';
}
}
// Get the issuer.
$issuer = api::get_issuer($issuerid);
// Validate the issuer and check if it is enabled or not.

View File

@ -0,0 +1,143 @@
<?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_course;
use core\moodlenet\utilities;
use core\oauth2\api;
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_warnings;
/**
* The external API to get MoodleNet information about the course to be shared.
*
* @package core
* @copyright 2023 Safat Shahin <safat.shahin@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 4.3
*/
class moodlenet_get_shared_course_info extends external_api {
/**
* Returns description of parameters.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([
'courseid' => new external_value(PARAM_INT, 'The course id', VALUE_REQUIRED),
]);
}
/**
* External function to get the course information.
*
* @param int $courseid The course id
* @return array
*/
public static function execute(int $courseid): array {
global $CFG, $USER;
[
'courseid' => $courseid
] = self::validate_parameters(self::execute_parameters(), [
'courseid' => $courseid
]);
// Get course.
$course = get_course($courseid);
// Check capability.
$coursecontext = context_course::instance($course->id);
if (!utilities::can_user_share($coursecontext, $USER->id, 'course')) {
return self::return_errors($courseid, 'errorpermission',
get_string('nopermissions', 'error', get_string('moodlenet:sharetomoodlenet', 'moodle')));
}
$warnings = [];
$supporturl = utilities::get_support_url();
$issuerid = get_config('moodlenet', 'oauthservice');
if (empty($issuerid)) {
return self::return_errors(0, 'errorissuernotset', get_string('moodlenet:issuerisnotset', 'moodle'));
}
// Get the issuer.
$issuer = api::get_issuer($issuerid);
// Validate the issuer and check if it is enabled or not.
if (!utilities::is_valid_instance($issuer)) {
return self::return_errors($issuerid, 'errorissuernotenabled', get_string('moodlenet:issuerisnotenabled', 'moodle'));
}
return [
'status' => true,
'name' => $course->fullname,
'type' => get_string('course'),
'server' => $issuer->get_display_name(),
'supportpageurl' => $supporturl,
'issuerid' => $issuerid,
'warnings' => $warnings
];
}
/**
* Describes the data returned from the external function.
*
* @return external_single_structure
*/
public static function execute_returns(): external_single_structure {
return new external_single_structure([
'name' => new external_value(PARAM_TEXT, 'Course short name'),
'type' => new external_value(PARAM_TEXT, 'Course type'),
'server' => new external_value(PARAM_TEXT, 'MoodleNet server'),
'supportpageurl' => new external_value(PARAM_URL, 'Support page URL'),
'issuerid' => new external_value(PARAM_INT, 'MoodleNet issuer id'),
'status' => new external_value(PARAM_BOOL, 'status: true if success'),
'warnings' => new external_warnings()
]);
}
/**
* Handle return error.
*
* @param int $itemid Item id.
* @param string $warningcode Warning code.
* @param string $message Message.
* @param int $issuerid Issuer id.
* @return array
*/
protected static function return_errors(int $itemid, string $warningcode, string $message, int $issuerid = 0): array {
$warnings[] = [
'item' => $itemid,
'warningcode' => $warningcode,
'message' => $message
];
return [
'status' => false,
'name' => '',
'type' => '',
'server' => '',
'supportpageurl' => '',
'issuerid' => $issuerid,
'warnings' => $warnings
];
}
}

View File

@ -116,7 +116,7 @@ class moodlenet_send_activity extends external_api {
try {
$moodlenetclient = new moodlenet_client($client, $oauthclient);
$activitysender = new activity_sender($cmid, $USER->id, $moodlenetclient, $oauthclient, $shareformat);
$result = $activitysender->share_activity();
$result = $activitysender->share_resource();
if (empty($result['drafturl'])) {
return self::return_errors($result['responsecode'], 'errorsendingactivity',
get_string('moodlenet:cannotconnecttoserver', 'moodle'));

View File

@ -0,0 +1,196 @@
<?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_course;
use core\http_client;
use core\moodlenet\course_sender;
use core\moodlenet\moodlenet_client;
use core\moodlenet\utilities;
use core\oauth2\api;
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_warnings;
use moodle_url;
/**
* The external API to send course to MoodleNet.
*
* @package core
* @copyright 2023 Safat Shahin <safat.shahin@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class moodlenet_send_course extends external_api {
/**
* Describes the parameters for sending the course.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([
'issuerid' => new external_value(PARAM_INT, 'OAuth 2 issuer ID', VALUE_REQUIRED),
'courseid' => new external_value(PARAM_INT, 'Course ID', VALUE_REQUIRED),
'shareformat' => new external_value(PARAM_INT, 'Share format', VALUE_REQUIRED),
]);
}
/**
* External function to send the course to MoodleNet.
*
* @param int $issuerid The MoodleNet OAuth 2 issuer ID
* @param int $courseid The course ID
* @param int $shareformat The share format being used, as defined by \core\moodlenet\course_sender
* @return array
*/
public static function execute(
int $issuerid,
int $courseid,
int $shareformat
): array {
global $CFG, $USER;
[
'issuerid' => $issuerid,
'courseid' => $courseid,
'shareformat' => $shareformat,
] = self::validate_parameters(self::execute_parameters(), [
'issuerid' => $issuerid,
'courseid' => $courseid,
'shareformat' => $shareformat,
]);
// Check capability.
$coursecontext = context_course::instance($courseid);
$usercanshare = utilities::can_user_share($coursecontext, $USER->id, 'course');
if (!$usercanshare) {
return self::return_errors(
$courseid,
'errorpermission',
get_string('nopermissions', 'error', get_string('moodlenet:sharetomoodlenet', 'moodle'))
);
}
// Check format.
if ($shareformat !== course_sender::SHARE_FORMAT_BACKUP) {
return self::return_errors(
$shareformat,
'errorinvalidformat',
get_string('invalidparameter', 'debug')
);
}
// Get the issuer.
$issuer = api::get_issuer($issuerid);
// Validate the issuer and check if it is enabled or not.
if (!utilities::is_valid_instance($issuer)) {
return self::return_errors(
$issuerid,
'errorissuernotenabled',
get_string('invalidparameter', 'debug')
);
}
// Get the OAuth Client.
if (!$oauthclient = api::get_user_oauth_client(
$issuer,
new moodle_url($CFG->wwwroot),
moodlenet_client::API_SCOPE_CREATE_RESOURCE
)) {
return self::return_errors(
$issuerid,
'erroroauthclient',
get_string('invalidparameter', 'debug')
);
}
// Check login state.
if (!$oauthclient->is_logged_in()) {
return self::return_errors(
$issuerid,
'erroroauthclient',
get_string('moodlenet:issuerisnotauthorized', 'moodle')
);
}
// Get the HTTP Client.
$client = new http_client();
// Share course.
try {
$moodlenetclient = new moodlenet_client($client, $oauthclient);
$coursesender = new course_sender($courseid, $USER->id, $moodlenetclient, $oauthclient, $shareformat);
$result = $coursesender->share_resource();
if (empty($result['drafturl'])) {
return self::return_errors(
$result['responsecode'],
'errorsendingcourse',
get_string('moodlenet:cannotconnecttoserver', 'moodle')
);
}
} catch (\moodle_exception | \JsonException $e) {
return self::return_errors(
0,
'errorsendingcourse',
$e->getMessage()
);
}
return [
'status' => true,
'resourceurl' => $result['drafturl'],
'warnings' => [],
];
}
/**
* Describes the data returned from the external function.
*
* @return external_single_structure
*/
public static function execute_returns(): external_single_structure {
return new external_single_structure([
'status' => new external_value(PARAM_BOOL, 'Status: true if success'),
'resourceurl' => new external_value(PARAM_URL, 'Resource URL from MoodleNet'),
'warnings' => new external_warnings(),
]);
}
/**
* Handle return error.
*
* @param int $itemid Item id
* @param string $warningcode Warning code
* @param string $message Message
* @return array
*/
protected static function return_errors(int $itemid, string $warningcode, string $message): array {
$warnings[] = [
'item' => $itemid,
'warningcode' => $warningcode,
'message' => $message,
];
return [
'status' => false,
'resourceurl' => '',
'warnings' => $warnings,
];
}
}

View File

@ -3101,6 +3101,18 @@ $functions = array(
'type' => 'write',
'ajax' => true,
],
'core_moodlenet_get_shared_course_info' => [
'classname' => 'core\external\moodlenet_get_shared_course_info',
'description' => 'Get information about an course being shared',
'type' => 'read',
'ajax' => true,
],
'core_moodlenet_send_course' => [
'classname' => 'core\external\moodlenet_send_course',
'description' => 'Send course to MoodleNet',
'type' => 'read',
'ajax' => true,
],
);
$services = array(

View File

@ -0,0 +1,103 @@
<?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 core\oauth2\api;
use core_external\external_api;
use externallib_advanced_testcase;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/lib/tests/moodlenet/helpers.php');
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* External functions test for moodlenet_get_shared_course_info.
*
* @package core
* @category test
* @copyright 2023 Safat Shahin <safat.shahin@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core\external\moodlenet_get_shared_course_info
*/
class moodlenet_get_shared_course_info_test extends externallib_advanced_testcase {
/**
* Test the behaviour of moodlenet_get_shared_course_info().
*
* @covers ::execute
*/
public function test_moodlenet_get_shared_course_info() {
global $CFG;
$this->resetAfterTest();
$this->setAdminUser();
$CFG->enablesharingtomoodlenet = true;
// Generate course and activities.
$course = $this->getDataGenerator()->create_course();
// Create dummy enabled issuer.
$issuer = \core\moodlenet\helpers::get_mock_issuer(1);
// Test the course with no OAuth2 setup yet.
$result = moodlenet_get_shared_course_info::execute($course->id);
$result = external_api::clean_returnvalue(moodlenet_get_shared_course_info::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertEmpty($result['name']);
$this->assertEmpty($result['type']);
$this->assertEmpty($result['server']);
$this->assertEmpty($result['supportpageurl']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals(0, $result['warnings'][0]['item']);
$this->assertEquals('errorissuernotset', $result['warnings'][0]['warningcode']);
$this->assertEquals(get_string('moodlenet:issuerisnotset', 'moodle'), $result['warnings'][0]['message']);
// Test the course with OAuth2 disabled.
set_config('oauthservice', $issuer->get('id'), 'moodlenet');
$issuer->set('enabled', 0);
$irecord = $issuer->to_record();
api::update_issuer($irecord);
$result = moodlenet_get_shared_course_info::execute($course->id);
$result = external_api::clean_returnvalue(moodlenet_get_shared_course_info::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertEmpty($result['name']);
$this->assertEmpty($result['type']);
$this->assertEmpty($result['server']);
$this->assertEmpty($result['supportpageurl']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals($issuer->get('id'), $result['warnings'][0]['item']);
$this->assertEquals('errorissuernotenabled', $result['warnings'][0]['warningcode']);
$this->assertEquals(get_string('moodlenet:issuerisnotenabled', 'moodle'), $result['warnings'][0]['message']);
// Test the course with support url is set to the internal contact site support page.
$issuer->set('enabled', 1);
$irecord = $issuer->to_record();
api::update_issuer($irecord);
$expectedsupporturl = $CFG->wwwroot . '/user/contactsitesupport.php';
$result = moodlenet_get_shared_course_info::execute($course->id);
$result = external_api::clean_returnvalue(moodlenet_get_shared_course_info::execute_returns(), $result);
$this->assertTrue($result['status']);
$this->assertEquals($course->fullname, $result['name']);
$this->assertEquals(get_string('course'), $result['type']);
$this->assertEquals($issuer->get_display_name(), $result['server']);
$this->assertEquals($expectedsupporturl, $result['supportpageurl']);
}
}

View File

@ -0,0 +1,113 @@
<?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 core\oauth2\api;
use core_external\external_api;
use externallib_advanced_testcase;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/lib/tests/moodlenet/helpers.php');
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* External functions test for moodlenet_send_course.
*
* @package core
* @category test
* @copyright 2023 Safat Shahin <safat.shahin@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core\external\moodlenet_send_course
*/
class moodlenet_send_course_test extends externallib_advanced_testcase {
/**
* Test the behaviour of moodlenet_send_course().
*
* @covers ::execute
*/
public function test_moodlenet_send_course() {
global $CFG;
$this->resetAfterTest();
$this->setAdminUser();
// Generate data.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$user = $generator->create_user();
$generator->enrol_user($user->id, $course->id, 'student');
// Create dummy issuer.
$issuer = \core\moodlenet\helpers::get_mock_issuer(0);
// Test with the experimental flag off.
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 0);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('errorissuernotenabled', $result['warnings'][0]['warningcode']);
$CFG->enablesharingtomoodlenet = true;
// Test with invalid format.
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 5);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('errorinvalidformat', $result['warnings'][0]['warningcode']);
// Test with the user does not have permission.
$this->setUser($user);
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 0);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('errorpermission', $result['warnings'][0]['warningcode']);
$this->setAdminUser();
// Test with the issuer is not enabled.
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 0);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('errorissuernotenabled', $result['warnings'][0]['warningcode']);
// Test with the issuer is enabled but not set in the MN Outbound setting.
$issuer->set('enabled', 1);
$irecord = $issuer->to_record();
api::update_issuer($irecord);
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 0);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('errorissuernotenabled', $result['warnings'][0]['warningcode']);
set_config('oauthservice', $issuer->get('id'), 'moodlenet');
// Test with the issuer not yet authorized.
$result = moodlenet_send_course::execute($issuer->get('id'), $course->id, 0);
$result = external_api::clean_returnvalue(moodlenet_send_course::execute_returns(), $result);
$this->assertFalse($result['status']);
$this->assertNotEmpty($result['warnings']);
$this->assertEquals('erroroauthclient', $result['warnings'][0]['warningcode']);
$this->assertEquals($issuer->get('id'), $result['warnings'][0]['item']);
$this->assertEquals(get_string('moodlenet:issuerisnotauthorized', 'moodle'), $result['warnings'][0]['message']);
}
}

View File

@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
$version = 2023081800.00; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2023081800.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '4.3dev+ (Build: 20230818)'; // Human-friendly version name