Merge branch 'MDL-77576-master-mvp' of https://github.com/safatshahin/moodle

This commit is contained in:
Andrew Nicols
2023-05-15 12:16:14 +08:00
66 changed files with 6331 additions and 9 deletions
+65
View File
@@ -0,0 +1,65 @@
<?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/>.
/**
* Communication and its plugins settings.
*
* @package core
* @subpackage communication
* @copyright 2023 Huong Nguyen <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../config.php');
require_once($CFG->libdir . '/adminlib.php');
$action = required_param('action', PARAM_ALPHANUMEXT);
$name = required_param('name', PARAM_PLUGIN);
$syscontext = context_system::instance();
$PAGE->set_url('/admin/communication.php');
$PAGE->set_context($syscontext);
require_admin();
require_sesskey();
$return = new moodle_url('/admin/settings.php', ['section' => 'managecommunicationproviders']);
$plugins = core_plugin_manager::instance()->get_plugins_of_type('communication');
$sortorder = array_flip(array_keys($plugins));
if (!isset($plugins[$name])) {
throw new moodle_exception('communicationprovidernotfound', 'core_communication', $return, $name);
}
$plugintypename = $plugins[$name]->type . '_' . $plugins[$name]->name;
switch ($action) {
case 'disable':
if ($plugins[$name]->is_enabled()) {
$class = core_plugin_manager::resolve_plugininfo_class('communication');
$class::enable_plugin($name, false);
}
break;
case 'enable':
if (!$plugins[$name]->is_enabled()) {
$class = core_plugin_manager::resolve_plugininfo_class('communication');
$class::enable_plugin($name, true);
}
break;
}
redirect($return);
+5
View File
@@ -38,6 +38,11 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
new lang_string('enablesharingtomoodlenet', 'core_admin'),
new lang_string('enablesharingtomoodlenet_desc', 'core_admin'), 0));
// New communication subsystem setting.
$temp->add(new admin_setting_configcheckbox('enablecommunicationsubsystem',
new lang_string('enablecommunicationsubsystem', 'core_admin'),
new lang_string('enablecommunicationsubsystem_desc', 'core_admin'), 0));
$ADMIN->add('experimental', $temp);
// "debugging" settingpage
+14
View File
@@ -781,6 +781,20 @@ if ($hassiteconfig) {
}
}
// Communication plugins.
if ($hassiteconfig && core_communication\api::is_available()) {
$ADMIN->add('modules', new admin_category('communicationsettings', new lang_string('communication', 'core_communication')));
$temp = new admin_settingpage('managecommunicationproviders',
new lang_string('managecommunicationproviders', 'core_communication'));
$temp->add(new \core_communication\admin\manage_communication_providers_page());
$ADMIN->add('communicationsettings', $temp);
$plugins = core_plugin_manager::instance()->get_plugins_of_type('communication');
foreach ($plugins as $plugin) {
/** @var \core\plugininfo\communication $plugin */
$plugin->load_settings($ADMIN, 'communicationsettings', $hassiteconfig);
}
}
// Content bank content types.
if ($hassiteconfig) {
$ADMIN->add('modules', new admin_category('contentbanksettings', new lang_string('contentbank')));
@@ -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/>.
namespace core_communication\admin;
use admin_setting;
use core_plugin_manager;
use core_text;
use html_table;
use html_table_row;
use html_writer;
use moodle_url;
/**
* Communication providers manager. Allow enable/disable communication providers and jump to settings.
*
* @package core_communication
* @copyright 2023 Huong Nguyen <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class manage_communication_providers_page extends admin_setting {
public function __construct() {
$this->nosave = true;
parent::__construct('managecommunications',
new \lang_string('managecommunicationproviders', 'core_communication'), '', '');
}
public function get_setting(): bool {
return true;
}
public function write_setting($data): string {
// Do not write any setting.
return '';
}
public function output_html($data, $query = ''): string {
global $OUTPUT;
$pluginmanager = core_plugin_manager::instance();
$plugins = $pluginmanager->get_plugins_of_type('communication');
if (empty($plugins)) {
return get_string('nocommunicationprovider', 'core_communication');
}
$table = new html_table();
$table->head = [
get_string('name'),
get_string('enable'),
get_string('settings'),
get_string('uninstallplugin', 'core_admin'),
];
$table->align = ['left', 'center', 'center', 'center'];
$table->attributes['class'] = 'managecommunicationtable generaltable admintable';
$table->data = [];
foreach ($plugins as $plugin) {
$class = '';
$actionurl = new moodle_url('/admin/communication.php', ['sesskey' => sesskey(), 'name' => $plugin->name]);
if ($pluginmanager->get_plugin_info('communication_' . $plugin->name)->get_status() ===
core_plugin_manager::PLUGIN_STATUS_MISSING) {
$strtypename = $plugin->displayname . ' (' . get_string('missingfromdisk') . ')';
} else {
$strtypename = $plugin->displayname;
}
if ($plugin->is_enabled()) {
$hideshow = html_writer::link($actionurl->out(false, ['action' => 'disable']),
$OUTPUT->pix_icon('t/hide', get_string('disable'), 'moodle', ['class' => 'iconsmall']));
} else {
$class = 'dimmed_text';
$hideshow = html_writer::link($actionurl->out(false, ['action' => 'enable']),
$OUTPUT->pix_icon('t/show', get_string('enable'), 'moodle', ['class' => 'iconsmall']));
}
$settings = '';
if ($plugin->get_settings_url()) {
$settings = html_writer::link($plugin->get_settings_url(), get_string('settings'));
}
$uninstall = '';
if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url(
'communication_' . $plugin->name, 'manage')) {
$uninstall = html_writer::link($uninstallurl, get_string('uninstallplugin', 'core_admin'));
}
$row = new html_table_row([$strtypename, $hideshow, $settings, $uninstall]);
if ($class) {
$row->attributes['class'] = $class;
}
$table->data[] = $row;
}
return highlight($query, html_writer::table($table));
}
public function is_related($query): bool {
if (parent::is_related($query)) {
return true;
}
$types = core_plugin_manager::instance()->get_plugins_of_type('communication');
foreach ($types as $type) {
if (strpos($type->component, $query) !== false ||
strpos(core_text::strtolower($type->displayname), $query) !== false) {
return true;
}
}
return false;
}
}
+402
View File
@@ -0,0 +1,402 @@
<?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_communication;
use core_communication\task\add_members_to_room_task;
use core_communication\task\create_and_configure_room_task;
use core_communication\task\delete_room_task;
use core_communication\task\remove_members_from_room;
use core_communication\task\update_room_task;
use stdClass;
/**
* Class api is the public endpoint of the communication api. This class is the point of contact for api usage.
*
* Communication api allows to add ad-hoc tasks to the queue to perform actions on the communication providers. This api will
* not allow any immediate actions to be performed on the communication providers. It will only add the tasks to the queue. The
* exception has been made for deletion of members in case of deleting the user. This is because the user will not be available.
* The member management api part allows run actions immediately if required.
*
* Communication api does allow to have form elements related to communication api in the required forms. This is done by using
* the form_definition method. This method will add the form elements to the form.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api {
/**
* @var null|processor $communication The communication settings object
*/
private ?processor $communication;
/**
* Communication handler constructor to manage and handle all communication related actions.
*
* This class is the entrypoint for all kinda usages.
* It will be used by the other api to manage the communication providers.
*
* @param string $component The component of the item for the instance
* @param string $instancetype The type of the item for the instance
* @param int $instanceid The id of the instance
*
*/
private function __construct(
private string $component,
private string $instancetype,
private int $instanceid
) {
$this->communication = processor::load_by_instance(
$this->component,
$this->instancetype,
$this->instanceid,
);
}
/**
* Get the communication processor object.
*
* @param string $component The component of the item for the instance
* @param string $instancetype The type of the item for the instance
* @param int $instanceid The id of the instance
* @return api
*/
public static function load_by_instance(
string $component,
string $instancetype,
int $instanceid
): self {
return new self($component, $instancetype, $instanceid);
}
/**
* Check if the communication api is enabled.
*/
public static function is_available(): bool {
return (bool) get_config('core', 'enablecommunicationsubsystem');
}
/**
* Get the communication room url.
*
* @return string|null
*/
public function get_communication_room_url(): ?string {
return $this->communication?->get_room_url();
}
/**
* Get the list of plugins for form selection.
*
* @return array
*/
public static function get_communication_plugin_list_for_form(): array {
// Add the option to have communication disabled.
$selection[processor::PROVIDER_NONE] = get_string('nocommunicationselected', 'communication');
$communicationplugins = \core\plugininfo\communication::get_enabled_plugins();
foreach ($communicationplugins as $pluginname => $notusing) {
$selection['communication_' . $pluginname] = get_string('pluginname', 'communication_'. $pluginname);
}
return $selection;
}
/**
* Define the form elements for the communication api.
* This method will be called from the form definition method of the instance.
*
* @param \MoodleQuickForm $mform The form element
*/
public function form_definition(\MoodleQuickForm $mform): void {
$mform->addElement('header', 'communication', get_string('communication', 'communication'));
// List the communication providers.
$communicationproviders = self::get_communication_plugin_list_for_form();
$mform->addElement(
'select',
'selectedcommunication',
get_string('seleccommunicationprovider', 'communication'),
$communicationproviders);
$mform->addHelpButton('selectedcommunication', 'seleccommunicationprovider', 'communication');
$mform->setDefault('selectedcommunication', processor::PROVIDER_NONE);
// Room name for the communication provider.
$mform->addElement('text',
'communicationroomname',
get_string('communicationroomname', 'communication'),
'maxlength="100" size="20"');
$mform->addHelpButton('communicationroomname', 'communicationroomname', 'communication');
$mform->setType('communicationroomname', PARAM_TEXT);
$mform->hideIf(
'communicationroomname',
'selectedcommunication',
'eq',
processor::PROVIDER_NONE);
}
/**
* Get the avatar file record for the avatar for filesystem.
*
* @param string $filename The filename of the avatar
* @return stdClass
*/
public function get_avatar_filerecord(string $filename): stdClass {
return (object) [
'contextid' => \context_system::instance()->id,
'component' => 'core_communication',
'filearea' => 'avatar',
'filename' => $filename,
'filepath' => '/',
'itemid' => $this->communication->get_id(),
];
}
/**
*
* Get the avatar file.
*
* If null is set, then delete the old area file and set the avatarfilename to null.
* This will make sure the plugin api deletes the avatar from the room.
*
* @param string|null $datauri The datauri of the avatar
* @return bool
*/
public function set_avatar_from_datauri_or_filepath(?string $datauri): bool {
global $DB;
$currentfilename = $DB->get_field('communication', 'avatarfilename', ['id' => $this->communication->get_id()]);
if (empty($datauri) && empty($currentfilename)) {
return false;
}
$currentfilerecord = $this->communication->get_avatar();
if (!empty($datauri) && !empty($currentfilerecord)) {
$currentfilehash = $currentfilerecord->get_contenthash();
$updatedfilehash = \file_storage::hash_from_string(file_get_contents($datauri));
// No update required.
if ($currentfilehash === $updatedfilehash) {
return false;
}
}
$context = \context_system::instance();
$filename = null;
$fs = get_file_storage();
$fs->delete_area_files(
$context->id,
'core_communication',
'avatar',
$this->communication->get_id()
);
if (!empty($datauri)) {
$filename = "avatar.svg";
$fs->create_file_from_string($this->get_avatar_filerecord($filename), file_get_contents($datauri));
}
$DB->set_field('communication', 'avatarfilename', $filename, ['id' => $this->communication->get_id()]);
return true;
}
/**
* Set the form data if the data is already available.
*
* @param \stdClass $instance The instance object
*/
public function set_data(\stdClass $instance): void {
if (!empty($instance->id) && $this->communication) {
$instance->selectedcommunication = $this->communication->get_provider();
$instance->communicationroomname = $this->communication->get_room_name();
}
}
/**
* Get the communication provider.
*
* @return string
*/
public function get_provider(): string {
if (!$this->communication) {
return '';
}
return $this->communication->get_provider();
}
/**
* Create a communication ad-hoc task for create operation.
* This method will add a task to the queue to create the room.
*
* @param string $selectedcommunication The selected communication provider
* @param string $communicationroomname The communication room name
* @param string|null $avatarurl The avatar url
*/
public function create_and_configure_room(
string $selectedcommunication,
string $communicationroomname,
?string $avatarurl = null,
): void {
if ($selectedcommunication !== processor::PROVIDER_NONE && $selectedcommunication !== '') {
// Create communication record.
$this->communication = processor::create_instance(
$selectedcommunication,
$this->instanceid,
$this->component,
$this->instancetype,
$communicationroomname,
);
// Set the avatar.
if (!empty($avatarurl)) {
$this->set_avatar_from_datauri_or_filepath($avatarurl);
}
// Add ad-hoc task to create the provider room.
create_and_configure_room_task::queue(
$this->communication,
);
}
}
/**
* Create a communication ad-hoc task for update operation.
* This method will add a task to the queue to update the room.
*
* @param string $selectedprovider The selected communication provider
* @param string $communicationroomname The communication room name
* @param string|null $avatarurl The avatar url
*/
public function update_room(
string $selectedprovider,
string $communicationroomname,
?string $avatarurl = null,
): void {
// Existing object found, let's update the communication record and associated actions.
if ($this->communication !== null) {
// Get the previous data to compare for update.
$previousroomname = $this->communication->get_room_name();
$previousprovider = $this->communication->get_provider();
// Update communication record.
$this->communication->update_instance($selectedprovider, $communicationroomname);
// Update the avatar.
$imageupdaterequired = $this->set_avatar_from_datauri_or_filepath($avatarurl);
// If the provider is none, we don't need to do anything from room point of view.
if ($this->communication->get_provider() === processor::PROVIDER_NONE) {
return;
}
// Add ad-hoc task to update the provider room if the room name changed.
if (
$previousprovider === $selectedprovider &&
($previousroomname !== $communicationroomname || $imageupdaterequired)
) {
update_room_task::queue(
$this->communication,
);
} else if (
$previousprovider !== $selectedprovider
) {
// Add ad-hoc task to create the provider room.
create_and_configure_room_task::queue(
$this->communication,
);
}
} else {
// The instance didn't have any communication record, so create one.
$this->create_and_configure_room($selectedprovider, $communicationroomname, $avatarurl);
}
}
/**
* Create a communication ad-hoc task for delete operation.
* This method will add a task to the queue to delete the room.
*/
public function delete_room(): void {
if ($this->communication !== null) {
// Add the ad-hoc task to remove the room data from the communication table and associated provider actions.
delete_room_task::queue(
$this->communication,
);
}
}
/**
* Create a communication ad-hoc task for add members operation and add the user mapping.
*
* This method will add a task to the queue to add the room users.
*
* @param array $userids The user ids to add to the room
* @param bool $queue Whether to queue the task or not
*/
public function add_members_to_room(array $userids, bool $queue = true): void {
// No communication object? something not done right.
if (!$this->communication) {
return;
}
// No userids? don't bother doing anything.
if (empty($userids)) {
return;
}
$this->communication->create_instance_user_mapping($userids);
if ($queue) {
add_members_to_room_task::queue(
$this->communication
);
}
}
/**
* Create a communication ad-hoc task for remove members operation or action immediately.
*
* This method will add a task to the queue to remove the room users.
*
* @param array $userids The user ids to remove from the room
* @param bool $queue Whether to queue the task or not
*/
public function remove_members_from_room(array $userids, bool $queue = true): void {
// No communication object? something not done right.
if (!$this->communication) {
return;
}
if ($this->communication->get_provider() === processor::PROVIDER_NONE) {
return;
}
// No user ids? don't bother doing anything.
if (empty($userids)) {
return;
}
$this->communication->add_delete_user_flag($userids);
if ($queue) {
remove_members_from_room::queue(
$this->communication
);
}
}
}
@@ -0,0 +1,38 @@
<?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_communication;
/**
* A base communication provider.
*
* This interface should be used to declare support for the instantiation method for communication providers.
*
* Every communication provider must, as a minimum, implement this provider.
*
* @package core_communication
* @copyright 2023 Andrew Lyons <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface communication_provider {
/**
* A base communication provider.
*
* @param processor $communication The communication object
*/
public static function load_for_instance(processor $communication): self;
}
@@ -0,0 +1,70 @@
<?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_communication\privacy;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\approved_userlist;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\userlist;
/**
* Privacy Subsystem for core_communication implementing null_provider.
*
* @package core_communication
* @copyright 2023 Huong Nguyen <[email protected]>
* @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\subsystem\provider,
\core_privacy\local\request\core_userlist_provider {
public static function get_metadata(collection $collection): collection {
$collection->add_database_table('communication_user', [
'commid' => 'privacy:metadata:communication_user:commid',
'userid' => 'privacy:metadata:communication_user:userid',
'synced' => 'privacy:metadata:communication_user:synced',
], 'privacy:metadata:communication_user');
return $collection;
}
public static function get_contexts_for_userid(int $userid): contextlist {
return new contextlist();
}
public static function export_user_data(approved_contextlist $contextlist) {
// None of the core communication tables should be exported.
}
public static function delete_data_for_all_users_in_context(\context $context) {
// None of the data from these tables should be deleted.
}
public static function delete_data_for_user(approved_contextlist $contextlist) {
// None of the data from these tables should be deleted.
}
public static function get_users_in_context(userlist $userlist) {
// Don't add any users.
}
public static function delete_data_for_users(approved_userlist $userlist) {
// None of the data from these tables should be deleted.
}
}
+563
View File
@@ -0,0 +1,563 @@
<?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_communication;
use stdClass;
use stored_file;
/**
* Class processor to manage the base operations of the providers.
*
* This class is responsible for creating, updating, deleting and loading the communication instance, associated actions.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class processor {
/** @var string The magic 'none' provider */
public const PROVIDER_NONE = 'none';
/** @var int The provider active flag */
public const PROVIDER_ACTIVE = 1;
/** @var int The provider inactive flag */
public const PROVIDER_INACTIVE = 0;
/** @var null|communication_provider|user_provider|room_chat_provider|room_user_provider The provider class */
private communication_provider|user_provider|room_chat_provider|room_user_provider|null $provider = null;
/**
* Communication processor constructor.
*
* @param stdClass $instancedata The instance data object
*/
protected function __construct(
private stdClass $instancedata,
) {
$providercomponent = $this->instancedata->provider;
if (!\core\plugininfo\communication::is_plugin_enabled($providercomponent)) {
throw new \moodle_exception('communicationproviderdisabled', 'core_communication', '', $providercomponent);
}
$providerclass = $this->get_classname_for_provider($providercomponent);
if (!class_exists($providerclass)) {
throw new \moodle_exception('communicationproviderclassnotfound', 'core_communication', '', $providerclass);
}
if (!is_a($providerclass, communication_provider::class, true)) {
// At the moment we only have one communication provider interface.
// In the future, we may have others, at which point we will support the newest first and
// emit a debugging notice for older ones.
throw new \moodle_exception('communicationproviderclassinvalid', 'core_communication', '', $providerclass);
}
$this->provider = $providerclass::load_for_instance($this);
}
/**
* Create communication instance.
*
* @param string $provider The communication provider
* @param int $instanceid The instance id
* @param string $component The component name
* @param string $instancetype The instance type
* @param string $roomname The room name
* @return processor|null
*/
public static function create_instance(
string $provider,
int $instanceid,
string $component,
string $instancetype,
string $roomname,
): ?self {
global $DB;
if ($provider === self::PROVIDER_NONE) {
return null;
}
$record = (object) [
'provider' => $provider,
'instanceid' => $instanceid,
'component' => $component,
'instancetype' => $instancetype,
'roomname' => $roomname,
'avatarfilename' => null,
'active' => self::PROVIDER_ACTIVE,
];
$record->id = $DB->insert_record('communication', $record);
return new self($record);
}
/**
* Update communication instance.
*
* @param string $provider The communication provider
* @param string $roomname The room name
*/
public function update_instance(
string $provider,
string $roomname,
): void {
global $DB;
if ($provider === self::PROVIDER_NONE) {
$this->instancedata->active = self::PROVIDER_INACTIVE;
} else {
$this->instancedata->provider = $provider;
$this->instancedata->active = self::PROVIDER_ACTIVE;
}
$this->instancedata->roomname = $roomname;
$DB->update_record('communication', $this->instancedata);
}
/**
* Delete communication data.
*/
public function delete_instance(): void {
global $DB;
$DB->delete_records('communication', ['id' => $this->instancedata->id]);
}
/**
* Get non synced instance user ids for the instance.
*
* @param bool $synced The synced status
* @param bool $deleted The deleted status
* @return array
*/
public function get_instance_userids(bool $synced = false, bool $deleted = false): array {
global $DB;
return $DB->get_fieldset_select(
'communication_user',
'userid',
'commid = ? AND synced = ? AND deleted = ?',
[$this->instancedata->id, (int) $synced, (int) $deleted]
);
}
/**
* Get existing instance user ids.
*
* @return array
*/
public function get_all_userids_for_instance(): array {
global $DB;
return $DB->get_fieldset_select(
'communication_user',
'userid',
'commid = ?',
[$this->instancedata->id]
);
}
/**
* Create communication user record for mapping and sync.
*
* @param array $userids The user ids
*/
public function create_instance_user_mapping(array $userids): void {
global $DB;
// Check if user ids exits in existing user ids.
$useridstoadd = array_diff($userids, $this->get_all_userids_for_instance());
foreach ($useridstoadd as $userid) {
$record = (object) [
'commid' => $this->instancedata->id,
'userid' => $userid,
];
$DB->insert_record('communication_user', $record);
}
$this->mark_users_as_not_deleted($userids);
}
/**
* Mark users as not deleted for the instance.
*
* @param array $userids The user ids
*/
public function mark_users_as_not_deleted(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->set_field_select(
'communication_user',
'deleted',
0,
'commid = ? AND userid IN (' . implode(',', $userids) . ')',
[$this->instancedata->id]
);
}
/**
* Mark users as synced for the instance.
*
* @param array $userids The user ids
*/
public function mark_users_as_synced(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->set_field_select(
'communication_user',
'synced',
1,
'commid = ? AND userid IN (' . implode(',', $userids) . ')',
[$this->instancedata->id]
);
}
/**
* Reset users sync flag for the instance.
*
* @param array $userids The user ids
*/
public function reset_users_sync_flag(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->set_field_select(
'communication_user',
'synced',
0,
'commid = ? AND userid IN (' . implode(',', $userids) . ')',
[$this->instancedata->id]
);
}
/**
* Delete users flag for the instance users.
*
* @param array $userids The user ids
*/
public function add_delete_user_flag(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->set_field_select(
'communication_user',
'deleted',
1,
'commid = ? AND userid IN (' . implode(',', $userids) . ')',
[$this->instancedata->id]
);
}
/**
* Delete communication user record for userid.
*
* @param array $userids The user ids
*/
public function delete_instance_user_mapping(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->delete_records_select(
'communication_user',
'commid = ? AND userid IN (' . implode(',', $userids) . ')',
[$this->instancedata->id]
);
}
/**
* Delete communication user record for userid who are not synced.
*
* @param array $userids The user ids
*/
public function delete_instance_non_synced_user_mapping(array $userids): void {
global $DB;
if (empty($userids)) {
return;
}
$DB->delete_records_select(
'communication_user',
'commid = ? AND userid IN (' . implode(',', $userids) . ') AND synced = ?' ,
[$this->instancedata->id, 0]
);
}
/**
* Delete communication user record for instance.
*/
public function delete_user_mappings_for_instance(): void {
global $DB;
$DB->delete_records('communication_user', [
'commid' => $this->instancedata->id,
]);
}
/**
* Load communication instance by id.
*
* @param int $id The communication instance id
* @return processor|null
*/
public static function load_by_id(int $id): ?self {
global $DB;
if ($record = $DB->get_record('communication', ['id' => $id])) {
return new self($record);
}
return null;
}
/**
* Load communication instance by instance id.
*
* @param string $component The component name
* @param string $instancetype The instance type
* @param int $instanceid The instance id
* @return processor|null
*/
public static function load_by_instance(
string $component,
string $instancetype,
int $instanceid
): ?self {
global $DB;
$record = $DB->get_record('communication', [
'instanceid' => $instanceid,
'component' => $component,
'instancetype' => $instancetype,
]);
if ($record) {
return new self($record);
}
return null;
}
/**
* Check if communication instance is active.
*
* @return bool
*/
public function is_instance_active(): bool {
return $this->instancedata->active;
}
/**
* Get communication provider class name.
*
* @param string $component The component name.
* @return string
*/
private function get_classname_for_provider(string $component): string {
return "{$component}\\communication_feature";
}
/**
* Get communication instance id after creating the instance in communication table.
*
* @return int
*/
public function get_id(): int {
return $this->instancedata->id;
}
/**
* Get communication instance id.
*
* @return string
*/
public function get_component(): string {
return $this->instancedata->component;
}
/**
* Get communication provider.
*
* @return string|null
*/
public function get_provider(): ?string {
// var_dump($this->instancedata);die;
if ((int)$this->instancedata->active === self::PROVIDER_ACTIVE) {
return $this->instancedata->provider;
}
return self::PROVIDER_NONE;
}
/**
* Get room name.
*
* @return string|null
*/
public function get_room_name(): ?string {
return $this->instancedata->roomname;
}
/**
* Get communication instance id.
*
* @return room_chat_provider
*/
public function get_room_provider(): room_chat_provider {
$this->require_api_enabled();
$this->require_room_features();
return $this->provider;
}
/**
* Get communication instance id.
*
* @return user_provider
*/
public function get_user_provider(): user_provider {
$this->require_api_enabled();
$this->require_user_features();
return $this->provider;
}
/**
* Get communication instance id.
*
* @return room_user_provider
*/
public function get_room_user_provider(): room_user_provider {
$this->require_api_enabled();
$this->require_room_features();
$this->require_room_user_features();
return $this->provider;
}
/**
* Get communication instance id.
*
* @return bool
*/
public function supports_user_features(): bool {
return ($this->provider instanceof user_provider);
}
/**
* Get communication instance id.
*
* @return bool
*/
public function supports_room_user_features(): bool {
if (!$this->supports_user_features()) {
return false;
}
if (!$this->supports_room_features()) {
return false;
}
return ($this->provider instanceof room_user_provider);
}
/**
* Get communication instance id.
*/
public function require_user_features(): void {
if (!$this->supports_user_features()) {
throw new \coding_exception('User features are not supported by the provider');
}
}
/**
* Get communication instance id.
*
* @return bool
*/
public function supports_room_features(): bool {
return ($this->provider instanceof room_chat_provider);
}
/**
* Check if communication api is enabled.
*/
public function require_api_enabled(): void {
if (!api::is_available()) {
throw new \coding_exception('Communication API is not enabled, please enable it from experimental features');
}
}
/**
* Get communication instance id.
*/
public function require_room_features(): void {
if (!$this->supports_room_features()) {
throw new \coding_exception('room features are not supported by the provider');
}
}
/**
* Get communication instance id.
*/
public function require_room_user_features(): void {
if (!$this->supports_room_user_features()) {
throw new \coding_exception('room features are not supported by the provider');
}
}
/**
* Get communication instance id.
*
* @return bool|\stored_file
*/
public function get_avatar(): ?stored_file {
$fs = get_file_storage();
$file = $fs->get_file(
(\context_system::instance())->id,
'core_communication',
'avatar',
$this->instancedata->id,
'/',
$this->instancedata->avatarfilename,
);
return $file ? $file : null;
}
/**
* Get a room url.
*
* @return string|null
*/
public function get_room_url(): ?string {
if ($this->provider && $this->is_instance_active()) {
return $this->get_room_provider()->get_chat_room_url();
}
return null;
}
}
@@ -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_communication;
/**
* Class communication_room_base to manage the room operations of communication providers.
*
* Every plugin that supports room operation must implement/extend this class in the plugin.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface room_chat_provider {
/**
* Create a provider room when a instance is created.
*/
public function create_chat_room(): bool;
/**
* Update a provider room when a instance is updated.
*/
public function update_chat_room(): bool;
/**
* Delete a provider room when a instance is deleted.
*/
public function delete_chat_room(): bool;
/**
* Generate a room url if there is a room.
*
* @return string|null
*/
public function get_chat_room_url(): ?string;
}
@@ -0,0 +1,40 @@
<?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_communication;
/**
* Class communication_user_base to manage communication provider users.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface room_user_provider {
/**
* Add members to communication room.
*
* @param array $userids The user ids to be added
*/
public function add_members_to_room(array $userids): void;
/**
* Remove members from room.
*
* @param array $userids The user ids to be removed
*/
public function remove_members_from_room(array $userids): void;
}
@@ -0,0 +1,64 @@
<?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_communication\task;
use core\task\adhoc_task;
use core_communication\processor;
/**
* Class add_members_to_room_task to add the task to add members to the room and execute the task to action the addition.
*
* @package core_communication
* @copyright 2023 David Woloszyn <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class add_members_to_room_task extends adhoc_task {
public function execute() {
// Initialize the custom data operation to be used for the action.
$data = $this->get_custom_data();
// Call the communication api to action the operation.
$communication = processor::load_by_id($data->id);
if ($communication === null) {
mtrace("Skipping room creation because the instance does not exist");
return;
}
$communication->get_room_user_provider()->add_members_to_room($communication->get_instance_userids());
}
/**
* Queue the task for the next run.
*
* @param processor $communication The communication processor to perform the action on
*/
public static function queue(
processor $communication
): void {
// Add ad-hoc task to update the provider room.
$task = new self();
$task->set_custom_data([
'id' => $communication->get_id()
]);
// Queue the task for the next run.
\core\task\manager::queue_adhoc_task($task);
}
}
@@ -0,0 +1,76 @@
<?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_communication\task;
use core\task\adhoc_task;
use core_communication\processor;
/**
* Class create_and_configure_room_task to add a task to create a room and execute the task to action the creation.
*
* this task will be queued by the communication api and will use the communication handler api to action the creation.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class create_and_configure_room_task extends adhoc_task {
public function execute() {
$data = $this->get_custom_data();
// Call the communication api to action the operation.
$communication = processor::load_by_id($data->id);
if ($communication === null) {
mtrace("Skipping room creation because the instance does not exist");
return;
}
if (!$communication->is_instance_active()) {
mtrace("Skipping room creation because the instance is not active");
return;
}
// If the room is created successfully, add members to the room.
if ($communication->get_room_provider()->create_chat_room()) {
add_members_to_room_task::queue(
$communication
);
}
}
/**
* Queue the task for the next run.
*
* @param processor $communication The communication processor to perform the action on
*/
public static function queue(
processor $communication,
): void {
// Add ad-hoc task to update the provider room.
$task = new self();
$task->set_custom_data([
'id' => $communication->get_id()
]);
// Queue the task for the next run.
\core\task\manager::queue_adhoc_task($task);
}
}
@@ -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/>.
namespace core_communication\task;
use core\task\adhoc_task;
use core_communication\processor;
/**
* Class delete_room_task to add a task to delete a room and execute the task to action the deletion.
*
* this task will be queued by the communication api and will use the communication handler api to action the deletion.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class delete_room_task extends adhoc_task {
public function execute() {
$data = $this->get_custom_data();
$communication = processor::load_by_id($data->id);
if ($communication === null) {
mtrace("Skipping room creation because the instance does not exist");
return;
}
// First remove the members from the room.
$communication->get_room_user_provider()->remove_members_from_room($communication->get_instance_userids(true, true));
// Now remove any mapping for users who are not in the room.
$communication->delete_instance_non_synced_user_mapping($communication->get_instance_userids(false, true));
// Now delete the room.
if ($communication->get_room_provider()->delete_chat_room()) {
$communication->delete_instance();
}
}
/**
* Queue the task for the next run.
*
* @param processor $communication The communication processor to perform the action on
*/
public static function queue(
processor $communication,
): void {
// Add ad-hoc task to update the provider room.
$task = new self();
$task->set_custom_data([
'id' => $communication->get_id()
]);
// Queue the task for the next run.
\core\task\manager::queue_adhoc_task($task);
}
}
@@ -0,0 +1,67 @@
<?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_communication\task;
use core\task\adhoc_task;
use core_communication\processor;
/**
* Class remove_members_from_room to add the task to remove members to the room and execute the task to action the removal.
*
* @package core_communication
* @copyright 2023 David Woloszyn <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class remove_members_from_room extends adhoc_task {
public function execute() {
// Initialize the custom data operation to be used for the action.
$data = $this->get_custom_data();
// Call the communication api to action the operation.
$communication = processor::load_by_id($data->id);
if ($communication === null) {
mtrace("Skipping room creation because the instance does not exist");
return;
}
$communication->get_room_user_provider()->remove_members_from_room($communication->get_instance_userids(true, true));
// Now remove any mapping for users who are not in the room.
$communication->delete_instance_non_synced_user_mapping($communication->get_instance_userids(false, true));
}
/**
* Queue the task for the next run.
*
* @param processor $communication The communication processor to perform the action on
*/
public static function queue(
processor $communication
): void {
// Add ad-hoc task to update the provider room.
$task = new self();
$task->set_custom_data([
'id' => $communication->get_id()
]);
// Queue the task for the next run.
\core\task\manager::queue_adhoc_task($task);
}
}
@@ -0,0 +1,65 @@
<?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_communication\task;
use core\task\adhoc_task;
use core_communication\processor;
/**
* Class update_room_task to add a task to update a room and execute the task to action the update.
*
* this task will be queued by the communication api and will use the communication handler api to action the updates.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class update_room_task extends adhoc_task {
public function execute() {
$data = $this->get_custom_data();
// Call the communication api to action the operation.
$communication = processor::load_by_id($data->id);
if ($communication === null) {
mtrace("Skipping room creation because the instance does not exist");
return;
}
$communication->get_room_provider()->update_chat_room();
}
/**
* Queue the task for the next run.
*
* @param processor $communication The communication processor to perform the action on
*/
public static function queue(
processor $communication,
): void {
// Add ad-hoc task to update the provider room.
$task = new self();
$task->set_custom_data([
'id' => $communication->get_id()
]);
// Queue the task for the next run.
\core\task\manager::queue_adhoc_task($task);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?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_communication;
/**
* Class communication_user_base to manage communication provider users.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface user_provider {
/**
* Create members.
*
* @param array $userid The users ids to be created
*/
public function create_members(array $userid): void;
}
+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/>.
/**
* Callback and library methods for core communication.
*
* @package core_communication
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Serve the files from the core_communication file areas.
*
* @param stdClass $course the course object
* @param stdClass $cm the course module object
* @param context $context the context
* @param string $filearea the name of the file area
* @param array $args extra arguments (itemid, path)
* @param bool $forcedownload whether force download
* @param array $options additional options affecting the file serving
*/
function core_communication_pluginfile(
$course,
$cm,
$context,
$filearea,
$args,
$forcedownload,
array $options = []
): void {
if ($filearea !== 'avatar') {
return;
}
$itemid = array_shift($args);
$filename = array_pop($args);
// Retrieve the file from the Files API.
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'core_communication', $filearea, $itemid, '/', $filename);
if (!$file) {
return;
}
send_file($file, $filename);
}
@@ -0,0 +1,316 @@
<?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 communication_matrix;
use core_communication\processor;
/**
* class communication_feature to handle matrix specific actions.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class communication_feature implements
\core_communication\communication_provider,
\core_communication\user_provider,
\core_communication\room_chat_provider,
\core_communication\room_user_provider {
/** @var matrix_events_manager $eventmanager The event manager object to get the endpoints */
private matrix_events_manager $eventmanager;
/** @var matrix_rooms $matrixrooms The matrix room object to update room information */
private matrix_rooms $matrixrooms;
/**
* Load the communication provider for the communication api.
*
* @param processor $communication The communication processor object
* @return communication_feature The communication provider object
*/
public static function load_for_instance(processor $communication): self {
return new self($communication);
}
/**
* Constructor for communication provider to initialize necessary objects for api cals etc..
*
* @param processor $communication The communication processor object
*/
private function __construct(
private \core_communication\processor $communication,
) {
$this->matrixrooms = new matrix_rooms($communication->get_id());
$this->eventmanager = new matrix_events_manager($this->matrixrooms->get_matrix_room_id());
}
/**
* Create members.
*
* @param array $userids The Moodle user ids to create
*/
public function create_members(array $userids): void {
$addedmembers = [];
foreach ($userids as $userid) {
$user = \core_user::get_user($userid);
$userfullname = fullname($user);
// Proceed if we have a user's full name and email to work with.
if (!empty($user->email) && !empty($userfullname)) {
$json = [
'displayname' => $userfullname,
'threepids' => [(object)[
'medium' => 'email',
'address' => $user->email
]],
'external_ids' => []
];
list($qualifiedmuid, $pureusername) = matrix_user_manager::set_qualified_matrix_user_id(
$userid,
$this->eventmanager->matrixhomeserverurl
);
// First create user in matrix.
$response = $this->eventmanager->request($json)->put($this->eventmanager->get_create_user_endpoint($qualifiedmuid));
$response = json_decode($response->getBody());
if (!empty($matrixuserid = $response->name)) {
// Then create matrix user id in moodle.
matrix_user_manager::add_user_matrix_id_to_moodle($userid, $pureusername);
if ($this->add_registered_matrix_user_to_room($matrixuserid)) {
$addedmembers[] = $userid;
}
}
}
}
// Mark then users as synced for the added members.
$this->communication->mark_users_as_synced($addedmembers);
}
/**
* Add members to a room.
*
* @param array $userids The user ids to add
*/
public function add_members_to_room(array $userids): void {
$unregisteredmembers = [];
$addedmembers = [];
foreach ($userids as $userid) {
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle(
$userid,
$this->eventmanager->matrixhomeserverurl
);
if ($matrixuserid && $this->check_user_exists($matrixuserid)) {
if ($this->add_registered_matrix_user_to_room($matrixuserid)) {
$addedmembers[] = $userid;
}
} else {
$unregisteredmembers[] = $userid;
}
}
// Mark then users as synced for the added members.
$this->communication->mark_users_as_synced($addedmembers);
// Create Matrix users.
if (count($unregisteredmembers) > 0) {
$this->create_members($unregisteredmembers);
}
}
/**
* Adds the registered matrix user id to room.
*
* @param string $matrixuserid Registered matrix user id
*/
private function add_registered_matrix_user_to_room(string $matrixuserid): bool {
if (!$this->check_room_membership($matrixuserid)) {
$json = ['user_id' => $matrixuserid];
$headers = ['Content-Type' => 'application/json'];
$response = $this->eventmanager->request(
$json,
$headers
)->post(
$this->eventmanager->get_room_membership_join_endpoint()
);
$response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
if (!empty($roomid = $response->room_id) && $roomid === $this->eventmanager->roomid) {
return true;
}
}
return false;
}
/**
* Remove members from a room.
*
* @param array $userids The Moodle user ids to remove
*/
public function remove_members_from_room(array $userids): void {
$membersremoved = [];
foreach ($userids as $userid) {
// Check user is member of room first.
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle(
$userid,
$this->eventmanager->matrixhomeserverurl
);
// Check if user is the room admin and halt removal of this user.
$matrixroomdata = $this->eventmanager->request()->get($this->eventmanager->get_room_info_endpoint());
$matrixroomdata = json_decode($matrixroomdata->getBody(), false, 512, JSON_THROW_ON_ERROR);
$roomadmin = $matrixroomdata->creator;
$isadmin = $matrixuserid === $roomadmin;
if (
!$isadmin && $matrixuserid && $this->check_user_exists($matrixuserid) &&
$this->check_room_membership($matrixuserid)
) {
$json = ['user_id' => $matrixuserid];
$headers = ['Content-Type' => 'application/json'];
$this->eventmanager->request(
$json,
$headers
)->post(
$this->eventmanager->get_room_membership_kick_endpoint()
);
$membersremoved[] = $userid;
}
}
$this->communication->delete_instance_user_mapping($membersremoved);
}
/**
* Check if a user exists in Matrix.
* Use if user existence is needed before doing something else.
*
* @param string $matrixuserid The Matrix user id to check
* @return bool
*/
public function check_user_exists(string $matrixuserid): bool {
$response = $this->eventmanager->request([], [], false)->get($this->eventmanager->get_user_info_endpoint($matrixuserid));
$response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
return isset($response->name);
}
/**
* Check if a user is a member of a room.
* Use if membership confirmation is needed before doing something else.
*
* @param string $matrixuserid The Matrix user id to check
* @return bool
*/
public function check_room_membership(string $matrixuserid): bool {
$response = $this->eventmanager->request([], [], false)->get($this->eventmanager->get_room_membership_joined_endpoint());
$response = json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);
// Check user id is in the returned room member ids.
return isset($response['joined']) && array_key_exists($matrixuserid, $response['joined']);
}
public function create_chat_room(): bool {
if ($this->matrixrooms->room_record_exists()) {
return $this->update_chat_room();
}
// Create a new room.
$json = [
'name' => $this->communication->get_room_name(),
'visibility' => 'private',
'preset' => 'private_chat',
'initial_state' => [],
];
$response = $this->eventmanager->request($json)->post($this->eventmanager->get_create_room_endpoint());
$response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
// Check if room was created.
if (!empty($roomid = $response->room_id)) {
$this->matrixrooms->create_matrix_room_record($this->communication->get_id(), $roomid);
$this->eventmanager->roomid = $roomid;
$this->update_room_avatar();
return true;
}
return false;
}
public function update_chat_room(): bool {
if (!$this->matrixrooms->room_record_exists()) {
return $this->create_chat_room();
}
// Get room data.
$matrixroomdata = $this->eventmanager->request()->get($this->eventmanager->get_room_info_endpoint());
$matrixroomdata = json_decode($matrixroomdata->getBody(), false, 512, JSON_THROW_ON_ERROR);
// Update the room name when it's updated from the form.
if ($matrixroomdata->name !== $this->communication->get_room_name()) {
$json = ['name' => $this->communication->get_room_name()];
$this->eventmanager->request($json)->put($this->eventmanager->get_update_room_name_endpoint());
}
// Update room avatar.
$this->update_room_avatar();
return true;
}
public function delete_chat_room(): bool {
return $this->matrixrooms->delete_matrix_room_record();
}
/**
* Update the room avatar when an instance image is added or updated.
*/
public function update_room_avatar(): void {
$instanceimage = $this->communication->get_avatar();
$contenturi = null;
// If avatar is set for the instance, update in matrix.
if (!empty($instanceimage)) {
// First upload the content.
$contenturi = $this->eventmanager->upload_matrix_content($instanceimage->get_content());
}
// Now update the room avatar.
$json = [
'url' => $contenturi,
];
$this->eventmanager->request($json, [], false)->put($this->eventmanager->get_update_avatar_endpoint());
}
public function get_chat_room_url(): ?string {
// Check for room record in Moodle and that it exists in Matrix.
if (!$this->matrixrooms->room_record_exists()) {
return null;
}
return $this->eventmanager->matrixwebclienturl . '#/room/' . $this->matrixrooms->get_matrix_room_id();
}
}
@@ -0,0 +1,246 @@
<?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 communication_matrix;
use core\http_client;
use GuzzleHttp\Psr7\Request;
/**
* Class matrix_endpoint_manager to manage the api endpoints of matrix provider.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class matrix_events_manager {
/**
* @var string|false|mixed|object $matrixhomeserverurl The URL of the home server
*/
public string $matrixhomeserverurl;
/**
* @var string $matrixwebclienturl The URL of the web client
*/
public string $matrixwebclienturl;
/**
* @var string|false|mixed|object $matrixaccesstoken The access token of the matrix server
*/
private string $matrixaccesstoken;
/**
* @var string $roomid The id of the room from matrix server
*/
public string $roomid;
/**
* Matrix events constructor to get the room id and refresh token usage if required.
*
* @param string|null $roomid The id of the room from matrix server
*/
public function __construct(?string $roomid = null) {
if (!empty($roomid)) {
$this->roomid = $roomid;
}
$this->matrixhomeserverurl = get_config('communication_matrix', 'matrixhomeserverurl');
$this->matrixaccesstoken = get_config('communication_matrix', 'matrixaccesstoken');
$this->matrixwebclienturl = get_config('communication_matrix', 'matrixelementurl');
}
/**
* Get the current token in use.
*
* @return string
*/
public function get_token(): string {
return $this->matrixaccesstoken;
}
/**
* Get the matrix api endpoint for creating a new room.
*
* @return string
*/
public function get_create_room_endpoint(): string {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/createRoom';
}
/**
* Get the matrix api endpoint for updating the room topic.
*
* @return string
*/
public function get_update_room_topic_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($this->roomid) . '/' . 'state/m.room.topic/';
}
}
/**
* Get the matrix api endpoint for updating room name.
*
* @return string
*/
public function get_update_room_name_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($this->roomid) . '/' . 'state/m.room.name/';
}
}
/**
* Get matrix api endpoint for getting room information.
*
* @return string
*/
public function get_room_info_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/_synapse/admin/v1/rooms/' . urlencode($this->roomid);
}
}
/**
* Get delete room endpoint.
*
* @return string
*/
public function get_delete_room_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_synapse/admin/v1/rooms/' . urlencode($this->roomid);
}
}
/**
* Get the matrix api endpoint for uploading a content to synapse server.
*/
public function get_upload_content_endpoint(): string {
return $this->matrixhomeserverurl . '/' . '_matrix/media/r0/upload/';
}
/**
* Get the matrix api endpoint for updating room avatar.
*
* @return string
*/
public function get_update_avatar_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($this->roomid) . '/' . 'state/m.room.avatar/';
}
}
/**
* Get the members of a room. Useful when performing actions where member needs to exist first.
*
* @return string
*/
public function get_room_membership_joined_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($this->roomid) . '/' . 'joined_members';
}
}
/**
* Get the 'join' room membership endpoint. This adds users to a room.
*
* @return string
*/
public function get_room_membership_join_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_synapse/admin/v1/join' . '/' . urlencode($this->roomid);
}
}
/**
* Get the 'kick' room membership endpoint. This removes users from a room.
*
* @return string
*/
public function get_room_membership_kick_endpoint(): string {
if (!empty($this->roomid)) {
return $this->matrixhomeserverurl . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($this->roomid) . '/' . 'kick';
}
}
/**
* Get the matrix api endpoint for creating a new user.
*
* @param string $matrixuserid Matrix user id
* @return string
*/
public function get_create_user_endpoint(string $matrixuserid): string {
return $this->matrixhomeserverurl . '/' . '_synapse/admin/v2/users/' . urlencode($matrixuserid);
}
/**
* Get the matrix api endpoint for creating a new user.
*
* @param string $matrixuserid Matrix user id
* @return string
*/
public function get_user_info_endpoint(string $matrixuserid): string {
return $this->matrixhomeserverurl . '/' . '_synapse/admin/v2/users/' . urlencode($matrixuserid);
}
/**
* The http request for the api call.
*
* @param array $jsonarray The array of json
* @param array $headers The array of headers
* @param bool $httperror Enable or disable http error from response
* @return \core\http_client
*/
public function request(array $jsonarray = [], array $headers = [], bool $httperror = true): \core\http_client {
$header = ['Authorization' => 'Bearer ' . $this->get_token()];
$headers = array_merge($header, $headers);
$response = new \core\http_client([
'http_errors' => $httperror,
'headers' => $headers,
'json' => $jsonarray,
]);
return $response;
}
/**
* Upload the content in the matrix/synapse server.
*
* @param string $content The content to be uploaded
* @return string|false
*/
public function upload_matrix_content(string $content): bool|string {
$headers = [
'Authorization' => 'Bearer ' . $this->get_token(),
'Content-Type' => 'image/png'
];
$client = new http_client();
$request = new Request('POST', $this->get_upload_content_endpoint(), $headers, $content);
$response = $client->send($request);
$response = json_decode($response->getBody());
if ($response) {
return $response->content_uri;
}
return false;
}
}
@@ -0,0 +1,116 @@
<?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 communication_matrix;
/**
* Class matrix_rooms to manage the updates to the room information in db.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class matrix_rooms {
/**
* @var \stdClass|null $matrixroomrecord The matrix room record from db
*/
private ?\stdClass $matrixroomrecord = null;
/**
* Matrix rooms constructor to load the matrix room information from matrix_rooms table.
*
* @param int $commid The id of the communication record
*/
public function __construct(int $commid) {
$this->load_matrix_room_data($commid);
}
/**
* Get the matrix room data from database. Either get the data object or return false if no data found.
*
* @param int $commid The id of the communication record
*/
public function load_matrix_room_data(int $commid): void {
global $DB;
if ($record = $DB->get_record('matrix_rooms', ['commid' => $commid])) {
$this->matrixroomrecord = $record;
}
}
/**
* Create matrix room data.
*
* @param int $commid The id of the communication record
* @param string $roomid The id of the room from matrix
*/
public function create_matrix_room_record(int $commid, string $roomid): void {
global $DB;
$roomrecord = new \stdClass();
$roomrecord->commid = $commid;
$roomrecord->roomid = $roomid;
$roomrecord->id = $DB->insert_record('matrix_rooms', $roomrecord);
$this->matrixroomrecord = $roomrecord;
}
/**
* Update matrix room data.
*
* @param string $roomid The id of the room from matrix
*/
public function update_matrix_room_record(string $roomid): void {
global $DB;
if ($this->room_record_exists()) {
$this->matrixroomrecord->roomid = $roomid;
$DB->update_record('matrix_rooms', $this->matrixroomrecord);
}
}
/**
* Delete matrix room data.
*
* @return bool
*/
public function delete_matrix_room_record(): bool {
global $DB;
if ($this->room_record_exists()) {
return $DB->delete_records('matrix_rooms', ['commid' => $this->matrixroomrecord->commid]);
}
return false;
}
/**
* Get the matrix room id.
*
* @return string|null
*/
public function get_matrix_room_id(): ?string {
if ($this->room_record_exists()) {
return $this->matrixroomrecord->roomid;
}
return null;
}
/**
* Check if room record exist for matrix.
*
* @return bool
*/
public function room_record_exists(): bool {
return (bool) $this->matrixroomrecord;
}
}
@@ -0,0 +1,186 @@
<?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 communication_matrix;
/**
* class matrix_user_manager to handle specific actions.
*
* @package communication_matrix
* @copyright 2023 Stevani Andolo <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class matrix_user_manager {
/**
* Gets matrix user id from moodle.
*
* @param string $userid Moodle user id
* @param string $homeserver Matrix home server url
* @return string|null
*/
public static function get_matrixid_from_moodle(
string $userid,
string $homeserver
) : ?string {
global $CFG;
require_once("$CFG->dirroot/user/profile/lib.php");
$matrixprofilefield = get_config('communication_matrix', 'matrixuserid_field');
if (!$matrixprofilefield) {
$matrixprofilefield = self::create_matrix_user_profile_fields();
}
$field = profile_user_record($userid);
$pureusername = $field->{$matrixprofilefield} ?? null;
if ($pureusername) {
$homeserver = self::set_matrix_home_server($homeserver);
return "@{$pureusername}:$homeserver";
}
return $pureusername;
}
/**
* Sets qualified matrix user id
*
* @param string $userid Moodle user id
* @param string $homeserver Matrix home server url
* @return array
*/
public static function set_qualified_matrix_user_id(
string $userid,
string $homeserver
) : array {
$user = \core_user::get_user($userid);
$username = preg_replace('/[@#$%^&*()+{}|<>?!,]/i', '.', $user->username);
$username = ltrim(rtrim($username, '.'), '.');
$homeserver = self::set_matrix_home_server($homeserver);
return ["@{$username}:{$homeserver}", $username];
}
/**
* Add user's Matrix user id.
*
* @param string $userid Moodle user id
* @param string $matrixuserid Matrix user id
* @return bool
*/
public static function add_user_matrix_id_to_moodle(
string $userid,
string $matrixuserid
): bool {
global $CFG;
require_once("$CFG->dirroot/user/profile/lib.php");
$matrixprofilefield = get_config('communication_matrix', 'matrixuserid_field');
$field = profile_get_custom_field_data_by_shortname($matrixprofilefield);
if ($field !== null) {
$userinfodata = new \stdClass();
$userinfodata->id = $userid;
$userinfodata->data = $matrixuserid;
$userinfodata->fieldid = $field->id;
$userinfodata->{"profile_field_{$matrixprofilefield}"} = $matrixuserid;
profile_save_data($userinfodata);
return true;
}
return false;
}
/**
* Sets home server for user matrix id
*
* @param string $homeserver Matrix home server url
* @return string
*/
public static function set_matrix_home_server(string $homeserver) : string {
$homeserver = parse_url($homeserver)['host'];
if (strpos($homeserver, '.') !== false) {
$host = explode('.', $homeserver);
return strpos($homeserver, 'www') !== false ? $host[1] : $host[0];
}
return $homeserver;
}
/**
* Insert "Communication" category and "matrixuserid" field.
*
* @return string
*/
public static function create_matrix_user_profile_fields(): string {
global $CFG, $DB;
require_once($CFG->dirroot . '/user/profile/definelib.php');
require_once($CFG->dirroot . '/user/profile/field/text/define.class.php');
// Check if communication category exists.
$categoryname = get_string('communication', 'core_communication');
$category = $DB->count_records('user_info_category', ['name' => $categoryname]);
if ($category < 1) {
$data = new \stdClass();
$data->sortorder = $DB->count_records('user_info_category') + 1;
$data->name = $categoryname;
$data->id = $DB->insert_record('user_info_category', $data);
$createdcategory = $DB->get_record('user_info_category', ['id' => $data->id]);
$categoryid = $createdcategory->id;
\core\event\user_info_category_created::create_from_category($createdcategory)->trigger();
} else {
$category = $DB->get_record('user_info_category', ['name' => $categoryname]);
$categoryid = $category->id;
}
set_config('communication_category_field', $categoryname, 'core_communication');
// Check if matrixuserid exists in user_info_field table.
$matrixuserid = $DB->count_records('user_info_field', [
'shortname' => 'matrixuserid',
'categoryid' => $categoryid
]);
if ($matrixuserid < 1) {
$profileclass = new \profile_define_text();
$data = (object) [
'shortname' => 'matrixuserid',
'name' => get_string('matrixuserid', 'communication_matrix'),
'datatype' => 'text',
'description' => get_string('matrixuserid_desc', 'communication_matrix'),
'descriptionformat' => 1,
'categoryid' => $categoryid,
'forceunique' => 1,
'visible' => 0,
'locked' => 1,
'param1' => 30,
'param2' => 2048
];
$profileclass->define_save($data);
set_config('matrixuserid_field', 'matrixuserid', 'communication_matrix');
return 'matrixuserid';
}
}
}
@@ -0,0 +1,39 @@
<?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 communication_matrix\privacy;
use core_privacy\local\metadata\null_provider;
/**
* Privacy Subsystem for communication_matrix implementing null_provider.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="communication/provider/matrix/db" VERSION="2023011900" COMMENT="Stores the matrix room information associated with the communication instance."
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../lib/xmldb/xmldb.xsd"
>
<TABLES>
<TABLE NAME="matrix_rooms" COMMENT="Stores the matrix room information associated with the communication instance.">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="commid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="ID of the communication record"/>
<FIELD NAME="roomid" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false" COMMENT="ID of the matrix room instance"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="fk_commid" TYPE="foreign" FIELDS="commid" REFTABLE="communication" REFFIELDS="id" COMMENT="Foreign key for communication reference"/>
</KEYS>
</TABLE>
</TABLES>
</XMLDB>
@@ -0,0 +1,36 @@
<?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/>.
/**
* Strings for component communication_matrix, language 'en'.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['matrixuserid'] = 'Matrix user ID';
$string['matrixuserid_desc'] = 'The user ID to be used for Matrix';
$string['matrixhomeserverurl'] = 'Home server URL';
$string['matrixhomeserverurl_desc'] = 'The URL of the Synapse home server to connect to, for user and room creation.';
$string['matrixaccesstoken'] = 'Access token';
$string['matrixaccesstoken_desc'] = 'Admin access token to authenticate against the Synapse Home server.';
$string['matrixrefreshtoken'] = 'Refresh token';
$string['matrixrefreshtoken_desc'] = 'Admin refresh token to associated with the access token.';
$string['matrixelementurl'] = 'Element web URL';
$string['matrixelementurl_desc'] = 'The URL to Element Web instance.';
$string['pluginname'] = 'Matrix';
$string['privacy:metadata'] = 'Matrix communication plugin does not store any personal data.';
@@ -0,0 +1,47 @@
<?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/>.
/**
* Matrix communication plugin settings.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($hassiteconfig) {
// Home server URL.
$name = new lang_string('matrixhomeserverurl', 'communication_matrix');
$desc = new lang_string('matrixhomeserverurl_desc', 'communication_matrix');
$settings->add(new admin_setting_requiredtext('communication_matrix/matrixhomeserverurl', $name, $desc, ''));
// Access token.
$name = new lang_string('matrixaccesstoken', 'communication_matrix');
$desc = new lang_string('matrixaccesstoken_desc', 'communication_matrix');
$settings->add(new admin_setting_requiredpasswordunmask('communication_matrix/matrixaccesstoken', $name, $desc, ''));
// Refresh token.
$name = new lang_string('matrixrefreshtoken', 'communication_matrix');
$desc = new lang_string('matrixrefreshtoken_desc', 'communication_matrix');
$settings->add(new admin_setting_requiredpasswordunmask('communication_matrix/matrixrefreshtoken', $name, $desc, ''));
// Element web URL.
$name = new lang_string('matrixelementurl', 'communication_matrix');
$desc = new lang_string('matrixelementurl_desc', 'communication_matrix');
$settings->add(new admin_setting_requiredtext('communication_matrix/matrixelementurl', $name, $desc, ''));
}
@@ -0,0 +1,65 @@
<?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/>.
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use communication_matrix\matrix_test_helper_trait;
use Moodle\BehatExtension\Exception\SkippedException;
require_once(__DIR__ . '/../matrix_test_helper_trait.php');
require_once(__DIR__ . '/../../../../../lib/behat/behat_base.php');
require_once(__DIR__ . '/../../../../tests/communication_test_helper_trait.php');
/**
* Class behat_communication_matrix for behat custom steps and configuration for matrix.
*
* @package communication_matrix
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class behat_communication_matrix extends \behat_base {
use \core_communication\communication_test_helper_trait;
use matrix_test_helper_trait;
/**
* BeforeScenario hook to reset the mock server.
*
* @BeforeScenario @communication_matrix
*
* @param BeforeScenarioScope $scope
*/
public function before_scenario(BeforeScenarioScope $scope) {
if (defined('TEST_COMMUNICATION_MATRIX_MOCK_SERVER')) {
$this->reset_mock();
}
}
/**
* Setup and configure and mock server for matrix.
*
* @Given /^a Matrix mock server is configured$/
*/
public function initialize_mock_server(): void {
if (!defined('TEST_COMMUNICATION_MATRIX_MOCK_SERVER')) {
throw new SkippedException(
'The TEST_COMMUNICATION_MATRIX_MOCK_SERVER constant must be defined to run communication_matrix tests'
);
}
$this->setup_communication_configs();
$this->initialise_mock_configs();
}
}
@@ -0,0 +1,48 @@
@communication @communication_matrix @javascript
Feature: Communication matrix
Access the Matrix room using the link provided
As a student or a teacher
Background: Make sure the mock server is initialized and a course is created
Given a Matrix mock server is configured
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | 1 | teacher1@example.com |
| student1 | Student | 1 | student1@example.com |
And the following "courses" exist:
| fullname | shortname | category | selectedcommunication | communicationroomname |
| Test course | Test course | 0 | communication_matrix | matrixroom |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | Test course | editingteacher |
| student1 | Test course | student |
And I run all adhoc tasks
Scenario: I can access the matrix room using the room link icon as a teacher
Given I am on the "Test course" "Course" page logged in as "teacher1"
Then ".btn-footer-communication" "css_element" should be visible
And I change window size to "mobile"
Then ".btn-footer-communication" "css_element" should not be visible
# You should not be able to see the following line unless you are in Mobile view.
# Behat is currently setup to always show footer links.
And ".footer-link-communication" "css_element" should be visible
Scenario: I can access the matrix room using the room link icon as a student
Given I am on the "Test course" "Course" page logged in as "student1"
Then ".btn-footer-communication" "css_element" should be visible
And I change window size to "mobile"
Then ".btn-footer-communication" "css_element" should not be visible
# You should not be able to see the following line unless you are in Mobile view.
# Behat is currently setup to always show footer links.
And ".footer-link-communication" "css_element" should be visible
Scenario: I cannot see the matrix room link when communication provider is disabled
Given I am on the "Test course" "Course editing" page logged in as "teacher1"
And I set the following fields to these values:
| selectedcommunication | none |
And I press "Save and display"
And I run all adhoc tasks
And I reload the page
Then ".btn-footer-communication" "css_element" should not be visible
And I change window size to "mobile"
And ".footer-link-communication" "css_element" should not be visible
@@ -0,0 +1,324 @@
<?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 communication_matrix;
use core_communication\processor;
use core_communication\communication_test_helper_trait;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/matrix_test_helper_trait.php');
require_once(__DIR__ . '/../../../tests/communication_test_helper_trait.php');
/**
* Class communication_feature_test to test the matrix features implemented using the core interfaces.
*
* @package communication_matrix
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \communication_matrix\communication_feature
*/
class communication_feature_test extends \advanced_testcase {
use matrix_test_helper_trait;
use communication_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->resetAfterTest();
$this->setup_communication_configs();
$this->initialise_mock_server();
}
/**
* Test create or update chat room.
*
* @covers ::create_chat_room
* @covers ::update_chat_room
*/
public function test_create_or_update_chat_room() {
$course = $this->getDataGenerator()->create_course();
// Sameple test data.
$instanceid = $course->id;
$component = 'core_course';
$instancetype = 'coursecommunication';
$selectedcommunication = 'communication_matrix';
$communicationroomname = 'communicationroom';
$communicationprocessor = processor::create_instance(
$selectedcommunication,
$instanceid,
$component,
$instancetype,
$communicationroomname,
);
$communicationprocessor->get_room_provider()->create_chat_room();
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
// Test the response against the stored data.
$this->assertNotEmpty($matrixrooms->get_matrix_room_id());
// Add api call to get room data and test against set data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertEquals($matrixrooms->get_matrix_room_id(), $matrixroomdata->room_id);
$this->assertEquals($communicationprocessor->get_room_name(), $matrixroomdata->name);
$communicationroomname = 'communicationroomedited';
$communicationprocessor->update_instance($selectedcommunication, $communicationroomname);
$communicationprocessor->get_room_provider()->update_chat_room();
// Add api call to get room data and test against set data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertEquals($communicationprocessor->get_room_name(), $matrixroomdata->name);
}
/**
* Test delete chat room.
*
* @covers ::delete_chat_room
*/
public function test_delete_chat_room(): void {
$course = $this->getDataGenerator()->create_course();
// Sameple test data.
$instanceid = $course->id;
$component = 'core_course';
$instancetype = 'coursecommunication';
$selectedcommunication = 'communication_matrix';
$communicationroomname = 'communicationroom';
$communicationprocessor = processor::create_instance(
$selectedcommunication,
$instanceid,
$component,
$instancetype,
$communicationroomname,
);
$communicationprocessor->get_room_provider()->create_chat_room();
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$communicationprocessor->get_room_provider()->delete_chat_room();
// We are not deleting any matrix room, just deleting local record.
$matrixroomsafterdeletion = new matrix_rooms($communicationprocessor->get_id());
$this->assertFalse($matrixroomsafterdeletion->room_record_exists());
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertNotEmpty($matrixroomdata);
$this->assertEquals($communicationprocessor->get_room_name(), $matrixroomdata->name);
}
/**
* Test update room avatar.
*
* @covers ::update_room_avatar
*/
public function test_update_room_avatar(): void {
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room(
$selectedcommunication,
$communicationroomname,
$avatarurl
);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationprocessor->get_room_provider()->create_chat_room();
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
// Add api call to get room data and test against set data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertNotEmpty($matrixroomdata->avatar);
}
/**
* Test get chat room url.
*
* @covers ::get_chat_room_url
*/
public function test_get_chat_room_url(): void {
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room(
$selectedcommunication,
$communicationroomname,
$avatarurl
);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationprocessor->get_room_provider()->create_chat_room();
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$this->assertNotNull($communicationprocessor->get_room_provider()->get_chat_room_url());
$this->assertStringContainsString(
$matrixrooms->get_matrix_room_id(),
$communicationprocessor->get_room_provider()->get_chat_room_url()
);
}
/**
* Test create members.
*
* @covers ::create_members
* @covers ::add_registered_matrix_user_to_room
*/
public function test_create_members(): void {
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
$userid = $this->get_user()->id;
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room(
$selectedcommunication,
$communicationroomname,
$avatarurl
);
$communication->add_members_to_room([$userid]);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationprocessor->get_room_provider()->create_chat_room();
$communicationprocessor->get_room_provider()->add_members_to_room([$userid]);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
// Get created matrixuserid from moodle.
$elementserver = matrix_user_manager::set_matrix_home_server($eventmanager->matrixhomeserverurl);
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($userid, $eventmanager->matrixhomeserverurl);
$this->assertNotNull($matrixuserid);
$this->assertEquals("@sampleun:{$elementserver}", $matrixuserid);
// Add api call to get user data and test against set data.
$matrixuserdata = $this->get_matrix_user_data($matrixrooms->get_matrix_room_id(), $matrixuserid);
$this->assertNotEmpty($matrixuserdata);
$this->assertEquals("Samplefn Sampleln", $matrixuserdata->displayname);
}
/**
* Test add/remove members from room.
*
* @covers ::remove_members_from_room
* @covers ::add_members_to_room
* @covers ::add_registered_matrix_user_to_room
* @covers ::check_room_membership
*/
public function test_add_and_remove_members_from_room(): void {
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
$userid = $this->get_user()->id;
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room(
$selectedcommunication,
$communicationroomname,
$avatarurl
);
$communication->add_members_to_room([$userid]);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationprocessor->get_room_provider()->create_chat_room();
$communicationprocessor->get_room_provider()->add_members_to_room([$userid]);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
// Get created matrixuserid from moodle.
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($userid, $eventmanager->matrixhomeserverurl);
// Test user is a member of the room.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Remove member from matrix room.
$communicationprocessor->get_room_provider()->remove_members_from_room([$userid]);
// Test user is no longer a member of the room.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
}
@@ -0,0 +1,883 @@
<?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 communication_matrix;
use core_communication\processor;
use core_communication\communication_test_helper_trait;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/matrix_test_helper_trait.php');
require_once(__DIR__ . '/../../../tests/communication_test_helper_trait.php');
/**
* Class matrix_provider_test to test the matrix provider scenarios using the matrix endpoints.
*
* @package communication_matrix
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class matrix_communication_test extends \advanced_testcase {
use matrix_test_helper_trait;
use communication_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->resetAfterTest();
$this->setup_communication_configs();
$this->initialise_mock_server();
}
/**
* Test creating course with matrix provider creates all the associated data and matrix room.
*
* @covers \core_communication\api::create_and_configure_room
* @covers \core_communication\task\create_and_configure_room_task::execute
* @covers \core_communication\task\create_and_configure_room_task::queue
*/
public function test_create_course_with_matrix_provider(): void {
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
// Run the task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Initialize the matrix room object.
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
// Test against the data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertEquals($matrixrooms->get_matrix_room_id(), $matrixroomdata->room_id);
$this->assertEquals($roomname, $matrixroomdata->name);
}
/**
* Test update course with matrix provider.
*
* @covers \core_communication\api::update_room
* @covers \core_communication\task\update_room_task::execute
* @covers \core_communication\task\update_room_task::queue
*/
public function test_update_course_with_matrix_provider(): void {
global $CFG;
$course = $this->get_course();
// Run the task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Sample data.
$communicationroomname = 'Sampleroomupdated';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->update_room($selectedcommunication, $communicationroomname, $avatarurl);
// Run the task.
$this->runAdhocTasks('\core_communication\task\update_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Initialize the matrix room object.
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
// Test against the data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertEquals($matrixrooms->get_matrix_room_id(), $matrixroomdata->room_id);
$this->assertEquals($communicationroomname, $matrixroomdata->name);
$this->assertNotEmpty($matrixroomdata->avatar);
}
/**
* Test course delete with matrix provider.
*
* @covers \core_communication\api::delete_room
* @covers \core_communication\task\delete_room_task::execute
* @covers \core_communication\task\delete_room_task::queue
*/
public function test_delete_course_with_matrix_provider(): void {
global $DB;
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
// Run the task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationid = $communicationprocessor->get_id();
// Initialize the matrix room object.
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
// Test against the data.
$matrixroomdata = $this->get_matrix_room_data($matrixrooms->get_matrix_room_id());
$this->assertEquals($matrixrooms->get_matrix_room_id(), $matrixroomdata->room_id);
// Now delete the course.
delete_course($course, false);
// Run the task.
$this->runAdhocTasks('\core_communication\task\delete_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertNull($communicationprocessor);
// Initialize the matrix room object.
$matrixrooms = $DB->get_record('matrix_rooms', ['commid' => $communicationid]);
$this->assertEmpty($matrixrooms);
}
/**
* Test creating course with matrix provider creates all the associated data and matrix room.
*
* @covers \core_communication\api::add_members_to_room
* @covers \core_communication\task\add_members_to_room_task::execute
* @covers \core_communication\task\add_members_to_room_task::queue
*/
public function test_create_members_with_matrix_provider(): void {
$course = $this->get_course('Samplematrixroom', 'communication_matrix');
$user = $this->get_user('Samplefnmatrix', 'Samplelnmatrix', 'sampleunmatrix');
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$enrol->enrol_user(reset($enrolinstances), $user->id);
// Run user operation task.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
// Get matrix user id from moodle.
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $eventmanager->matrixhomeserverurl);
$this->assertNotNull($matrixuserid);
// Get matrix user id from matrix.
$matrixuserdata = $this->get_matrix_user_data($matrixrooms->get_matrix_room_id(), $matrixuserid);
$this->assertNotEmpty($matrixuserdata);
$this->assertEquals("Samplefnmatrix Samplelnmatrix", $matrixuserdata->displayname);
}
/**
* Test enrolment adds the user to a Matrix room.
*
* @covers \core_communication\api::add_members_to_room
* @covers \core_communication\task\add_members_to_room_task::execute
* @covers \core_communication\task\add_members_to_room_task::queue
*/
public function test_enrolling_user_adds_user_to_matrix_room(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolment removes the user from a Matrix room.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_unenrolling_user_removes_user_from_matrix_room(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Unenrol the user from the course.
$enrol->unenrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when their enrolment is suspended.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_suspending_enrolment(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Suspend user enrolment.
$enrol->update_user_enrol($instance, $user->id, 1);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when the instance is deleted.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_deleting_instance(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Delete instance.
$enrol->delete_instance($instance);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when the instance is disabled.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_disabling_instance(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Update enrolment communication.
$enrol->update_communication($instance->id, 'remove', $course->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users memerbship toggles correctly when an instance is disabled and reenabled again.
*
* @covers \core_communication\api::add_members_to_room
* @covers \core_communication\task\add_members_to_room_task::execute
* @covers \core_communication\task\add_members_to_room_task::queue
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_memerbship_toggles_when_disabling_and_reenabling_instance(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Update enrolment communication when updating instance to disabled.
$enrol->update_communication($instance->id, 'remove', $course->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Update enrolment communication when updating instance to enabled.
$enrol->update_communication($instance->id, 'add', $course->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Check our Matrix user id no longer has membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when the provider is disabled.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_disabling_provider(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
require_once($CFG->dirroot . '/course/lib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Disable communication provider.
$course->selectedcommunication = 'none';
update_course($course);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when their user account is suspended.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_suspending_user(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Suspend user.
$user->suspended = 1;
user_update_user($user, false, false);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test enrolled users in a course lose access to a room when their user account is deleted.
*
* @covers \core_communication\api::remove_members_from_room
* @covers \core_communication\task\remove_members_from_room::execute
* @covers \core_communication\task\remove_members_from_room::queue
*/
public function test_users_removed_from_room_when_deleting_user(): void {
global $CFG;
require_once($CFG->dirroot . '/lib/enrollib.php');
// Sample data.
$roomname = 'Samplematrixroom';
$provider = 'communication_matrix';
$course = $this->get_course($roomname, $provider);
$user = $this->get_user();
// Run room tasks.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Enrol the user in the course.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course->id, true);
$instance = reset($enrolinstances);
$enrol->enrol_user($instance, $user->id);
// Run the user tasks.
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($user->id, $matrixhomeserverurl);
// Check our Matrix user id has room membership.
$this->assertTrue($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
// Delete user.
delete_user($user);
// Run the user tasks.
// $this->runAdhocTasks('\core_communication\task\remove_members_from_room');
// Check our Matrix user id no longer has membership.
$this->assertFalse($communicationprocessor->get_room_provider()->check_room_membership($matrixuserid));
}
/**
* Test create instance user mapping.
*
* @covers \core_communication\processor::create_instance_user_mapping
* @covers \core_communication\processor::mark_users_as_synced
* @covers \core_communication\processor::get_instance_userids
*/
public function test_create_instance_user_mapping(): void {
$this->resetAfterTest();
global $DB;
$course = $this->get_course('Sampleroom', 'none');
$userid = $this->get_user()->id;
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$component = 'core_course';
$instancetype = 'coursecommunication';
// First test the adding members to a room.
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Test against the object.
$communicationprocessor = processor::load_by_instance(
$component,
$instancetype,
$course->id
);
// Test against the database.
$communicationuserrecord = $DB->get_record('communication_user', [
'commid' => $communicationprocessor->get_id(),
'userid' => $userid
]);
$this->assertEquals($communicationuserrecord->userid, $userid);
$this->assertEquals($communicationuserrecord->commid, $communicationprocessor->get_id());
}
/**
* Test update instance user mapping.
*
* @covers \core_communication\processor::create_instance_user_mapping
* @covers \core_communication\processor::mark_users_as_synced
* @covers \core_communication\processor::get_instance_userids
* @covers \core_communication\processor::delete_instance_user_mapping
*/
public function test_update_instance_user_mapping(): void {
$this->resetAfterTest();
global $DB;
$course = $this->get_course();
$userid = $this->get_user()->id;
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$component = 'core_course';
$instancetype = 'coursecommunication';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->update_room($selectedcommunication, $communicationroomname);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\update_room_task');
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Test against the object.
$communicationprocessor = processor::load_by_instance(
$component,
$instancetype,
$course->id
);
// Test against the database.
$communicationuserrecord = $DB->get_record('communication_user', [
'commid' => $communicationprocessor->get_id(),
'userid' => $userid
]);
$this->assertEquals($communicationuserrecord->userid, $userid);
$this->assertEquals($communicationuserrecord->commid, $communicationprocessor->get_id());
// Now add again.
$communicationprocessor->delete_instance_user_mapping([$userid]);
// Test against the database.
$communicationuserrecord = $DB->get_record('communication_user', [
'commid' => $communicationprocessor->get_id(),
'userid' => $userid
]);
$this->assertEmpty($communicationuserrecord);
}
/**
* Test delete instance user mapping.
*
* @covers \core_communication\processor::create_instance_user_mapping
* @covers \core_communication\processor::mark_users_as_synced
* @covers \core_communication\processor::get_instance_userids
* @covers \core_communication\processor::delete_instance_user_mapping
*/
public function test_delete_instance_user_mapping(): void {
$this->resetAfterTest();
global $DB;
$course = $this->get_course('Sampleroom', 'none');
$userid = $this->get_user()->id;
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$component = 'core_course';
$instancetype = 'coursecommunication';
// First test the adding members to a room.
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Test against the object.
$communicationprocessor = processor::load_by_instance(
$component,
$instancetype,
$course->id
);
$this->assertEquals([$userid], $communicationprocessor->get_all_userids_for_instance());
// Delete the user mapping.
$communicationprocessor->delete_instance_user_mapping([$userid]);
$this->assertEmpty($communicationprocessor->get_all_userids_for_instance());
// Test against the database.
$communicationuserrecord = $DB->get_record('communication_user', [
'commid' => $communicationprocessor->get_id(),
'userid' => $userid
]);
$this->assertEmpty($communicationuserrecord);
}
/**
* Test delete user mappings for instance.
*
* @covers \core_communication\processor::create_instance_user_mapping
* @covers \core_communication\processor::mark_users_as_synced
* @covers \core_communication\processor::get_instance_userids
* @covers \core_communication\processor::delete_user_mappings_for_instance
*/
public function test_delete_user_mappings_for_instance(): void {
$this->resetAfterTest();
global $DB;
$course = $this->get_course('Sampleroom', 'none');
$userid = $this->get_user()->id;
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$component = 'core_course';
$instancetype = 'coursecommunication';
// First test the adding members to a room.
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Test against the object.
$communicationprocessor = processor::load_by_instance(
$component,
$instancetype,
$course->id
);
$this->assertEquals([$userid], $communicationprocessor->get_all_userids_for_instance());
// Delete the user mapping.
$communicationprocessor->delete_user_mappings_for_instance();
$this->assertEmpty($communicationprocessor->get_all_userids_for_instance());
// Test against the database.
$communicationuserrecord = $DB->get_record('communication_user', [
'commid' => $communicationprocessor->get_id(),
'userid' => $userid
]);
$this->assertEmpty($communicationuserrecord);
}
}
@@ -0,0 +1,125 @@
<?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 communication_matrix;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/matrix_test_helper_trait.php');
/**
* Class matrix_events_manager_test to test the matrix events endpoint.
*
* @package communication_matrix
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \communication_matrix\matrix_events_manager
*/
class matrix_events_manager_test extends \advanced_testcase {
use matrix_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->initialise_mock_server();
}
/**
* Test the api endpoints url's for matrix.
*
* @return void
* @covers ::get_token
* @covers ::get_update_avatar_endpoint
* @covers ::get_update_room_topic_endpoint
* @covers ::get_update_room_name_endpoint
* @covers ::get_create_room_endpoint
* @covers ::get_delete_room_endpoint
* @covers ::get_upload_content_endpoint
*/
public function test_matrix_api_endpoints(): void {
$this->resetAfterTest();
$mockroomid = 'sampleroomid';
$mockuserid = 'sampleuserid';
$matrixeventsmanager = new matrix_events_manager($mockroomid);
// Test the endpoints and information.
$this->assertEquals($this->get_matrix_access_token(), $matrixeventsmanager->get_token());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/client/r0/createRoom',
$matrixeventsmanager->get_create_room_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($mockroomid) . '/' . 'state/m.room.topic/',
$matrixeventsmanager->get_update_room_topic_endpoint());
$this->assertEquals($this->get_matrix_server_url(). '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($mockroomid) . '/' . 'state/m.room.name/',
$matrixeventsmanager->get_update_room_name_endpoint());
$this->assertEquals($this->get_matrix_server_url(). '/' . '_synapse/admin/v1/rooms' .
'/' . urlencode($mockroomid), $matrixeventsmanager->get_room_info_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_synapse/admin/v1/rooms/' . urlencode($mockroomid),
$matrixeventsmanager->get_delete_room_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/media/r0/upload/',
$matrixeventsmanager->get_upload_content_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($mockroomid) . '/' . 'state/m.room.avatar/',
$matrixeventsmanager->get_update_avatar_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($mockroomid) . '/' . 'joined_members',
$matrixeventsmanager->get_room_membership_joined_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_synapse/admin/v1/join' .
'/' . urlencode($mockroomid),
$matrixeventsmanager->get_room_membership_join_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_matrix/client/r0/rooms' .
'/' . urlencode($mockroomid) . '/' . 'kick',
$matrixeventsmanager->get_room_membership_kick_endpoint());
$this->assertEquals($this->get_matrix_server_url() . '/' . '_synapse/admin/v2/users/' . urlencode($mockuserid),
$matrixeventsmanager->get_create_user_endpoint($mockuserid));
$this->assertEquals($this->get_matrix_server_url() . '/' . '_synapse/admin/v2/users/' . urlencode($mockuserid),
$matrixeventsmanager->get_user_info_endpoint($mockuserid));
}
/**
* Test upload matrix content.
*
* @return void
* @covers ::upload_matrix_content
*/
public function test_upload_matrix_content(): void {
global $CFG;
$this->resetAfterTest();
$mockroomid = 'sampleroomid';
$filecontent = file_get_contents($CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg');
$matrixeventsmanager = new matrix_events_manager($mockroomid);
$response = $matrixeventsmanager->upload_matrix_content($filecontent);
$this->assertNotFalse($response);
$this->assertNotEmpty($response);
}
}
@@ -0,0 +1,179 @@
<?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 communication_matrix;
use core_communication\processor;
use core_communication\communication_test_helper_trait;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/matrix_test_helper_trait.php');
require_once(__DIR__ . '/../../../tests/communication_test_helper_trait.php');
/**
* Class matrix_rooms_test to test the matrix room data in db.
*
* @package communication_matrix
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \communication_matrix\matrix_rooms
*/
class matrix_rooms_test extends \advanced_testcase {
use matrix_test_helper_trait;
use communication_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->resetAfterTest();
$this->setup_communication_configs();
}
/**
* Test the matrix room creation in database.
*
* @covers ::create_matrix_room_record
*/
public function test_create_matrix_room_record(): void {
global $DB;
$course = $this->get_course();
$sampleroomid = 'samplematrixroomid';
// Communication internal api call.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Call matrix room object to create the matrix data.
$matrixroom = new \communication_matrix\matrix_rooms($communicationprocessor->get_id());
$matrixroom->create_matrix_room_record(
$communicationprocessor->get_id(),
$sampleroomid,
);
// Test the object.
$this->assertEquals($matrixroom->get_matrix_room_id(), $sampleroomid);
// Get the record from db.
$matrixrecord = $DB->get_record('matrix_rooms',
['commid' => $communicationprocessor->get_id()]);
// Check the record against sample data.
$this->assertNotEmpty($matrixrecord);
$this->assertEquals($sampleroomid, $matrixrecord->roomid);
$this->assertEquals($communicationprocessor->get_id(), $matrixrecord->commid);
}
/**
* Test matrix room record updates.
*
* @covers ::update_matrix_room_record
*/
public function test_update_matrix_room_record(): void {
global $DB;
$course = $this->get_course();
$sampleroomid = 'samplematrixroomid';
// Communication internal api call.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Call matrix room object to create the matrix data.
$matrixroom = new \communication_matrix\matrix_rooms($communicationprocessor->get_id());
$matrixroom->create_matrix_room_record(
$communicationprocessor->get_id(),
$sampleroomid,
);
// Get the record from db.
$matrixrecord = $DB->get_record('matrix_rooms',
['commid' => $communicationprocessor->get_id()]);
// Check the record against sample data.
$this->assertNotEmpty($matrixrecord);
$sampleroomidupdated = 'samplematrixroomidupdated';
$matrixroom->update_matrix_room_record(
$sampleroomidupdated,
);
// Test the object.
$this->assertEquals($matrixroom->get_matrix_room_id(), $sampleroomidupdated);
// Get the record from db.
$matrixrecord = $DB->get_record('matrix_rooms',
['commid' => $communicationprocessor->get_id()]);
// Check the record against sample data.
$this->assertNotEmpty($matrixrecord);
$this->assertEquals($sampleroomidupdated, $matrixrecord->roomid);
$this->assertEquals($communicationprocessor->get_id(), $matrixrecord->commid);
}
/**
* Test matrix room deletion.
*
* @covers ::delete_matrix_room_record
* @covers ::get_matrix_room_id
*/
public function test_delete_matrix_room_record(): void {
global $DB;
$course = $this->get_course();
$sampleroomid = 'samplematrixroomid';
// Communication internal api call.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Call matrix room object to create the matrix data.
$matrixroom = new \communication_matrix\matrix_rooms($communicationprocessor->get_id());
$matrixroom->create_matrix_room_record(
$communicationprocessor->get_id(),
$sampleroomid,
);
// Get the record from db.
$matrixrecord = $DB->get_record('matrix_rooms',
['commid' => $communicationprocessor->get_id()]);
// Check the record against sample data.
$this->assertNotEmpty($matrixrecord);
// Now delete the record.
$matrixroom->delete_matrix_room_record();
// Get the record from db.
$matrixrecord = $DB->get_record('matrix_rooms',
['commid' => $communicationprocessor->get_id()]);
// Check the record against sample data.
$this->assertEmpty($matrixrecord);
}
}
@@ -0,0 +1,166 @@
<?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 communication_matrix;
/**
* Trait matrix_helper_trait to generate initial setup for matrix mock and associated helpers.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
trait matrix_test_helper_trait {
/**
* @var string $accesstoken The token for matrix connection
*/
protected string $accesstoken;
/**
* @var string $matrixhomeserverurl The server url of matrix synapse server
*/
protected string $matrixhomeserverurl;
/**
* Initialize the mock configs in settings.
*
* @return void
*/
protected function initialise_mock_configs(): void {
$this->matrixhomeserverurl = TEST_COMMUNICATION_MATRIX_MOCK_SERVER;
set_config('matrixhomeserverurl', $this->matrixhomeserverurl, 'communication_matrix');
$request = $this->request();
$response = $request->post($this->matrixhomeserverurl. '/backoffice/create-admin');
$admindata = json_decode($response->getBody());
$json = [
'identifier' => [
'type' => 'm.id.user',
'user' => $admindata->user_id,
],
'type' => 'm.login.password',
'password' => $admindata->password,
];
$request = $this->request($json);
$response = $request->post($this->matrixhomeserverurl. '/_matrix/client/r0/login');
$response = json_decode($response->getBody());
if (empty($response->access_token)) {
$this->markTestSkipped(
'The matrix mock server is not responsive, can not continue the tests'
);
}
$this->accesstoken = $response->access_token;
set_config('matrixaccesstoken', $this->accesstoken, 'communication_matrix');
}
/**
* Get the mock server url.
*
* @return string
*/
public function get_matrix_server_url(): string {
if (empty($this->matrixhomeserverurl)) {
throw new \coding_exception('Can not get this information without initializing the mock server.');
}
return $this->matrixhomeserverurl;
}
/**
* Get the matrix access token.
*
* @return string
*/
public function get_matrix_access_token(): string {
if (empty($this->accesstoken)) {
throw new \coding_exception('Can not get this information without initializing the mock server.');
}
return $this->accesstoken;
}
/**
* This test requires mock server to be present.
*
* @return void
*/
protected function initialise_mock_server(): void {
if (!defined('TEST_COMMUNICATION_MATRIX_MOCK_SERVER')) {
$this->markTestSkipped(
'The TEST_COMMUNICATION_MATRIX_MOCK_SERVER constant must be defined to run communication_matrix tests'
);
}
$this->reset_mock();
$this->initialise_mock_configs();
}
/**
* Get matrix room data from matrix server.
*
* @param string $roomid The id of the room
* @return \stdClass
*/
public function get_matrix_room_data(string $roomid): \stdClass {
$matrixeventmanager = new matrix_events_manager($roomid);
$response = $matrixeventmanager->request()->get($matrixeventmanager->get_room_info_endpoint());
return json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
}
/**
* Get matrix user data from matrix server.
*
* @param string $roomid The id of the room
* @param string $matrixuserid The id of the user
* @return \stdClass
*/
public function get_matrix_user_data(string $roomid, string $matrixuserid): \stdClass {
$matrixeventmanager = new matrix_events_manager($roomid);
$response = $matrixeventmanager->request()->get($matrixeventmanager->get_user_info_endpoint($matrixuserid));
return json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
}
/**
* The http request for the api call.
*
* @param array $jsonarray The array of json
* @param array $headers The array of headers
* @return \core\http_client
*/
public function request(array $jsonarray = [], array $headers = []): \core\http_client {
$response = new \core\http_client([
'headers' => $headers,
'json' => $jsonarray,
]);
return $response;
}
/**
* Reset the mock server
*
* @return void
*/
public function reset_mock(): void {
if (defined('TEST_COMMUNICATION_MATRIX_MOCK_SERVER')) {
$request = $this->request();
$response = $request->post(TEST_COMMUNICATION_MATRIX_MOCK_SERVER. '/backoffice/reset');
$response = json_decode($response->getBody());
if (empty($response->reset)) {
$this->markTestSkipped(
'The matrix mock server is not responsive, can not continue the tests'
);
}
}
}
}
@@ -0,0 +1,255 @@
<?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 communication_matrix;
use core_communication\processor;
use core_communication\communication_test_helper_trait;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/matrix_test_helper_trait.php');
require_once(__DIR__ . '/../../../tests/communication_test_helper_trait.php');
/**
* Class matrix_user_manager_test to test the matrix user manager.
*
* @package communication_matrix
* @category test
* @copyright 2023 Stevani Andolo <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \communication_matrix\matrix_user_manager
*/
class matrix_user_manager_test extends \advanced_testcase {
use matrix_test_helper_trait;
use communication_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->resetAfterTest();
$this->setup_communication_configs();
$this->initialise_mock_server();
}
/**
* Test get matrix id from moodle.
*
* @covers ::get_matrixid_from_moodle
*/
public function test_get_matrixid_from_moodle(): void {
$course = $this->get_course();
$userid = $this->get_user()->id;
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
// Get created matrixuserid from moodle.
$elementserver = matrix_user_manager::set_matrix_home_server($matrixhomeserverurl);
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($userid, $matrixhomeserverurl);
$this->assertNotNull($matrixuserid);
$this->assertEquals("@sampleun:{$elementserver}", $matrixuserid);
}
/**
* Sets qualified matrix user id.
*
* @return void
* @covers ::set_qualified_matrix_user_id
*/
public function test_set_qualified_matrix_user_id(): void {
$course = $this->get_course();
$user = $this->get_user();
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$user->id]);
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
$matrixhomeserverurl = $eventmanager->matrixhomeserverurl;
$elementserver = matrix_user_manager::set_matrix_home_server($matrixhomeserverurl);
// Sets qualified matrix id test1.
list($matrixuserid, $pureusername) = matrix_user_manager::set_qualified_matrix_user_id($user->id, $matrixhomeserverurl);
$this->assertEquals("@{$user->username}:{$elementserver}", $matrixuserid);
$this->assertEquals("sampleun", $pureusername);
// Sets qualified matrix id test2.
$user = $this->get_user('moodlefn', 'moodleln', '[email protected]');
list($matrixuserid, $pureusername) = matrix_user_manager::set_qualified_matrix_user_id($user->id, $matrixhomeserverurl);
$this->assertEquals("@admin.moodle.com:{$elementserver}", $matrixuserid);
$this->assertEquals("admin.moodle.com", $pureusername);
// Sets qualified matrix id test3.
$user = $this->get_user('moodlefn', 'moodleln', '[email protected]');
list($matrixuserid, $pureusername) = matrix_user_manager::set_qualified_matrix_user_id($user->id, $matrixhomeserverurl);
$this->assertEquals("@admin-user.moodle.com:{$elementserver}", $matrixuserid);
$this->assertEquals("admin-user.moodle.com", $pureusername);
}
/**
* Add user's matrix id to moodle.
*
* @covers ::add_user_matrix_id_to_moodle
*/
public function test_add_user_matrix_id_to_moodle(): void {
$course = $this->get_course();
$userid = $this->get_user()->id;
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
// Sets qualified matrix id.
list($qualifiedmuid, $pureusername) = matrix_user_manager::set_qualified_matrix_user_id(
$userid,
$eventmanager->matrixhomeserverurl
);
$this->assertNotNull($qualifiedmuid);
$this->assertNotNull($pureusername);
// Will return true on success.
$this->assertTrue(matrix_user_manager::add_user_matrix_id_to_moodle($userid, $pureusername));
// Get created matrixuserid from moodle.
$elementserver = matrix_user_manager::set_matrix_home_server($eventmanager->matrixhomeserverurl);
$matrixuserid = matrix_user_manager::get_matrixid_from_moodle($userid, $eventmanager->matrixhomeserverurl);
$this->assertNotNull($matrixuserid);
$this->assertEquals("@sampleun:{$elementserver}", $matrixuserid);
}
/**
* Add matrix home server for qualified matrix id.
*
* @return void
* @covers ::set_matrix_home_server
*/
public function test_set_matrix_home_server(): void {
$course = $this->get_course();
$userid = $this->get_user()->id;
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$matrixrooms = new matrix_rooms($communicationprocessor->get_id());
$eventmanager = new matrix_events_manager($matrixrooms->get_matrix_room_id());
// Will generate matrix home server.
$generatedhomeserver = matrix_user_manager::set_matrix_home_server($eventmanager->matrixhomeserverurl);
$this->assertNotNull($generatedhomeserver);
}
/**
* Test post matrix insert new user field record.
*
* @covers ::execute
*/
public function test_create_matrix_user_profile_fields(): void {
$course = $this->get_course();
$userid = $this->get_user()->id;
// Run room operation task.
$this->runAdhocTasks('\core_communication\task\create_and_configure_room_task');
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$userid]);
$this->runAdhocTasks('\core_communication\task\add_members_to_room_task');
// Check if "Communication" field has been added.
$categoryfield = get_config('core_communication', 'communication_category_field');
$this->assertNotNull($categoryfield);
$this->assertEquals('Communication', $categoryfield);
// Check if "matrixuserid" field has been added.
$infofield = get_config('communication_matrix', 'matrixuserid_field');
$this->assertNotNull($infofield);
$this->assertEquals('matrixuserid', $infofield);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?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/>.
/**
* Version information for communication_matrix.
*
* @package communication_matrix
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'communication_matrix';
$plugin->version = 2023032900;
$plugin->requires = 2023011300;
$plugin->maturity = MATURITY_ALPHA;
+2
View File
@@ -0,0 +1,2 @@
=== 4.2 ===
* Added new communication plugin type
+315
View File
@@ -0,0 +1,315 @@
<?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_communication;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/communication_test_helper_trait.php');
/**
* Class api_test to test the communication public api and its associated methods.
*
* @package core_communication
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_communication\api
*/
class api_test extends \advanced_testcase {
use communication_test_helper_trait;
public function setUp(): void {
parent::setUp();
$this->resetAfterTest();
$this->setup_communication_configs();
}
/**
* Test the communication plugin list for the form element returns the correct number of plugins.
*
* @covers ::get_communication_plugin_list_for_form
*/
public function test_get_communication_plugin_list_for_form(): void {
$communicationplugins = \core_communication\api::get_communication_plugin_list_for_form();
// Get the communication plugins.
$plugins = \core_component::get_plugin_list('communication');
// Check the number of plugins matches plus 1 as we have none in the selection.
$this->assertCount(count($plugins) + 1, $communicationplugins);
}
/**
* Test set data to the instance.
*
* @covers ::set_data
*/
public function test_set_data(): void {
$course = $this->get_course();
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Sample data.
$roomname = 'Sampleroom';
$provider = 'communication_matrix';
// Set the data.
$communication->set_data($course);
// Test the set data.
$this->assertEquals($roomname, $course->communicationroomname);
$this->assertEquals($provider, $course->selectedcommunication);
}
/**
* Test get_current_communication_provider method.
*
* @covers ::get_provider
*/
public function test_get_provider(): void {
$course = $this->get_course();
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals('communication_matrix', $communication->get_provider());
}
/**
* Test get_avatar_filerecord method.
*
* @covers ::get_avatar_filerecord
*/
public function test_get_avatar_filerecord(): void {
$course = $this->get_course();
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$filerecord = $communication->get_avatar_filerecord('avatar.svg');
$this->assertEquals('avatar.svg', $filerecord->filename);
$this->assertEquals('core_communication', $filerecord->component);
$this->assertEquals('avatar', $filerecord->filearea);
}
/**
* Test set_avatar_from_datauri method.
*
* @covers ::set_avatar_from_datauri_or_filepath
* @covers ::get_avatar_filerecord
*/
public function test_set_avatar_from_datauri_or_filepath(): void {
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname, $avatarurl);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertNotNull($communicationprocessor->get_avatar());
}
/**
* Test the create_and_configure_room method to add/create tasks.
*
* @covers ::create_and_configure_room
*/
public function test_create_and_configure_room(): void {
// Get the course by disabling communication so that we can create it manually calling the api.
$course = $this->get_course('Sampleroom', 'none');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname);
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\create_and_configure_room_task');
$this->assertCount(1, $adhoctask);
$adhoctask = reset($adhoctask);
$this->assertInstanceOf('\\core_communication\\task\\create_and_configure_room_task', $adhoctask);
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals($communicationroomname, $communicationprocessor->get_room_name());
$this->assertEquals($selectedcommunication, $communicationprocessor->get_provider());
}
/**
* Test the create_and_configure_room method to add/create tasks when no communication provider selected.
*
* @covers ::create_and_configure_room
*/
public function test_create_and_configure_room_without_communication_provider_selected(): void {
// Get the course by disabling communication so that we can create it manually calling the api.
$course = $this->getDataGenerator()->create_course();
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\create_and_configure_room_task');
$this->assertCount(0, $adhoctask);
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertNull($communicationprocessor);
}
/**
* Test update operation.
*
* @covers ::update_room
*/
public function test_update_room(): void {
$course = $this->get_course();
// Sample data.
$communicationroomname = 'Sampleroomupdated';
$selectedcommunication = 'communication_matrix';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->update_room($selectedcommunication, $communicationroomname);
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\update_room_task');
// Should be 2 as one for create, another for update.
$this->assertCount(1, $adhoctask);
$adhoctask = reset($adhoctask);
$this->assertInstanceOf('\\core_communication\\task\\update_room_task', $adhoctask);
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals($communicationroomname, $communicationprocessor->get_room_name());
$this->assertEquals($selectedcommunication, $communicationprocessor->get_provider());
}
/**
* Test delete operation.
*
* @covers ::delete_room
*/
public function test_delete_room(): void {
$course = $this->get_course();
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals($communicationroomname, $communicationprocessor->get_room_name());
$this->assertEquals($selectedcommunication, $communicationprocessor->get_provider());
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->delete_room();
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\delete_room_task');
// Should be 2 as one for create, another for update.
$this->assertCount(1, $adhoctask);
$adhoctask = reset($adhoctask);
$this->assertInstanceOf('\\core_communication\\task\\delete_room_task', $adhoctask);
}
/**
* Test the update_room_membership for adding adn removing members.
*
* @covers ::add_members_to_room
* @covers ::remove_members_from_room
*/
public function test_update_room_membership(): void {
$course = $this->get_course();
$userid = $this->get_user()->id;
// First test the adding members to a room.
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->add_members_to_room([$userid]);
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\add_members_to_room_task');
$this->assertCount(1, $adhoctask);
// Now test the removing members from a room.
$communication->remove_members_from_room([$userid]);
// Test the tasks added.
$adhoctask = \core\task\manager::get_adhoc_tasks('\\core_communication\\task\\remove_members_from_room');
$this->assertCount(1, $adhoctask);
}
}
@@ -0,0 +1,82 @@
<?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_communication;
/**
* Trait communication_test_helper_trait to generate initial setup for communication providers.
*
* @package core_communication
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
trait communication_test_helper_trait {
/**
* Setup necessary configs for communication subsystem.
*
* @return void
*/
protected function setup_communication_configs(): void {
set_config('enablecommunicationsubsystem', 1);
}
/**
* Get or create course if it does not exist
*
* @param string $roomname The room name for the communication api
* @param string $provider The selected provider
* @return \stdClass
*/
protected function get_course(
string $roomname = 'Sampleroom',
string $provider = 'communication_matrix'
): \stdClass {
$this->setup_communication_configs();
$records = [
'selectedcommunication' => $provider,
'communicationroomname' => $roomname,
];
return $this->getDataGenerator()->create_course($records);
}
/**
* Get or create user if it does not exist.
*
* @param string $firstname The user's firstname for the communication api
* @param string $lastname The user's lastname for the communication api
* @param string $username The user's username for the communication api
* @return \stdClass
*/
protected function get_user(
string $firstname = 'Samplefn',
string $lastname = 'Sampleln',
string $username = 'sampleun'
): \stdClass {
$this->setup_communication_configs();
$records = [
'firstname' => $firstname,
'lastname' => $lastname,
'username' => $username
];
return $this->getDataGenerator()->create_user($records);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

+398
View File
@@ -0,0 +1,398 @@
<?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_communication;
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/communication_test_helper_trait.php');
/**
* Class processor_test to test the communication internal api and its associated methods.
*
* @package core_communication
* @category test
* @copyright 2023 Safat Shahin <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_communication\processor
*/
class processor_test extends \advanced_testcase {
use communication_test_helper_trait;
/**
* Test create instance.
*
* @covers ::create_instance
* @covers ::get_id
* @covers ::get_instance
* @covers ::get_room_name
*/
public function test_create_instance(): void {
global $DB;
$this->resetAfterTest();
// Sameple test data.
$instanceid = 10;
$component = 'core_course';
$instancetype = 'coursecommunication';
$selectedcommunication = 'communication_matrix';
$communicationroomname = 'communicationroom';
$communicationprocessor = processor::create_instance(
$selectedcommunication,
$instanceid,
$component,
$instancetype,
$communicationroomname,
);
// Now test the record against the database.
$communicationrecord = $DB->get_record('communication',
['instanceid' => $instanceid, 'component' => $component, 'instancetype' => $instancetype]);
// Test against the set data.
$this->assertNotEmpty($communicationrecord);
$this->assertEquals($instanceid, $communicationrecord->instanceid);
$this->assertEquals($component, $communicationrecord->component);
$this->assertEquals($selectedcommunication, $communicationrecord->provider);
$this->assertEquals($communicationroomname, $communicationrecord->roomname);
$this->assertEquals($instancetype, $communicationrecord->instancetype);
// Test against the object.
$this->assertEquals($communicationprocessor->get_id(), $communicationrecord->id);
$this->assertEquals($communicationprocessor->get_provider(), $communicationrecord->provider);
$this->assertEquals($communicationprocessor->get_room_name(), $communicationrecord->roomname);
}
/**
* Test update instance.
*
* @covers ::update_instance
* @covers ::is_instance_active
* @covers ::get_id
* @covers ::get_room_name
*/
public function test_update_instance(): void {
global $DB;
$this->resetAfterTest();
// Sameple test data.
$instanceid = 10;
$component = 'core_course';
$instancetype = 'coursecommunication';
$selectedcommunication = 'communication_matrix';
$communicationroomname = 'communicationroom';
$communicationprocessor = processor::create_instance(
$selectedcommunication,
$instanceid,
$component,
$instancetype,
$communicationroomname,
);
$selectedcommunication = 'none';
$communicationroomname = 'communicationroomedited';
$communicationprocessor->update_instance($selectedcommunication, $communicationroomname);
// Now test the record against the database.
$communicationrecord = $DB->get_record('communication', [
'instanceid' => $instanceid,
'component' => $component,
'instancetype' => $instancetype
]);
// Test against the set data.
$this->assertNotEmpty($communicationrecord);
$this->assertEquals($instanceid, $communicationrecord->instanceid);
$this->assertEquals($component, $communicationrecord->component);
$this->assertEquals(processor::PROVIDER_INACTIVE, $communicationrecord->active);
$this->assertEquals($communicationroomname, $communicationrecord->roomname);
$this->assertEquals($instancetype, $communicationrecord->instancetype);
// Test against the object.
$this->assertEquals($communicationprocessor->get_id(), $communicationrecord->id);
$this->assertEquals($communicationprocessor->is_instance_active(), $communicationrecord->active);
$this->assertEquals($communicationprocessor->get_room_name(), $communicationrecord->roomname);
}
/**
* Test delete instance.
*
* @covers ::delete_instance
* @covers ::create_instance
* @covers ::load_by_instance
*/
public function test_delete_instance(): void {
global $DB;
$this->resetAfterTest();
// Sameple test data.
$instanceid = 10;
$component = 'core_course';
$instancetype = 'coursecommunication';
$selectedcommunication = 'communication_matrix';
$communicationroomname = 'communicationroom';
$communicationprocessor = processor::create_instance(
$selectedcommunication,
$instanceid,
$component,
$instancetype,
$communicationroomname,
);
$communicationprocessor->delete_instance();
// Now test the record against the database.
$communicationrecord = $DB->get_record('communication', [
'instanceid' => $instanceid,
'component' => $component,
'instancetype' => $instancetype
]);
// Test against the set data.
$this->assertEmpty($communicationrecord);
// Test against the object.
$communicationprocessor = processor::load_by_instance(
$component,
$instancetype,
$instanceid);
$this->assertNull($communicationprocessor);
}
/**
* Test load by id.
*
* @covers ::load_by_instance
* @covers ::get_room_provider
*/
public function test_load_by_instance(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertNotNull($communicationprocessor);
$this->assertInstanceOf(communication_provider::class, $communicationprocessor->get_room_provider());
$this->assertInstanceOf(room_chat_provider::class, $communicationprocessor->get_room_provider());
$this->assertInstanceOf(room_user_provider::class, $communicationprocessor->get_room_provider());
$this->assertInstanceOf(user_provider::class, $communicationprocessor->get_room_provider());
}
/**
* Test load by id.
*
* @covers ::load_by_id
* @covers ::get_room_provider
* @covers ::load_by_instance
*/
public function test_load_by_id(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communicationprocessorbyid = processor::load_by_id($communicationprocessor->get_id());
$this->assertNotNull($communicationprocessorbyid);
$this->assertInstanceOf(communication_provider::class, $communicationprocessorbyid->get_room_provider());
$this->assertInstanceOf(room_chat_provider::class, $communicationprocessorbyid->get_room_provider());
$this->assertInstanceOf(room_user_provider::class, $communicationprocessorbyid->get_room_provider());
$this->assertInstanceOf(user_provider::class, $communicationprocessorbyid->get_room_provider());
}
/**
* Test get component.
*
* @covers ::get_component
* @covers ::load_by_instance
*/
public function test_get_component(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals('core_course', $communicationprocessor->get_component());
}
/**
* Test get provider.
*
* @covers ::get_provider
* @covers ::load_by_instance
*/
public function test_get_provider(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals('communication_matrix', $communicationprocessor->get_provider());
}
/**
* Test get room name.
*
* @covers ::get_room_name
* @covers ::load_by_instance
*/
public function test_get_room_name(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertEquals('Sampleroom', $communicationprocessor->get_room_name());
}
/**
* Test get room provider.
*
* @covers ::get_room_provider
* @covers ::require_room_features
* @covers ::supports_room_features
* @covers ::load_by_instance
*/
public function test_get_room_provider(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertInstanceOf(room_chat_provider::class, $communicationprocessor->get_room_provider());
}
/**
* Test get user provider.
*
* @covers ::get_user_provider
* @covers ::require_user_features
* @covers ::supports_user_features
* @covers ::load_by_instance
*/
public function test_get_user_provider(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertInstanceOf(user_provider::class, $communicationprocessor->get_room_provider());
}
/**
* Test get room user provider.
*
* @covers ::get_room_user_provider
* @covers ::require_room_features
* @covers ::require_room_user_features
* @covers ::supports_room_user_features
* @covers ::supports_room_features
* @covers ::load_by_instance
*/
public function test_get_room_user_provider(): void {
$this->resetAfterTest();
$course = $this->get_course();
// Test the communication record exists.
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$this->assertInstanceOf(room_user_provider::class, $communicationprocessor->get_room_user_provider());
}
/**
* Test get avatar.
*
* @covers ::get_avatar
* @covers ::load_by_instance
*/
public function test_get_avatar(): void {
$this->resetAfterTest();
global $CFG;
$course = $this->get_course('Sampleroom', 'none');
// Sample data.
$communicationroomname = 'Sampleroom';
$selectedcommunication = 'communication_matrix';
$avatarurl = $CFG->dirroot . '/communication/tests/fixtures/moodle_logo.jpg';
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname, $avatarurl);
$communicationprocessor = processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$avatar = $communicationprocessor->get_avatar();
$this->assertNotNull($avatar);
$this->assertEquals($avatar->get_component(), 'core_communication');
$this->assertEquals($avatar->get_filearea(), 'avatar');
$this->assertEquals($avatar->get_itemid(), $communicationprocessor->get_id());
$this->assertEquals($avatar->get_filepath(), '/');
$this->assertEquals($avatar->get_filearea(), 'avatar');
}
}
+10
View File
@@ -403,6 +403,16 @@ class course_edit_form extends moodleform {
$handler->set_parent_context($categorycontext); // For course handler only.
$handler->instance_form_definition($mform, empty($course->id) ? 0 : $course->id);
// Add communication plugins to the form.
if (core_communication\api::is_available()) {
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
empty($course->id) ? 0 : $course->id);
$communication->form_definition($mform);
$communication->set_data($course);
}
// When two elements we need a group.
$buttonarray = array();
$classarray = array('class' => 'form-submit');
+78
View File
@@ -24,6 +24,7 @@
defined('MOODLE_INTERNAL') || die;
use core_course\external\course_summary_exporter;
use core_courseformat\base as course_format;
require_once($CFG->libdir.'/completionlib.php');
@@ -2313,6 +2314,18 @@ function create_course($data, $editoroptions = NULL) {
core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
}
// Communication api implementation in course.
if (isset($data->selectedcommunication) && core_communication\api::is_available()) {
// Prepare the communication api date.
$courseimage = course_summary_exporter::get_course_image($course);
$communicationroomname = !empty($data->communicationroomname) ? $data->communicationroomname : $data->fullname;
$selectedcommunication = $data->selectedcommunication;
// Communication api call.
$communication = \core_communication\api::load_by_instance('core_course', 'coursecommunication', $course->id);
$communication->create_and_configure_room($selectedcommunication, $communicationroomname, $courseimage);
}
// Save custom fields if there are any of them in the form.
$handler = core_course\customfield\course_handler::create();
// Make sure to set the handler's parent context first.
@@ -2434,6 +2447,71 @@ function update_course($data, $editoroptions = NULL) {
$data->showcompletionconditions = null;
}
// Check if provider is selected.
$provider = $data->selectedcommunication ?? null;
// If the course moved to hidden category, set provider to none.
if ($changesincoursecat && empty($data->visible)) {
$provider = 'none';
}
// Communication api call.
if (!empty($provider) && core_communication\api::is_available()) {
// Prepare the communication api data.
$courseimage = course_summary_exporter::get_course_image($data);
if (!$courseimage) {
$courseimage = null;
}
// This nasty logic is here because of hide course doesn't pass anything in the data object.
if (!empty($data->communicationroomname)) {
$communicationroomname = $data->communicationroomname;
} else {
$communicationroomname = $data->fullname ?? $oldcourse->fullname;
}
// Update communication room membership of enrolled users.
require_once($CFG->libdir . '/enrollib.php');
$courseusers = enrol_get_course_users($data->id);
$enrolledusers = [];
foreach ($courseusers as $user) {
$enrolledusers[] = $user->id;
}
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$data->id
);
$addafterupdate = false;
if ($provider !== $communication->get_provider()) {
// If provider set to none, remove all the members.
if ($provider === 'none') {
$communication->remove_members_from_room($enrolledusers);
} else if (
// If previous provider was not none and current provider is not none, but a different provider, remove members.
$communication->get_provider() !== '' &&
$communication->get_provider() !== 'none' &&
$provider !== $communication->get_provider()
) {
$communication->remove_members_from_room($enrolledusers);
$addafterupdate = true;
} else if (
// If previous provider was none and current provider is not none, but a different provider, remove members.
($communication->get_provider() === '' || $communication->get_provider() === 'none') &&
$provider !== $communication->get_provider()
) {
$addafterupdate = true;
}
}
$communication->update_room($provider, $communicationroomname, $courseimage);
if ($addafterupdate) {
$communication->add_members_to_room($enrolledusers, false);
}
}
// Update custom fields if there are any of them in the form.
$handler = core_course\customfield\course_handler::create();
$handler->instance_form_save($data);
+15
View File
@@ -93,6 +93,7 @@ if ($canconfig and $action and confirm_sesskey()) {
redirect($PAGE->url);
} else if ($action === 'delete') {
$instance = $instances[$instanceid];
$plugin = $plugins[$instance->enrol];
@@ -117,6 +118,10 @@ if ($canconfig and $action and confirm_sesskey()) {
die();
}
}
// Update communication for instance and given action.
if (core_communication\api::is_available() && $instance->enrol !== 'guest') {
$plugin->update_communication($instance->id, 'remove', $course->id);
}
$plugin->delete_instance($instance);
redirect($PAGE->url);
}
@@ -144,6 +149,7 @@ if ($canconfig and $action and confirm_sesskey()) {
}
} else if ($action === 'disable') {
$instance = $instances[$instanceid];
$plugin = $plugins[$instance->enrol];
if ($plugin->can_hide_show_instance($instance)) {
@@ -166,16 +172,25 @@ if ($canconfig and $action and confirm_sesskey()) {
die();
}
}
// Update communication for instance and given action.
if (core_communication\api::is_available() && $instance->enrol !== 'guest') {
$plugin->update_communication($instance->id, 'remove', $course->id);
}
$plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
redirect($PAGE->url);
}
}
} else if ($action === 'enable') {
$instance = $instances[$instanceid];
$plugin = $plugins[$instance->enrol];
if ($plugin->can_hide_show_instance($instance)) {
if ($instance->status != ENROL_INSTANCE_ENABLED) {
// Update communication for instance and given action.
if (core_communication\api::is_available() && $instance->enrol !== 'guest') {
$plugin->update_communication($instance->id, 'add', $course->id);
}
$plugin->update_status($instance, ENROL_INSTANCE_ENABLED);
redirect($PAGE->url);
}
+2
View File
@@ -589,6 +589,8 @@ $string['enableanalytics'] = 'Analytics';
$string['enableblogs'] = 'Enable blogs';
$string['enablecalendarexport'] = 'Enable calendar export';
$string['enablecomments'] = 'Enable comments';
$string['enablecommunicationsubsystem'] = 'Enable communication subsystem';
$string['enablecommunicationsubsystem_desc'] = 'This setting enables the new communication subsystem. This new subsystem allow teachers and students to more easily communicate while using Moodle for teaching and learning';
$string['enablecourserelativedates'] = 'Enable course relative dates';
$string['enablecourserelativedates_desc'] = 'Allow courses to be set up to display dates relative to the user\'s start date in the course.';
$string['enablecourserequests'] = 'Enable course requests';
+37
View File
@@ -0,0 +1,37 @@
<?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/>.
/**
* Strings for component 'communication', language 'en'.
*
* @package core_communication
* @copyright 2022 Huong Nguyen <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['communication'] = 'Communication';
$string['communicationprovidernotfound'] = 'The \'{$a}\' communication provider doesn\'t exist or is not recognised.';
$string['communicationroomname'] = 'Room name';
$string['communicationroomname_help'] = 'The name that participants see when they visit the room. If you leave this blank, a default room name will be automatically set.';
$string['managecommunicationproviders'] = 'Manage communication providers';
$string['nocommunicationprovider'] = 'No communication provider found.';
$string['nocommunicationselected'] = 'None';
$string['privacy:metadata:communication_user'] = 'The communication user table stores the user id and communication id for communication provider mapping.';
$string['privacy:metadata:communication_user:commid'] = 'The communication id for user mapping';
$string['privacy:metadata:communication_user:userid'] = 'The user id for communication provider mapping for users';
$string['privacy:metadata:communication_user:synced'] = 'The user is synced with the provider or not';
$string['seleccommunicationprovider'] = 'Communication service';
$string['seleccommunicationprovider_help'] = 'The tool available for chat and related communication methods.';
+1
View File
@@ -51,6 +51,7 @@ $string['aria:recommendedtab'] = 'Recommended activities';
$string['aria:modulefavourite'] = 'Star {$a} activity';
$string['browsecourseadminindex'] = 'Browse the course administration with this index.';
$string['browsesettingindex'] = 'Browse settings with this index.';
$string['communicationroomlink'] = 'Chat to course participants';
$string['completion_automatic:done'] = 'Done:';
$string['completion_automatic:failed'] = 'Failed:';
$string['completion_automatic:todo'] = 'To do:';
+4
View File
@@ -124,8 +124,12 @@ $string['type_cachestore'] = 'Cache store';
$string['type_cachestore_plural'] = 'Cache stores';
$string['type_calendartype'] = 'Calendar type';
$string['type_calendartype_plural'] = 'Calendar types';
$string['type_communication'] = 'Communication provider';
$string['type_communication_plural'] = 'Communication providers';
$string['type_contenttype'] = 'Content bank';
$string['type_contenttype_plural'] = 'Content bank plugins';
$string['type_contentbank'] = 'Content bank';
$string['type_contentbank_plural'] = 'Content bank plugins';
$string['type_customfield'] = 'Custom field';
$string['type_customfield_plural'] = 'Custom fields';
$string['type_coursereport'] = 'Course report';
+23
View File
@@ -4918,6 +4918,29 @@ class admin_setting_requiredtext extends admin_setting_configtext {
}
}
/**
* This type of field should be used for mandatory config settings where setting password is required.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class admin_setting_requiredpasswordunmask extends admin_setting_configpasswordunmask {
/**
* Validate data before storage.
*
* @param string $data The string to be validated.
* @return bool|string true for success or error string if invalid.
*/
public function validate($data) {
$cleaned = clean_param($data, PARAM_TEXT);
if ($cleaned === '') {
return get_string('required');
}
return parent::validate($data);
}
}
/**
* Special text editor for site description.
*
@@ -414,6 +414,7 @@ class icon_system_fontawesome extends icon_system_font {
'core:t/locktime' => 'fa-lock',
'core:t/markasread' => 'fa-check',
'core:t/messages' => 'fa-comments',
'core:t/messages-o' => 'fa-comments-o',
'core:t/message' => 'fa-comment-o',
'core:t/more' => 'fa-caret-down',
'core:t/move' => 'fa-arrows-v',
+4
View File
@@ -1825,6 +1825,10 @@ class core_plugin_manager {
'gregorian'
),
'communication' => [
'matrix',
],
'contenttype' => array(
'h5p'
),
+134
View File
@@ -0,0 +1,134 @@
<?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\plugininfo;
use admin_settingpage;
use core_plugin_manager;
use moodle_url;
/**
* Class for communication provider.
*
* @package core
* @copyright 2023 Huong Nguyen <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class communication extends base {
public static function get_manage_url(): moodle_url {
return new moodle_url('/admin/settings.php', ['section' => 'managecommunicationproviders']);
}
public function get_settings_section_name(): string {
return $this->type . '_' . $this->name;
}
public static function enable_plugin(string $pluginname, int $enabled): bool {
$haschanged = false;
$plugin = 'communication_' . $pluginname;
$oldvalue = get_config($plugin, 'disabled');
$disabled = !$enabled;
// Only set value if there is no config setting or if the value is different from the previous one.
if ($oldvalue == false && $disabled) {
set_config('disabled', $disabled, $plugin);
$haschanged = true;
} else if ($oldvalue != false && !$disabled) {
unset_config('disabled', $plugin);
$haschanged = true;
}
if ($haschanged) {
add_to_config_log('disabled', $oldvalue, $disabled, $plugin);
core_plugin_manager::reset_caches();
}
return $haschanged;
}
public static function get_enabled_plugins(): ?array {
$pluginmanager = core_plugin_manager::instance();
$plugins = $pluginmanager->get_installed_plugins('communication');
if (!$plugins) {
return [];
}
$plugins = array_keys($plugins);
// Filter to return only enabled plugins.
$enabled = [];
foreach ($plugins as $plugin) {
$disabled = get_config('communication_' . $plugin, 'disabled');
if (empty($disabled)) {
$enabled[$plugin] = $plugin;
}
}
return $enabled;
}
public function load_settings(\part_of_admin_tree $adminroot, $parentnodename, $hassiteconfig) {
global $CFG, $USER, $DB, $OUTPUT, $PAGE; // In case settings.php wants to refer to them.
$ADMIN = $adminroot; // May be used in settings.php.
$plugininfo = $this; // Also can be used inside settings.php.
if (!$this->is_installed_and_upgraded()) {
return;
}
if (!$hassiteconfig) {
return;
}
$section = $this->get_settings_section_name();
$settings = null;
if (file_exists($this->full_path('settings.php'))) {
$settings = new admin_settingpage($section, $this->displayname,
'moodle/site:config', $this->is_enabled() === false);
include($this->full_path('settings.php')); // This may also set $settings to null.
}
if ($settings) {
$ADMIN->add($parentnodename, $settings);
}
}
public function is_uninstall_allowed(): bool {
if (in_array($this->name, \core_plugin_manager::standard_plugins_list('communication'))) {
return false;
}
return true;
}
/**
* Checks if a communication plugin is ready to be used.
* It checks the plugin status as well as the plugin is missing or not.
*
* @param string $fullpluginname the name of the plugin
* @return bool
*/
public static function is_plugin_enabled($fullpluginname): bool {
$pluginmanager = \core_plugin_manager::instance();
$communicationinfo = $pluginmanager->get_plugin_info($fullpluginname);
if (empty($communicationinfo)) {
return false;
}
$communicationavailable = $communicationinfo->get_status();
return !($communicationavailable === \core_plugin_manager::PLUGIN_STATUS_MISSING ||
!empty(get_config($fullpluginname, 'disabled')));
}
}
+2
View File
@@ -6,6 +6,7 @@
"mod": "mod",
"auth": "auth",
"calendartype": "calendar\/type",
"communication": "communication\/provider",
"customfield": "customfield\/field",
"enrol": "enrol",
"message": "message\/output",
@@ -59,6 +60,7 @@
"calendar": "calendar",
"cohort": "cohort",
"comment": "comment",
"communication": "communication",
"competency": "competency",
"completion": "completion",
"contentbank": "contentbank",
+29
View File
@@ -218,6 +218,35 @@
<INDEX NAME="useridcourse" UNIQUE="true" FIELDS="userid, course"/>
</INDEXES>
</TABLE>
<TABLE NAME="communication" COMMENT="Communication records">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="instanceid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="ID of the instance where the communication is a part of"/>
<FIELD NAME="component" TYPE="char" LENGTH="100" NOTNULL="true" SEQUENCE="false" COMMENT="Component of the instance where the communication room is a part of"/>
<FIELD NAME="instancetype" TYPE="char" LENGTH="100" NOTNULL="true" SEQUENCE="false" COMMENT="The type of the instance for the given component"/>
<FIELD NAME="provider" TYPE="char" LENGTH="100" NOTNULL="true" SEQUENCE="false" COMMENT="Name of the selected communication provider"/>
<FIELD NAME="roomname" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false" COMMENT="Name of the communication room"/>
<FIELD NAME="avatarfilename" TYPE="char" LENGTH="100" NOTNULL="false" SEQUENCE="false" COMMENT="Name of the avatar file name for the communication instance"/>
<FIELD NAME="active" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="1" SEQUENCE="false" COMMENT="The communication instance is active or not"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="communication_user" COMMENT="Communication user records mapping">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="commid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="ID of the communication instance"/>
<FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="ID of the moodle user to map with communication instance"/>
<FIELD NAME="synced" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="The user is synced or not"/>
<FIELD NAME="deleted" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="The user need to be deleted or not"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="commid" TYPE="foreign" FIELDS="commid" REFTABLE="communication" REFFIELDS="id"/>
<KEY NAME="userid" TYPE="foreign" FIELDS="userid" REFTABLE="user" REFFIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="enrol" COMMENT="Instances of enrolment plugins used in courses, fields marked as custom have a plugin defined meaning, core does not touch them. Create a new linked table if you need even more custom fields.">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
+46
View File
@@ -3259,5 +3259,51 @@ privatefiles,moodle|/user/files.php';
// Automatically generated Moodle v4.2.0 release upgrade line.
// Put any upgrade step following this.
if ($oldversion < 2023051500.00) {
// Define communication table.
$table = new xmldb_table('communication');
// Adding fields to table communication.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
$table->add_field('instanceid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
$table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'instanceid');
$table->add_field('instancetype', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'component');
$table->add_field('provider', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'instancerype');
$table->add_field('roomname', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'provider');
$table->add_field('avatarfilename', XMLDB_TYPE_CHAR, '100', null, null, null, null, 'roomname');
$table->add_field('active', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 1, 'avatarfilename');
// Add key.
$table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
// Conditionally launch create table for communication.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Define communication user table.
$table = new xmldb_table('communication_user');
// Adding fields to table communication.
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
$table->add_field('commid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
$table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'commid');
$table->add_field('synced', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'userid');
$table->add_field('deleted', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'synced');
// Add keys.
$table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
$table->add_key('commid', XMLDB_KEY_FOREIGN, ['commid'], 'communication', ['id']);
$table->add_key('userid', XMLDB_KEY_FOREIGN, ['userid'], 'user', ['id']);
// Conditionally launch create table for communication.
if (!$dbman->table_exists($table)) {
$dbman->create_table($table);
}
// Main savepoint reached.
upgrade_main_savepoint(true, 2023051500.00);
}
return true;
}
+79
View File
@@ -2145,6 +2145,16 @@ abstract class enrol_plugin {
grade_recover_history_grades($userid, $courseid);
}
// Add users to a communication room.
if (core_communication\api::is_available()) {
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$courseid
);
$communication->add_members_to_room([$userid]);
}
// reset current user enrolment caching
if ($userid == $USER->id) {
if (isset($USER->enrol['enrolled'][$courseid])) {
@@ -2182,9 +2192,12 @@ abstract class enrol_plugin {
}
$modified = false;
$statusmodified = false;
$timeendmodified = false;
if (isset($status) and $ue->status != $status) {
$ue->status = $status;
$modified = true;
$statusmodified = true;
}
if (isset($timestart) and $ue->timestart != $timestart) {
$ue->timestart = $timestart;
@@ -2193,6 +2206,7 @@ abstract class enrol_plugin {
if (isset($timeend) and $ue->timeend != $timeend) {
$ue->timeend = $timeend;
$modified = true;
$timeendmodified = true;
}
if (!$modified) {
@@ -2200,6 +2214,22 @@ abstract class enrol_plugin {
return;
}
// Add/remove users to/from communication room.
if (core_communication\api::is_available()) {
$course = enrol_get_course_by_user_enrolment_id($ue->id);
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
if (($statusmodified && ((int) $ue->status === 1)) ||
($timeendmodified && $ue->timeend !== 0 && (time() > $ue->timeend))) {
$communication->remove_members_from_room([$userid]);
} else {
$communication->add_members_to_room([$userid]);
}
}
$ue->modifierid = $USER->id;
$ue->timemodified = time();
$DB->update_record('user_enrolments', $ue);
@@ -2303,6 +2333,16 @@ abstract class enrol_plugin {
);
$event->trigger();
// Remove users from a communication room.
if (core_communication\api::is_available()) {
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$courseid
);
$communication->remove_members_from_room([$userid]);
}
// User enrolments have changed, so mark user as dirty.
mark_user_dirty($userid);
@@ -2641,6 +2681,45 @@ abstract class enrol_plugin {
$context->mark_dirty();
}
/**
* Update instance members.
*
* Update communication room membership for an instance action being performed.
*
* @param int $instanceid ID of the enrolment instance
* @param string $action The update action being performed
* @param int $courseid The id of the course
* @return void
*/
public function update_communication(int $instanceid, string $action, int $courseid): void {
global $DB;
// Get enrolled instance users.
$instanceusers = $DB->get_records('user_enrolments', ['enrolid' => $instanceid, 'status' => 0]);
$enrolledusers = [];
foreach ($instanceusers as $user) {
$enrolledusers[] = $user->userid;
}
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$courseid
);
switch ($action) {
case 'add':
$communication->add_members_to_room($enrolledusers);
break;
case 'remove':
$communication->remove_members_from_room($enrolledusers);
break;
default:
throw new \coding_exception('Invalid action');
}
}
/**
* Delete course enrol plugin instance, unenrol all users.
* @param object $instance
+34 -1
View File
@@ -4145,6 +4145,19 @@ function delete_user(stdClass $user) {
// Keep a copy of user context, we need it for event.
$usercontext = context_user::instance($user->id);
// Remove user from communication rooms immediately.
if (core_communication\api::is_available()) {
foreach (enrol_get_users_courses($user->id) as $course) {
$communication = \core_communication\processor::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
$communication->get_room_user_provider()->remove_members_from_room([$user->id]);
$communication->delete_instance_user_mapping([$user->id]);
}
}
// Delete all grades - backup is kept in grade_grades_history table.
grade_user_delete($user->id);
@@ -5031,7 +5044,7 @@ function set_login_session_preferences() {
* failed, but you have no way of knowing which.
*/
function delete_course($courseorid, $showfeedback = true) {
global $DB;
global $DB, $CFG;
if (is_object($courseorid)) {
$courseid = $courseorid->id;
@@ -5071,6 +5084,26 @@ function delete_course($courseorid, $showfeedback = true) {
// Delete the course and related context instance.
context_helper::delete_instance(CONTEXT_COURSE, $courseid);
// Communication provider delete associated information.
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$course->id
);
// Update communication room membership of enrolled users.
require_once($CFG->libdir . '/enrollib.php');
$courseusers = enrol_get_course_users($courseid);
$enrolledusers = [];
foreach ($courseusers as $user) {
$enrolledusers[] = $user->id;
}
$communication->remove_members_from_room($enrolledusers);
$communication->delete_room();
$DB->delete_records("course", array("id" => $courseid));
$DB->delete_records("course_format_options", array("courseid" => $courseid));
+48
View File
@@ -4285,6 +4285,54 @@ EOD;
return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
}
/**
* Helper function to decide whether to show the communication link or not.
*
* @return bool
*/
public function has_communication_links(): bool {
if (!core_communication\api::is_available()) {
return false;
}
return !empty($this->communication_link());
}
/**
* Returns the communication link, complete with html.
*
* @return string
*/
public function communication_link(): string {
if (during_initial_install()) {
return '';
}
$link = $this->communication_url() ?? '';
$commicon = $this->pix_icon('t/messages-o', '', 'moodle', ['class' => 'fa fa-comments']);
$newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
$content = $commicon . get_string('communicationroomlink', 'course') . $newwindowicon;
$html = html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
return !empty($link) ? $html : '';
}
/**
* Returns the communication url for a given instance if it exists.
*
* @return string
*/
public function communication_url(): string {
global $COURSE;
$url = '';
if ($COURSE->id !== SITEID) {
$comm = \core_communication\api::load_by_instance('core_course', 'coursecommunication', $COURSE->id);
$url = $comm->get_communication_room_url();
}
return !empty($url) ? $url : '';
}
/**
* Returns the page heading menu.
*
+1 -1
View File
@@ -31,7 +31,7 @@ class component_test extends advanced_testcase {
* this is defined here to annoy devs that try to add more without any thinking,
* always verify that it does not collide with any existing add-on modules and subplugins!!!
*/
const SUBSYSTEMCOUNT = 76;
const SUBSYSTEMCOUNT = 77;
public function setUp(): void {
$psr0namespaces = new ReflectionProperty('core_component', 'psr0namespaces');
+5
View File
@@ -1,6 +1,11 @@
This files describes API changes in core libraries and APIs,
information provided here is intended especially for developers.
=== 4.3 ===
* Admin settings for passwords (admin_setting_configpasswordunmask) can now be a required field using the following class:
- admin_setting_requiredpasswordunmask
=== 4.2 ===
* All context classes were moved to \core\context namespace while keeping full backwards compatibility.
+3
View File
@@ -217,6 +217,9 @@
<testsuite name="core_admin_testsuite">
<directory suffix="_test.php">admin/tests</directory>
</testsuite>
<testsuite name="core_communication_testsuite">
<directory suffix="_test.php">communication/tests</directory>
</testsuite>
<!--Plugin suites: use admin/tool/phpunit/cli/util.php to build phpunit.xml from
phpunit.xml.dist with up-to-date list of plugins in current install-->
+14 -1
View File
@@ -2309,10 +2309,22 @@ $footer-link-color: $bg-inverse-link-color !default;
@include box-shadow($popover-box-shadow);
}
.btn-footer-communication {
display: none;
position: fixed;
bottom: 5rem;
right: 2rem;
@include box-shadow($popover-box-shadow);
}
.hasstickyfooter .btn-footer-popover {
bottom: calc(1rem + #{$stickyfooter-height});
}
.hasstickyfooter .btn-footer-communication {
bottom: calc(4rem + #{$stickyfooter-height});
}
.popover.footer {
.popover-body {
padding: 0;
@@ -2339,7 +2351,8 @@ $footer-link-color: $bg-inverse-link-color !default;
.jsenabled #page-footer .footer-content-popover {
display: none;
}
.jsenabled .btn-footer-popover {
.jsenabled .btn-footer-popover,
.jsenabled .btn-footer-communication {
display: block;
z-index: $zindex-dropdown;
}
+13 -1
View File
@@ -25138,10 +25138,21 @@ h3.sectionname .inplaceeditable.inplaceeditingon .editinstructions {
right: 2rem;
}
.btn-footer-communication {
display: none;
position: fixed;
bottom: 5rem;
right: 2rem;
}
.hasstickyfooter .btn-footer-popover {
bottom: calc(1rem + max(96px, 0.9375rem * 3));
}
.hasstickyfooter .btn-footer-communication {
bottom: calc(4rem + max(96px, 0.9375rem * 3));
}
.popover.footer .popover-body {
padding: 0;
}
@@ -25164,7 +25175,8 @@ h3.sectionname .inplaceeditable.inplaceeditingon .editinstructions {
.jsenabled #page-footer .footer-content-popover {
display: none;
}
.jsenabled .btn-footer-popover {
.jsenabled .btn-footer-popover,
.jsenabled .btn-footer-communication {
display: block;
z-index: 1000;
}
+14 -1
View File
@@ -27,18 +27,31 @@
"has_popover_links": true,
"services_support": "Services and support",
"login_info": "You are logged in as cute kitten",
"moodle_release": "90210"
"moodle_release": "90210",
"has_communication_links": true,
"communication_url": "https://element:8081/#/room/#yourroom:synapse",
"communication_link": "<a href=\"#\">Communication room</a>"
}
}
}}
<footer id="page-footer" class="footer-popover bg-white">
<div data-region="footer-container-popover">
{{#output.has_communication_links}}
<button onclick="window.open('{{output.communication_url}}', '_blank')" class="btn btn-icon bg-primary text-white icon-no-margin btn-footer-communication" aria-label="{{#str}}communicationroomlink, course{{/str}}">
{{#pix}}t/messages-o, core{{/pix}}
</button>
{{/output.has_communication_links}}
<button class="btn btn-icon bg-secondary icon-no-margin btn-footer-popover" data-action="footer-popover" aria-label="{{#str}}showfooter, theme_boost{{/str}}">
{{#pix}}e/question, core{{/pix}}
</button>
</div>
<div class="footer-content-popover container" data-region="footer-content-popover">
{{#output.has_communication_links}}
<div class="footer-section p-3 border-bottom footer-link-communication">
<div class="footer-support-link">{{{ output.communication_link }}}</div>
</div>
{{/output.has_communication_links}}
{{# output.has_popover_links }}
<div class="footer-section p-3 border-bottom">
{{# output.page_doc_link }}
+13 -1
View File
@@ -25138,10 +25138,21 @@ h3.sectionname .inplaceeditable.inplaceeditingon .editinstructions {
right: 2rem;
}
.btn-footer-communication {
display: none;
position: fixed;
bottom: 5rem;
right: 2rem;
}
.hasstickyfooter .btn-footer-popover {
bottom: calc(1rem + max(96px, 0.9375rem * 3));
}
.hasstickyfooter .btn-footer-communication {
bottom: calc(4rem + max(96px, 0.9375rem * 3));
}
.popover.footer .popover-body {
padding: 0;
}
@@ -25164,7 +25175,8 @@ h3.sectionname .inplaceeditable.inplaceeditingon .editinstructions {
.jsenabled #page-footer .footer-content-popover {
display: none;
}
.jsenabled .btn-footer-popover {
.jsenabled .btn-footer-popover,
.jsenabled .btn-footer-communication {
display: block;
z-index: 1000;
}
+10 -1
View File
@@ -33,8 +33,17 @@
<footer id="page-footer" class="footer-dark bg-dark text-light">
<div class="container footer-dark-inner">
<div id="course-footer">{{{ output.course_footer }}}</div>
{{#output.has_communication_links}}
<button onclick="window.open('{{output.communication_url}}', '_blank')" class="btn btn-icon bg-primary text-white icon-no-margin btn-footer-communication" aria-label="{{#str}}communicationroomlink, course{{/str}}">
{{#pix}}t/messages-o, core{{/pix}}
</button>
{{/output.has_communication_links}}
<div class="pb-3">
{{#output.has_communication_links}}
<div class="footer-section footer-link-communication">
<div class="footer-support-link">{{{ output.communication_link }}}</div>
</div>
{{/output.has_communication_links}}
{{# output.page_doc_link }}
<div class="footer-support-link">{{{ output.page_doc_link }}}</div>
{{/ output.page_doc_link }}
+22 -1
View File
@@ -150,13 +150,34 @@ function user_create_user($user, $updatepassword = true, $triggerevent = true) {
* This will not affect user_password_updated event triggering.
*/
function user_update_user($user, $updatepassword = true, $triggerevent = true) {
global $DB;
global $DB, $CFG;
// Set the timecreate field to the current time.
if (!is_object($user)) {
$user = (object) $user;
}
// Communication api update for user.
if (core_communication\api::is_available()) {
$usercourses = enrol_get_users_courses($user->id);
$currentrecord = $DB->get_record('user', ['id' => $user->id]);
if (!empty($currentrecord) && isset($user->suspended) && $currentrecord->suspended !== $user->suspended) {
foreach ($usercourses as $usercourse) {
$communication = \core_communication\api::load_by_instance(
'core_course',
'coursecommunication',
$usercourse->id
);
// If the record updated the suspended for a user.
if ($user->suspended === 0) {
$communication->add_members_to_room([$user->id]);
} else if ($user->suspended === 1) {
$communication->remove_members_from_room([$user->id]);
}
}
}
}
// Check username.
if (isset($user->username)) {
if ($user->username !== core_text::strtolower($user->username)) {
+1 -1
View File
@@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
$version = 2023051200.00; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2023051500.00; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '4.3dev (Build: 20230512)'; // Human-friendly version name