first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+145
View File
@@ -0,0 +1,145 @@
<?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/>.
/**
* Privacy Subsystem implementation for enrol_cohort.
*
* @package enrol_cohort
* @category privacy
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace enrol_cohort\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_userlist;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
/**
* Privacy provider for enrol_cohort.
*
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
// This plugin stores user data.
\core_privacy\local\metadata\provider,
// This plugin contains user's enrolments.
\core_privacy\local\request\plugin\provider,
// This plugin is capable of determining which users have data within it.
\core_privacy\local\request\core_userlist_provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised item collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
$collection->add_subsystem_link('core_group', [], 'privacy:metadata:core_group');
return $collection;
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
return \core_group\privacy\provider::get_contexts_for_group_member($userid, 'enrol_cohort');
}
/**
* Get the list of users who have data within a context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_course) {
return;
}
\core_group\privacy\provider::get_group_members_in_context($userlist, 'enrol_cohort');
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
if (empty($contextlist)) {
return;
}
foreach ($contextlist as $context) {
if ($context->contextlevel == CONTEXT_COURSE) {
\core_group\privacy\provider::export_groups(
$context,
'enrol_cohort',
[get_string('pluginname', 'enrol_cohort')]
);
}
}
}
/**
* Delete all use data which matches the specified deletion_criteria.
*
* @param \context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
if (empty($context)) {
return;
}
if ($context->contextlevel == CONTEXT_COURSE) {
// Delete all the associated groups.
\core_group\privacy\provider::delete_groups_for_all_users($context, 'enrol_cohort');
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
if (empty($contextlist->count())) {
return;
}
\core_group\privacy\provider::delete_groups_for_user($contextlist, 'enrol_cohort');
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
\core_group\privacy\provider::delete_groups_for_users($userlist, 'enrol_cohort');
}
}
@@ -0,0 +1,60 @@
<?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/>.
/**
* Syncing enrolments task.
*
* @package enrol_cohort
* @author Farhan Karmali <farhan6318@gmail.com>
* @copyright Farhan Karmali
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace enrol_cohort\task;
defined('MOODLE_INTERNAL') || die();
/**
* Syncing enrolments task.
*
* @package enrol_cohort
* @author Farhan Karmali <farhan6318@gmail.com>
* @copyright Farhan Karmali
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_cohort_sync extends \core\task\scheduled_task {
/**
* Name for this task.
*
* @return string
*/
public function get_name() {
return get_string('enrolcohortsynctask', 'enrol_cohort');
}
/**
* Run task for syncing cohort enrolments.
*/
public function execute() {
global $CFG;
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new \null_progress_trace();
enrol_cohort_sync($trace);
$trace->finished();
}
}
+70
View File
@@ -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/>.
/**
* CLI sync for cohort enrolments, use for debugging or immediate sync
* of all courses.
*
* Notes:
* - it is required to use the web server account when executing PHP CLI scripts
* - you need to change the "www-data" to match the apache user account
* - use "su" if "sudo" not available
*
* @package enrol_cohort
* @copyright 2011 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('CLI_SCRIPT', true);
require(__DIR__.'/../../../config.php');
require_once("$CFG->libdir/clilib.php");
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
// Now get cli options.
list($options, $unrecognized) = cli_get_params(array('verbose'=>false, 'help'=>false), array('v'=>'verbose', 'h'=>'help'));
if ($unrecognized) {
$unrecognized = implode("\n ", $unrecognized);
cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
}
if ($options['help']) {
$help =
"Execute cohort course enrol sync.
Options:
-v, --verbose Print verbose progess information
-h, --help Print out this help
Example:
\$ sudo -u www-data /usr/bin/php enrol/cohort/cli/sync.php
";
echo $help;
die;
}
if (empty($options['verbose'])) {
$trace = new null_progress_trace();
} else {
$trace = new text_progress_trace();
}
$result = enrol_cohort_sync($trace, null);
$trace->finished();
exit($result);
+49
View File
@@ -0,0 +1,49 @@
<?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/>.
/**
* Capabilities for cohort access plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'enrol/cohort:config' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW,
)
),
/* This is used only when sync suspends users instead of full unenrolment. */
'enrol/cohort:unenrol' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
'manager' => CAP_ALLOW,
)
),
);
+47
View File
@@ -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/>.
/**
* Cohort enrolment plugin event handler definition.
*
* @package enrol_cohort
* @category event
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$observers = array(
array(
'eventname' => '\core\event\cohort_member_added',
'callback' => 'enrol_cohort_handler::member_added',
'includefile' => '/enrol/cohort/locallib.php'
),
array(
'eventname' => '\core\event\cohort_member_removed',
'callback' => 'enrol_cohort_handler::member_removed',
'includefile' => '/enrol/cohort/locallib.php'
),
array(
'eventname' => '\core\event\cohort_deleted',
'callback' => 'enrol_cohort_handler::deleted',
'includefile' => '/enrol/cohort/locallib.php'
),
);
+39
View File
@@ -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/>.
/**
* Task definition for enrol_cohort.
* @author Farhan Karmali <farhan6318@gmail.com>
* @copyright Farhan Karmali
* @package enrol_cohort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$tasks = array(
array(
'classname' => '\enrol_cohort\task\enrol_cohort_sync',
'blocking' => 0,
'minute' => 'R',
'hour' => '*',
'day' => '*',
'month' => '*',
'dayofweek' => '*',
'disabled' => 0
)
);
+40
View File
@@ -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/>.
/**
* Meta link enrolment plugin uninstallation.
*
* @package enrol_cohort
* @copyright 2011 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
function xmldb_enrol_cohort_uninstall() {
global $CFG, $DB;
$cohort = enrol_get_plugin('cohort');
$rs = $DB->get_recordset('enrol', array('enrol'=>'cohort'));
foreach ($rs as $instance) {
$cohort->delete_instance($instance);
}
$rs->close();
role_unassign_all(array('component'=>'enrol_cohort'));
return true;
}
+1
View File
@@ -0,0 +1 @@
plugindisabled,enrol_cohort
+39
View File
@@ -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/>.
/**
* Strings for component 'enrol_cohort', language 'en'.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['addgroup'] = 'Add to group';
$string['assignrole'] = 'Assign role';
$string['cohort:config'] = 'Configure cohort instances';
$string['cohort:unenrol'] = 'Unenrol suspended users';
$string['defaultgroupnametext'] = '{$a->name} cohort {$a->increment}';
$string['enrolcohortsynctask'] = 'Cohort enrolment sync task';
$string['instanceexists'] = 'Cohort is already synchronised with selected role';
$string['pluginname'] = 'Cohort sync';
$string['pluginname_desc'] = 'Cohort enrolment plugin synchronises cohort members with course participants.';
$string['status'] = 'Active';
$string['creategroup'] = 'Create new group';
$string['privacy:metadata:core_group'] = 'Enrol cohort plugin can create a new group or use an existing group to add all the members of the cohort.';
// Deprecated since Moodle 4.5.
$string['plugindisabled'] = 'Cohort sync plugin is disabled';
+725
View File
@@ -0,0 +1,725 @@
<?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/>.
/**
* Cohort enrolment plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
*/
define('COHORT_CREATE_GROUP', -1);
/**
* COHORT_NOGROUP constant for using no group for a cohort.
*/
define('COHORT_NOGROUP', 0);
/**
* Cohort enrolment plugin implementation.
* @author Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_cohort_plugin extends enrol_plugin {
/**
* Is it possible to delete enrol instance via standard UI?
*
* @param stdClass $instance
* @return bool
*/
public function can_delete_instance($instance) {
$context = context_course::instance($instance->courseid);
return has_capability('enrol/cohort:config', $context);
}
/**
* Returns localised name of enrol instance.
*
* @param stdClass $instance (null is accepted too)
* @return string
*/
public function get_instance_name($instance) {
global $DB;
if (empty($instance)) {
$enrol = $this->get_name();
return get_string('pluginname', 'enrol_'.$enrol);
} else if (empty($instance->name)) {
$enrol = $this->get_name();
$cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
if (!$cohort) {
return get_string('pluginname', 'enrol_'.$enrol);
}
$cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid)));
if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
$role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING), ROLENAME_BOTH);
return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
} else {
return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
}
} else {
return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
}
}
/**
* Given a courseid this function returns true if the user is able to enrol or configure cohorts.
* AND there are cohorts that the user can view.
*
* @param int $courseid
* @return bool
*/
public function can_add_instance($courseid) {
global $CFG;
require_once($CFG->dirroot . '/cohort/lib.php');
$coursecontext = context_course::instance($courseid);
if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
return false;
}
return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
}
/**
* Add new instance of enrol plugin.
* @param object $course
* @param array $fields instance fields
* @return int id of new instance, null if can not be created
*/
public function add_instance($course, array $fields = null) {
global $CFG;
// Allows multiple cohorts to be set on creation.
if (!empty($fields['customint1'])) {
$fields2 = $fields;
if (!is_array($fields['customint1'])) {
$fields['customint1'] = array($fields['customint1']);
}
foreach ($fields['customint1'] as $cid) {
$fields2['customint1'] = $cid;
if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
// Create a new group for the cohort if requested.
$context = context_course::instance($course->id);
require_capability('moodle/course:managegroups', $context);
$groupid = enrol_cohort_create_new_group($course->id, $cid);
$fields2['customint2'] = $groupid;
}
$result = parent::add_instance($course, $fields2);
}
} else {
$result = parent::add_instance($course, $fields);
}
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new null_progress_trace();
enrol_cohort_sync($trace, $course->id);
$trace->finished();
return $result;
}
/**
* Update instance of enrol plugin.
* @param stdClass $instance
* @param stdClass $data modified instance fields
* @return boolean
*/
public function update_instance($instance, $data) {
global $CFG;
// NOTE: no cohort changes here!!!
$context = context_course::instance($instance->courseid);
if ($data->roleid != $instance->roleid) {
// The sync script can only add roles, for perf reasons it does not modify them.
$params = array(
'contextid' => $context->id,
'roleid' => $instance->roleid,
'component' => 'enrol_cohort',
'itemid' => $instance->id
);
role_unassign_all($params);
}
// Create a new group for the cohort if requested.
if ($data->customint2 == COHORT_CREATE_GROUP) {
require_capability('moodle/course:managegroups', $context);
$groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
$data->customint2 = $groupid;
}
$result = parent::update_instance($instance, $data);
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new null_progress_trace();
enrol_cohort_sync($trace, $instance->courseid);
$trace->finished();
return $result;
}
/**
* Called after updating/inserting course.
*
* @param bool $inserted true if course just inserted
* @param stdClass $course
* @param stdClass $data form data
* @return void
*/
public function course_updated($inserted, $course, $data) {
// It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
}
/**
* Update instance status
*
* @param stdClass $instance
* @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
* @return void
*/
public function update_status($instance, $newstatus) {
global $CFG;
parent::update_status($instance, $newstatus);
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new null_progress_trace();
enrol_cohort_sync($trace, $instance->courseid);
$trace->finished();
}
/**
* Does this plugin allow manual unenrolment of a specific user?
* Yes, but only if user suspended...
*
* @param stdClass $instance course enrol instance
* @param stdClass $ue record from user_enrolments table
*
* @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
*/
public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
if ($ue->status == ENROL_USER_SUSPENDED) {
return true;
}
return false;
}
/**
* Restore instance and map settings.
*
* @param restore_enrolments_structure_step $step
* @param stdClass $data
* @param stdClass $course
* @param int $oldid
*/
public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
global $DB, $CFG;
if (!$step->get_task()->is_samesite()) {
// No cohort restore from other sites.
$step->set_mapping('enrol', $oldid, 0);
return;
}
if (!empty($data->customint2)) {
$data->customint2 = $step->get_mappingid('group', $data->customint2);
}
if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
$instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
if ($instance) {
$instanceid = $instance->id;
} else {
$instanceid = $this->add_instance($course, (array)$data);
}
$step->set_mapping('enrol', $oldid, $instanceid);
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new null_progress_trace();
enrol_cohort_sync($trace, $course->id);
$trace->finished();
} else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
$data->customint1 = 0;
$instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
if ($instance) {
$instanceid = $instance->id;
} else {
$data->status = ENROL_INSTANCE_DISABLED;
$instanceid = $this->add_instance($course, (array)$data);
}
$step->set_mapping('enrol', $oldid, $instanceid);
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$trace = new null_progress_trace();
enrol_cohort_sync($trace, $course->id);
$trace->finished();
} else {
$step->set_mapping('enrol', $oldid, 0);
}
}
/**
* Restore user enrolment.
*
* @param restore_enrolments_structure_step $step
* @param stdClass $data
* @param stdClass $instance
* @param int $oldinstancestatus
* @param int $userid
*/
public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
global $DB;
if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
// Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
return;
}
// ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
// but without roles and suspended.
if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
$this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
}
}
/**
* Restore user group membership.
* @param stdClass $instance
* @param int $groupid
* @param int $userid
*/
public function restore_group_member($instance, $groupid, $userid) {
// Nothing to do here, the group members are added in $this->restore_group_restored()
return;
}
/**
* Is it possible to hide/show enrol instance via standard UI?
*
* @param stdClass $instance
* @return bool
*/
public function can_hide_show_instance($instance) {
$context = context_course::instance($instance->courseid);
return has_capability('enrol/cohort:config', $context);
}
/**
* Return an array of valid options for the status.
*
* @return array
*/
protected function get_status_options() {
$options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
ENROL_INSTANCE_DISABLED => get_string('no'));
return $options;
}
/**
* Return an array of valid options for the cohorts.
*
* @param stdClass $instance
* @param context $context
* @return array
*/
protected function get_cohort_options($instance, $context) {
global $DB, $CFG;
require_once($CFG->dirroot . '/cohort/lib.php');
$cohorts = array();
if ($instance->id) {
if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
$name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
$cohorts = array($instance->customint1 => $name);
} else {
$cohorts = array($instance->customint1 => get_string('error'));
}
} else {
$cohorts = array('' => get_string('choosedots'));
$allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
foreach ($allcohorts as $c) {
$cohorts[$c->id] = format_string($c->name);
}
}
return $cohorts;
}
/**
* Return an array of valid options for the roles.
*
* @param stdClass $instance
* @param context $coursecontext
* @return array
*/
protected function get_role_options($instance, $coursecontext) {
global $DB;
$roles = get_assignable_roles($coursecontext, ROLENAME_BOTH);
$roles[0] = get_string('none');
$roles = array_reverse($roles, true); // Descending default sortorder.
// If the instance is already configured, but the configured role is no longer assignable in the course then add it back.
if ($instance->id and !isset($roles[$instance->roleid])) {
if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
$roles[$instance->roleid] = role_get_name($role, $coursecontext, ROLENAME_BOTH);
} else {
$roles[$instance->roleid] = get_string('error');
}
}
return $roles;
}
/**
* Return an array of valid options for the groups.
*
* @param context $coursecontext
* @return array
*/
protected function get_group_options($coursecontext) {
$groups = array(0 => get_string('none'));
if (has_capability('moodle/course:managegroups', $coursecontext)) {
$groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
}
foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
$groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
}
return $groups;
}
/**
* We are a good plugin and don't invent our own UI/validation code path.
*
* @return boolean
*/
public function use_standard_editing_ui() {
return true;
}
/**
* Add elements to the edit instance form.
*
* @param stdClass $instance
* @param MoodleQuickForm $mform
* @param context $coursecontext
* @return bool
*/
public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
$options = $this->get_status_options();
$mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
$options = ['contextid' => $coursecontext->id, 'multiple' => true];
$mform->addElement('cohort', 'customint1', get_string('cohort', 'cohort'), $options);
if ($instance->id) {
$mform->setConstant('customint1', $instance->customint1);
$mform->hardFreeze('customint1', $instance->customint1);
} else {
$mform->addRule('customint1', get_string('required'), 'required', null, 'client');
}
$roles = $this->get_role_options($instance, $coursecontext);
$mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
$mform->setDefault('roleid', $this->get_config('roleid'));
$groups = $this->get_group_options($coursecontext);
$mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
}
/**
* Perform custom validation of the data used to edit the instance.
*
* @param array $data array of ("fieldname" => value) of submitted data
* @param array $files array of uploaded files "element_name" => tmp_file_path
* @param object $instance The instance loaded from the DB
* @param context $context The context of the instance we are editing
* @return array of "element_name" => "error_description" if there are errors,
* or an empty array if everything is OK.
* @return void
*/
public function edit_instance_validation($data, $files, $instance, $context) {
global $DB;
$errors = array();
// Allows multiple cohorts to be selected.
list($sql1, $params1) = $DB->get_in_or_equal($data['customint1'], SQL_PARAMS_NAMED);
$params = array(
'roleid' => $data['roleid'],
'courseid' => $data['courseid'],
'id' => $data['id']
);
$params = array_merge($params, $params1);
$sql = "roleid = :roleid AND customint1 $sql1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
if ($DB->record_exists_select('enrol', $sql, $params)) {
$errors['customint1'] = get_string('instanceexists', 'enrol_cohort');
}
$validstatus = array_keys($this->get_status_options());
$validcohorts = array_keys($this->get_cohort_options($instance, $context));
$validroles = array_keys($this->get_role_options($instance, $context));
$validgroups = array_keys($this->get_group_options($context));
$tovalidate = array(
'status' => $validstatus,
'roleid' => $validroles,
'customint2' => $validgroups
);
$typeerrors = $this->validate_param_types($data, $tovalidate);
// When creating a new cohort enrolment, we allow multiple cohorts in just one go.
// When editing an existing enrolment, changing the cohort is no allowed, so cohort is a single value.
if (is_array($data['customint1'])) {
$cohorts = $data['customint1'];
} else {
$cohorts = [$data['customint1']];
}
$errors = array_merge($errors, $typeerrors);
// Check that the cohorts passed are valid.
if (!empty(array_diff($cohorts, $validcohorts))) {
$errors['customint1'] = get_string('invaliddata', 'error');
}
return $errors;
}
/**
* Check if data is valid for a given enrolment plugin
*
* @param array $enrolmentdata enrolment data to validate.
* @param int|null $courseid Course ID.
* @return array Errors
*/
public function validate_enrol_plugin_data(array $enrolmentdata, ?int $courseid = null): array {
global $DB;
$errors = parent::validate_enrol_plugin_data($enrolmentdata, $courseid);
if (isset($enrolmentdata['addtogroup'])) {
$addtogroup = $enrolmentdata['addtogroup'];
if (($addtogroup == - COHORT_CREATE_GROUP) || $addtogroup == COHORT_NOGROUP) {
if (isset($enrolmentdata['groupname'])) {
$errors['erroraddtogroupgroupname'] =
new lang_string('erroraddtogroupgroupname', 'group');
}
} else {
$errors['erroraddtogroup'] =
new lang_string('erroraddtogroup', 'group');
}
}
if ($courseid) {
$enrolmentdata = $this->fill_enrol_custom_fields($enrolmentdata, $courseid);
$error = $this->validate_plugin_data_context($enrolmentdata, $courseid);
if ($error) {
$errors['contextnotallowed'] = $error;
}
if (isset($enrolmentdata['groupname']) && $enrolmentdata['groupname']) {
$groupname = $enrolmentdata['groupname'];
if (!groups_get_group_by_name($courseid, $groupname)) {
$errors['errorinvalidgroup'] =
new lang_string('errorinvalidgroup', 'group', $groupname);
}
}
}
if (!isset($enrolmentdata['cohortidnumber'])) {
$missingmandatoryfields = 'cohortidnumber';
} else {
$cohortidnumber = $enrolmentdata['cohortidnumber'];
// Cohort idnumber is unique.
$cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $cohortidnumber]);
if (!$cohortid) {
$errors['unknowncohort'] =
new lang_string('unknowncohort', 'cohort', $cohortidnumber);
}
}
if (!isset($enrolmentdata['role'])) {
// We require role since we need it to identify enrol instance.
if (isset($missingmandatoryfields)) {
$missingmandatoryfields .= ', role';
} else {
$missingmandatoryfields = 'role';
}
$errors['missingmandatoryfields'] =
new lang_string('missingmandatoryfields', 'tool_uploadcourse',
$missingmandatoryfields);
} else {
$roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
if (!$roleid) {
$errors['unknownrole'] =
new lang_string('unknownrole', 'error', s($enrolmentdata['role']));
}
}
return $errors;
}
/**
* Fill custom fields data for a given enrolment plugin.
*
* @param array $enrolmentdata enrolment data.
* @param int $courseid Course ID.
* @return array Updated enrolment data with custom fields info.
*/
public function fill_enrol_custom_fields(array $enrolmentdata, int $courseid): array {
global $DB;
if (isset($enrolmentdata['cohortidnumber'])) {
// Cohort idnumber is unique.
$enrolmentdata['customint1'] =
$DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
}
if (isset($enrolmentdata['addtogroup'])) {
if ($enrolmentdata['addtogroup'] == COHORT_NOGROUP) {
$enrolmentdata['customint2'] = COHORT_NOGROUP;
} else if ($enrolmentdata['addtogroup'] == - COHORT_CREATE_GROUP) {
$enrolmentdata['customint2'] = COHORT_CREATE_GROUP;
}
} else if (isset($enrolmentdata['groupname'])) {
$enrolmentdata['customint2'] = groups_get_group_by_name($courseid, $enrolmentdata['groupname']);
}
return $enrolmentdata;
}
/**
* Check if plugin custom data is allowed in relevant context.
*
* @param array $enrolmentdata enrolment data to validate.
* @param int|null $courseid Course ID.
* @return lang_string|null Error
*/
public function validate_plugin_data_context(array $enrolmentdata, ?int $courseid = null): ?lang_string {
$error = null;
if (isset($enrolmentdata['customint1'])) {
$cohortid = $enrolmentdata['customint1'];
$coursecontext = \context_course::instance($courseid);
if (!cohort_get_cohort($cohortid, $coursecontext)) {
$error = new lang_string('contextcohortnotallowed', 'cohort', $enrolmentdata['cohortidnumber']);
}
}
return $error;
}
/**
* Add new instance of enrol plugin with custom settings,
* called when adding new instance manually or when adding new course.
* Used for example on course upload.
*
* Not all plugins support this.
*
* @param stdClass $course Course object
* @param array|null $fields instance fields
* @return int|null id of new instance or null if not supported
*/
public function add_custom_instance(stdClass $course, ?array $fields = null): ?int {
return $this->add_instance($course, $fields);
}
/**
* Check if enrolment plugin is supported in csv course upload.
*
* @return bool
*/
public function is_csv_upload_supported(): bool {
return true;
}
/**
* Finds matching instances for a given course.
*
* @param array $enrolmentdata enrolment data.
* @param int $courseid Course ID.
* @return stdClass|null Matching instance
*/
public function find_instance(array $enrolmentdata, int $courseid): ?stdClass {
global $DB;
$instances = enrol_get_instances($courseid, false);
$instance = null;
if (isset($enrolmentdata['cohortidnumber']) && isset($enrolmentdata['role'])) {
$cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
$roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
if ($cohortid && $roleid) {
foreach ($instances as $i) {
if ($i->enrol == 'cohort' && $i->customint1 == $cohortid && $i->roleid == $roleid) {
$instance = $i;
break;
}
}
}
}
return $instance;
}
}
/**
* Prevent removal of enrol roles.
* @param int $itemid
* @param int $groupid
* @param int $userid
* @return bool
*/
function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
return false;
}
/**
* Create a new group with the cohorts name.
*
* @param int $courseid
* @param int $cohortid
* @return int $groupid Group ID for this cohort.
*/
function enrol_cohort_create_new_group($courseid, $cohortid) {
global $DB, $CFG;
require_once($CFG->dirroot . '/group/lib.php');
$groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
$a = new stdClass();
$a->name = $groupname;
$a->increment = '';
$groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
$inc = 1;
// Check to see if the cohort group name already exists. Add an incremented number if it does.
while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
$a->increment = '(' . (++$inc) . ')';
$newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
$groupname = $newshortname;
}
// Create a new group for the cohort.
$groupdata = new stdClass();
$groupdata->courseid = $courseid;
$groupdata->name = $groupname;
$groupid = groups_create_group($groupdata);
return $groupid;
}
+313
View File
@@ -0,0 +1,313 @@
<?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/>.
/**
* Local stuff for cohort enrolment plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/enrol/locallib.php');
require_once($CFG->dirroot . '/cohort/lib.php');
/**
* Event handler for cohort enrolment plugin.
*
* We try to keep everything in sync via listening to events,
* it may fail sometimes, so we always do a full sync in cron too.
*/
class enrol_cohort_handler {
/**
* Event processor - cohort member added.
* @param \core\event\cohort_member_added $event
* @return bool
*/
public static function member_added(\core\event\cohort_member_added $event) {
global $DB, $CFG;
require_once("$CFG->dirroot/group/lib.php");
if (!enrol_is_enabled('cohort')) {
return true;
}
// Does any enabled cohort instance want to sync with this cohort?
$sql = "SELECT e.*, r.id as roleexists
FROM {enrol} e
LEFT JOIN {role} r ON (r.id = e.roleid)
WHERE e.customint1 = :cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus
ORDER BY e.id ASC";
$params['cohortid'] = $event->objectid;
$params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
if (!$instances = $DB->get_records_sql($sql, $params)) {
return true;
}
$plugin = enrol_get_plugin('cohort');
foreach ($instances as $instance) {
if ($instance->status != ENROL_INSTANCE_ENABLED ) {
// No roles for disabled instances.
$instance->roleid = 0;
} else if ($instance->roleid and !$instance->roleexists) {
// Invalid role - let's just enrol, they will have to create new sync and delete this one.
$instance->roleid = 0;
}
unset($instance->roleexists);
// No problem if already enrolled.
$plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE);
// Sync groups.
if ($instance->customint2) {
if (!groups_is_member($instance->customint2, $event->relateduserid)) {
if ($group = $DB->get_record('groups', array('id'=>$instance->customint2, 'courseid'=>$instance->courseid))) {
groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id);
}
}
}
}
return true;
}
/**
* Event processor - cohort member removed.
* @param \core\event\cohort_member_removed $event
* @return bool
*/
public static function member_removed(\core\event\cohort_member_removed $event) {
global $DB;
// Does anything want to sync with this cohort?
if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
return true;
}
$plugin = enrol_get_plugin('cohort');
$unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
foreach ($instances as $instance) {
if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$event->relateduserid))) {
continue;
}
if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
$plugin->unenrol_user($instance, $event->relateduserid);
} else {
if ($ue->status != ENROL_USER_SUSPENDED) {
$plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
$context = context_course::instance($instance->courseid);
if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id,
'component' => 'enrol_cohort', 'itemid' => $instance->id));
}
}
}
}
return true;
}
/**
* Event processor - cohort deleted.
* @param \core\event\cohort_deleted $event
* @return bool
*/
public static function deleted(\core\event\cohort_deleted $event) {
global $DB;
// Does anything want to sync with this cohort?
if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
return true;
}
$plugin = enrol_get_plugin('cohort');
$unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
foreach ($instances as $instance) {
if ($unenrolaction != ENROL_EXT_REMOVED_UNENROL) {
$context = context_course::instance($instance->courseid);
if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
role_unassign_all(array('contextid' => $context->id, 'component' => 'enrol_cohort',
'itemid' => $instance->id));
}
$plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
} else {
$plugin->delete_instance($instance);
}
}
return true;
}
}
/**
* Sync all cohort course links.
* @param progress_trace $trace
* @param int $courseid one course, empty mean all
* @return int 0 means ok, 1 means error, 2 means plugin disabled
*/
function enrol_cohort_sync(progress_trace $trace, $courseid = NULL) {
global $CFG, $DB;
require_once("$CFG->dirroot/group/lib.php");
// Purge all roles if cohort sync disabled, those can be recreated later here by cron or CLI.
if (!enrol_is_enabled('cohort')) {
$trace->output('Cohort sync plugin is disabled, unassigning all plugin roles and stopping.');
role_unassign_all(array('component'=>'enrol_cohort'));
return 2;
}
// Unfortunately this may take a long time, this script can be interrupted without problems.
core_php_time_limit::raise();
raise_memory_limit(MEMORY_HUGE);
$trace->output('Starting user enrolment synchronisation...');
$allroles = get_all_roles();
$instances = array(); //cache
$plugin = enrol_get_plugin('cohort');
$unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
// Iterate through all not enrolled yet users.
$onecourse = $courseid ? "AND e.courseid = :courseid" : "";
$sql = "SELECT cm.userid, e.id AS enrolid, ue.status
FROM {cohort_members} cm
JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus $onecourse)
JOIN {user} u ON (u.id = cm.userid AND u.deleted = 0)
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
WHERE ue.id IS NULL OR ue.status = :suspended";
$params = array();
$params['courseid'] = $courseid;
$params['suspended'] = ENROL_USER_SUSPENDED;
$params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $ue) {
if (!isset($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
}
$instance = $instances[$ue->enrolid];
if ($ue->status == ENROL_USER_SUSPENDED) {
$plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_ACTIVE);
$trace->output("unsuspending: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
} else {
$plugin->enrol_user($instance, $ue->userid);
$trace->output("enrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
}
}
$rs->close();
// Unenrol as necessary.
$sql = "SELECT ue.*, e.courseid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
WHERE cm.id IS NULL";
$rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
foreach($rs as $ue) {
if (!isset($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
}
$instance = $instances[$ue->enrolid];
if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
// Remove enrolment together with group membership, grades, preferences, etc.
$plugin->unenrol_user($instance, $ue->userid);
$trace->output("unenrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
} else { // ENROL_EXT_REMOVED_SUSPENDNOROLES
// Just disable and ignore any changes.
if ($ue->status != ENROL_USER_SUSPENDED) {
$plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
$context = context_course::instance($instance->courseid);
if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id,
'component' => 'enrol_cohort', 'itemid' => $instance->id));
$trace->output("unsassigning all roles: $ue->userid ==> $instance->courseid", 1);
}
$trace->output("suspending: $ue->userid ==> $instance->courseid", 1);
}
}
}
$rs->close();
unset($instances);
// Now assign all necessary roles to enrolled users - skip suspended instances and users.
$onecourse = $courseid ? "AND e.courseid = :courseid" : "";
$sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid, e.courseid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' AND e.status = :statusenabled $onecourse)
JOIN {role} r ON (r.id = e.roleid)
JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :coursecontext)
JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid AND ra.itemid = e.id AND ra.component = 'enrol_cohort' AND e.roleid = ra.roleid)
WHERE ue.status = :useractive AND ra.id IS NULL";
$params = array();
$params['statusenabled'] = ENROL_INSTANCE_ENABLED;
$params['useractive'] = ENROL_USER_ACTIVE;
$params['coursecontext'] = CONTEXT_COURSE;
$params['courseid'] = $courseid;
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $ra) {
role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
$trace->output("assigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
}
$rs->close();
if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
// Remove unwanted roles - sync role can not be changed, we only remove role when unenrolled.
$onecourse = $courseid ? "AND e.courseid = :courseid" : "";
$sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid
FROM {role_assignments} ra
JOIN {context} c ON (c.id = ra.contextid AND c.contextlevel = :coursecontext)
JOIN {enrol} e ON (e.id = ra.itemid AND e.enrol = 'cohort' $onecourse)
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :useractive)
WHERE ra.component = 'enrol_cohort' AND (ue.id IS NULL OR e.status <> :statusenabled)";
$params = array();
$params['statusenabled'] = ENROL_INSTANCE_ENABLED;
$params['useractive'] = ENROL_USER_ACTIVE;
$params['coursecontext'] = CONTEXT_COURSE;
$params['courseid'] = $courseid;
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ra) {
role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
$trace->output("unassigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
}
$rs->close();
}
// Finally sync groups.
$affectedusers = groups_sync_with_enrolment('cohort', $courseid);
foreach ($affectedusers['removed'] as $gm) {
$trace->output("removing user from group: $gm->userid ==> $gm->courseid - $gm->groupname", 1);
}
foreach ($affectedusers['added'] as $ue) {
$trace->output("adding user to group: $ue->userid ==> $ue->courseid - $ue->groupname", 1);
}
$trace->output('...user enrolment synchronisation finished.');
return 0;
}
+47
View File
@@ -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/>.
/**
* Cohort enrolment plugin settings and presets.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
if ($ADMIN->fulltree) {
//--- general settings -----------------------------------------------------------------------------------
$settings->add(new admin_setting_heading('enrol_cohort_settings', '', get_string('pluginname_desc', 'enrol_cohort')));
//--- enrol instance defaults ----------------------------------------------------------------------------
if (!during_initial_install()) {
$options = get_default_enrol_roles(context_system::instance());
$student = get_archetype_roles('student');
$student = reset($student);
$settings->add(new admin_setting_configselect('enrol_cohort/roleid',
get_string('defaultrole', 'role'), '', $student->id ?? null, $options));
$options = array(
ENROL_EXT_REMOVED_UNENROL => get_string('extremovedunenrol', 'enrol'),
ENROL_EXT_REMOVED_SUSPEND => get_string('extremovedsuspend', 'enrol'),
ENROL_EXT_REMOVED_SUSPENDNOROLES => get_string('extremovedsuspendnoroles', 'enrol'));
$settings->add(new admin_setting_configselect('enrol_cohort/unenrolaction', get_string('extremovedaction', 'enrol'), get_string('extremovedaction_help', 'enrol'), ENROL_EXT_REMOVED_UNENROL, $options));
}
}
@@ -0,0 +1,112 @@
@enrol @enrol_cohort
Feature: Cohort enrolment management
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher001 | Teacher | 001 | teacher001@example.com |
And the following "cohorts" exist:
| name | idnumber | visible |
| Alpha1 | A1 | 1 |
| Beta2 | B1 | 1 |
And the following "courses" exist:
| fullname | shortname | format | startdate |
| Course 001 | C001 | weeks | ##1 month ago## |
And the following "course enrolments" exist:
| user | course | role | timestart |
| teacher001 | C001 | editingteacher | ##1 month ago## |
@javascript
Scenario: Add multiple cohorts to the course
When I log in as "teacher001"
And I am on the "Course 001" "enrolment methods" page
And I select "Cohort sync" from the "Add method" singleselect
And I open the autocomplete suggestions list
And I click on "Alpha1" item in the autocomplete list
And "Alpha1" "autocomplete_selection" should exist
And I click on "Beta2" item in the autocomplete list
And "Alpha1" "autocomplete_selection" should exist
And "Beta2" "autocomplete_selection" should exist
And I press "Add method"
Then I should see "Cohort sync (Beta2 - Student)"
And I should see "Cohort sync (Alpha1 - Student)"
@javascript
Scenario: Edit cohort enrolment
When I log in as "teacher001"
And I add "Cohort sync" enrolment method in "Course 001" with:
| Cohort | Alpha1 |
And I should see "Cohort sync (Alpha1 - Student)"
And I click on "Edit" "link" in the "Alpha1" "table_row"
And I set the field "Assign role" to "Non-editing teacher"
And I click on "Save" "button"
And I should see "Cohort sync (Alpha1 - Non-editing teacher)"
@javascript
Scenario: Course cohort enrolment sync cohorts members
Given the following "users" exist:
| username | firstname | lastname | email |
| s1 | Sandra | Cole | s1@example.com |
| s2 | John | Smith | s2@example.com |
| s4 | Jane | Doe | s4@example.com |
And the following "cohort members" exist:
| user | cohort |
| s1 | A1 |
| s2 | A1 |
When I log in as "teacher001"
And I add "Cohort sync" enrolment method in "Course 001" with:
| Cohort | A1 |
| customint2 | -1 |
Then I should see "Cohort sync (Alpha1 - Student)"
And I set the field "Participants tertiary navigation" to "Groups"
# Confirm that group was created and corresponding group members are present
And I set the field "groups[]" to "Alpha1 cohort (2)"
And the "members" select box should contain "Sandra Cole (s1@example.com)"
And the "members" select box should contain "John Smith (s2@example.com)"
And I log in as "admin"
And I navigate to "Users > Accounts > Cohorts" in site administration
And I press "Assign" action in the "Alpha1" report row
And I should see "Cohort 'Alpha1' members"
And I should see "Removing users from a cohort may result in unenrolling of users from multiple courses which includes deleting of user settings, grades, group membership and other user information from affected courses."
# Remove user s4 from cohort
And I set the field "removeselect[]" to "John Smith (s2@example.com)"
And I click on "Remove" "button"
# Add user s4 to the cohort.
And I set the field "addselect_searchtext" to "s4"
And I set the field "addselect[]" to "Jane Doe (s4@example.com)"
And I click on "Add" "button"
And the "removeselect[]" select box should contain "Sandra Cole (s1@example.com)"
And the "removeselect[]" select box should contain "Jane Doe (s4@example.com)"
And the "removeselect[]" select box should not contain "John Smith (s2@example.com)"
And I trigger cron
And I am on "Course 001" course homepage
And I navigate to course participants
# Verifies students 1 and 4 are in the cohort and student 2 is not any more.
And the following should exist in the "participants" table:
| First name | Email address | Roles | Groups |
| Sandra Cole | s1@example.com | Student | Alpha1 cohort |
| Jane Doe | s4@example.com | Student | Alpha1 cohort |
And the following should not exist in the "participants" table:
| First name | Email address | Roles | Groups |
| John Smith | s2@example.com | Student | Alpha1 cohort |
@javascript
Scenario: Course cohort enrolment creates a new group
Given the following "users" exist:
| username | firstname | lastname | email |
| s3 | Bianca | McAfee | s3@example.com |
| s5 | Abigail | Wyatt | s5@example.com |
And the following "cohort members" exist:
| user | cohort |
| s3 | B1 |
| s5 | B1 |
When I log in as "teacher001"
And I add "Cohort sync" enrolment method in "Course 001" with:
| Cohort | B1 |
And I click on "Edit" "link" in the "Beta2" "table_row"
And I set the field "Add to group" to "Create new group"
And I click on "Save changes" "button"
And I set the field "Participants tertiary navigation" to "Groups"
And I set the field "groups[]" to "Beta2 cohort (2)"
Then the "members" select box should contain "Bianca McAfee (s3@example.com)"
And the "members" select box should contain "Abigail Wyatt (s5@example.com)"
@@ -0,0 +1,87 @@
@enrol @enrol_cohort
Feature: Unenrol action to disable course enrolment
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher001 | Teacher | 001 | teacher001@example.com |
| student001 | Student | 001 | student001@example.com |
| student002 | Student | 002 | student002@example.com |
| student003 | Student | 003 | student003@example.com |
| student004 | Student | 004 | student004@example.com |
And the following "cohorts" exist:
| name | idnumber | visible |
| System cohort | CVO | 1 |
And the following "cohort members" exist:
| user | cohort |
| student001 | CVO |
| student002 | CVO |
| student003 | CVO |
| student004 | CVO |
And the following "courses" exist:
| fullname | shortname | format | startdate |
| Course 001 | C001 | weeks | ##1 month ago## |
And the following "course enrolments" exist:
| user | course | role | timestart |
| teacher001 | C001 | editingteacher | ##1 month ago## |
@javascript @skip_chrome_zerosize
Scenario: Removing the user from the cohort will suspend the enrolment but keep the role
When I log in as "teacher001"
And I am on the "Course 001" "enrolment methods" page
And I select "Cohort sync" from the "Add method" singleselect
And I open the autocomplete suggestions list
Then "System cohort" "autocomplete_suggestions" should exist
And I set the field "Cohort" to "System cohort"
And I press "Add method"
And I am on the "Course 001" "enrolled users" page
And I should see "student001@example.com"
And I should see "student002@example.com"
And I should see "student003@example.com"
And I should see "student004@example.com"
And I log out
When I log in as "admin"
Then I navigate to "Plugins > Enrolments > Cohort sync" in site administration
And I select "Disable course enrolment" from the "External unenrol action" singleselect
And I press "Save changes"
And I navigate to "Users > Accounts > Cohorts" in site administration
When I press "Assign" action in the "System cohort" report row
And I set the field "removeselect_searchtext" to "Student 001"
And I set the field "Current users" to "Student 001 (student001@example.com)"
And I wait "1" seconds
And I press "Remove"
And I am on "Course 001" course homepage
And I navigate to course participants
And I should see "Suspended" in the "Student 001" "table_row"
And I should see "Active" in the "Student 002" "table_row"
And I should see "Active" in the "Student 003" "table_row"
And I should see "Active" in the "Student 004" "table_row"
@javascript @skip_chrome_zerosize
Scenario: Deleting non-empty cohort will suspend the enrolment but keep the role
When I log in as "teacher001"
And I am on the "Course 001" "enrolment methods" page
And I select "Cohort sync" from the "Add method" singleselect
And I open the autocomplete suggestions list
Then "System cohort" "autocomplete_suggestions" should exist
And I set the field "Cohort" to "System cohort"
And I press "Add method"
And I am on the "Course 001" "enrolled users" page
And I should see "student001@example.com"
And I should see "student002@example.com"
And I should see "student003@example.com"
And I should see "student004@example.com"
And I log out
When I log in as "admin"
Then I navigate to "Plugins > Enrolments > Cohort sync" in site administration
And I select "Disable course enrolment" from the "External unenrol action" singleselect
And I press "Save changes"
And I navigate to "Users > Accounts > Cohorts" in site administration
When I press "Delete" action in the "System cohort" report row
And I press "Continue"
And I am on "Course 001" course homepage
And I navigate to course participants
And I should see "Suspended" in the "Student 001" "table_row"
And I should see "Suspended" in the "Student 002" "table_row"
And I should see "Suspended" in the "Student 003" "table_row"
And I should see "Suspended" in the "Student 004" "table_row"
+481
View File
@@ -0,0 +1,481 @@
<?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 enrol_cohort;
use core\plugininfo\enrol;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot.'/cohort/lib.php');
require_once($CFG->dirroot.'/group/lib.php');
/**
* Contains tests for the cohort library.
*
* @package enrol_cohort
* @category test
* @copyright 2015 Adrian Greeve <adrian@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class lib_test extends \advanced_testcase {
/**
* Test that a new group with the name of the cohort is created.
*/
public function test_enrol_cohort_create_new_group(): void {
global $DB;
$this->resetAfterTest();
// Create a category.
$category = $this->getDataGenerator()->create_category();
// Create two courses.
$course = $this->getDataGenerator()->create_course(array('category' => $category->id));
$course2 = $this->getDataGenerator()->create_course(array('category' => $category->id));
// Create a cohort.
$cohort = $this->getDataGenerator()->create_cohort(array('context' => \context_coursecat::instance($category->id)->id));
// Run the function.
$groupid = enrol_cohort_create_new_group($course->id, $cohort->id);
// Check the results.
$group = $DB->get_record('groups', array('id' => $groupid));
// The group name should match the cohort name.
$this->assertEquals($cohort->name . ' cohort', $group->name);
// Group course id should match the course id.
$this->assertEquals($course->id, $group->courseid);
// Create a group that will have the same name as the cohort.
$groupdata = new \stdClass();
$groupdata->courseid = $course2->id;
$groupdata->name = $cohort->name . ' cohort';
groups_create_group($groupdata);
// Create a group for the cohort in course 2.
$groupid = enrol_cohort_create_new_group($course2->id, $cohort->id);
$groupinfo = $DB->get_record('groups', array('id' => $groupid));
// Check that the group name has been changed.
$this->assertEquals($cohort->name . ' cohort (2)', $groupinfo->name);
// Create another group that will have the same name as a generated cohort.
$groupdata = new \stdClass();
$groupdata->courseid = $course2->id;
$groupdata->name = $cohort->name . ' cohort (2)';
groups_create_group($groupdata);
// Create a group for the cohort in course 2.
$groupid = enrol_cohort_create_new_group($course2->id, $cohort->id);
$groupinfo = $DB->get_record('groups', array('id' => $groupid));
// Check that the group name has been changed.
$this->assertEquals($cohort->name . ' cohort (3)', $groupinfo->name);
}
/**
* Test for getting user enrolment actions.
*/
public function test_get_user_enrolment_actions(): void {
global $CFG, $PAGE;
$this->resetAfterTest();
// Set page URL to prevent debugging messages.
$PAGE->set_url('/enrol/editinstance.php');
$pluginname = 'cohort';
// Only enable the cohort enrol plugin.
$CFG->enrol_plugins_enabled = $pluginname;
$generator = $this->getDataGenerator();
// Get the enrol plugin.
$plugin = enrol_get_plugin($pluginname);
// Create a course.
$course = $generator->create_course();
// Enable this enrol plugin for the course.
$plugin->add_instance($course);
// Create a student.
$student = $generator->create_user();
// Enrol the student to the course.
$generator->enrol_user($student->id, $course->id, 'student', $pluginname);
// Teachers don't have enrol/cohort:unenrol capability by default. Login as admin for simplicity.
$this->setAdminUser();
require_once($CFG->dirroot . '/enrol/locallib.php');
$manager = new \course_enrolment_manager($PAGE, $course);
$userenrolments = $manager->get_user_enrolments($student->id);
$this->assertCount(1, $userenrolments);
$ue = reset($userenrolments);
$actions = $plugin->get_user_enrolment_actions($manager, $ue);
// Cohort-sync has no enrol actions for active students.
$this->assertCount(0, $actions);
// Enrol actions for a suspended student.
// Suspend the student.
$ue->status = ENROL_USER_SUSPENDED;
$actions = $plugin->get_user_enrolment_actions($manager, $ue);
// Cohort-sync has enrol actions for suspended students -- unenrol.
$this->assertCount(1, $actions);
}
public function test_enrol_cohort_unenrolaction_suspend_only(): void {
global $CFG, $DB, $PAGE;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->assertNotEmpty($studentrole);
// Setup a test course.
$course = $this->getDataGenerator()->create_course();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$user4 = $this->getDataGenerator()->create_user();
$cohort = $this->getDataGenerator()->create_cohort();
$cohortplugin->add_instance($course, ['customint1' => $cohort->id,
'roleid' => $studentrole->id]
);
cohort_add_member($cohort->id, $user1->id);
cohort_add_member($cohort->id, $user2->id);
cohort_add_member($cohort->id, $user3->id);
cohort_add_member($cohort->id, $user4->id);
// Test sync.
enrol_cohort_sync($trace, $course->id);
// All users should be enrolled.
$this->assertTrue(is_enrolled(\context_course::instance($course->id), $user1));
$this->assertTrue(is_enrolled(\context_course::instance($course->id), $user2));
$this->assertTrue(is_enrolled(\context_course::instance($course->id), $user3));
$this->assertTrue(is_enrolled(\context_course::instance($course->id), $user4));
// Remove cohort member.
cohort_remove_member($cohort->id, $user1->id);
$this->assertTrue(is_enrolled(\context_course::instance($course->id), $user1));
// Run the sync again.
enrol_cohort_sync($trace, $course->id);
$enrolid = $DB->get_field('enrol', 'id', ['enrol' => 'cohort', 'customint1' => $cohort->id]);
$ue = $DB->get_record('user_enrolments', ['enrolid' => $enrolid, 'userid' => $user1->id]);
// Check user is suspended.
$this->assertEquals($ue->status, ENROL_USER_SUSPENDED);
// Check that user4 still have student role.
$userrole = $DB->get_record('role_assignments', ['userid' => $user1->id]);
$this->assertNotEmpty($userrole);
$this->assertEquals($studentrole->id, $userrole->roleid);
// Delete the cohort.
cohort_delete_cohort($cohort);
// Run the sync again.
enrol_cohort_sync($trace, $course->id);
$ue = $DB->get_records('user_enrolments', ['enrolid' => $enrolid], '', 'userid, status, enrolid');
// Check users are suspended.
$this->assertEquals($ue[$user2->id]->status, ENROL_USER_SUSPENDED);
$this->assertEquals($ue[$user3->id]->status, ENROL_USER_SUSPENDED);
$this->assertEquals($ue[$user4->id]->status, ENROL_USER_SUSPENDED);
// Check that users still have student role.
$usersrole = $DB->get_records('role_assignments', ['itemid' => $enrolid], '', 'userid, roleid');
$this->assertNotEmpty($usersrole);
$this->assertEquals($studentrole->id, $usersrole[$user2->id]->roleid);
$this->assertEquals($studentrole->id, $usersrole[$user3->id]->roleid);
$this->assertEquals($studentrole->id, $usersrole[$user4->id]->roleid);
}
/**
* Test the behaviour of validate_plugin_data_context().
*
* @covers ::validate_plugin_data_context
*/
public function test_validate_plugin_data_context(): void {
$this->resetAfterTest();
$cohortplugin = enrol_get_plugin('cohort');
$cat = $this->getDataGenerator()->create_category();
$cat1 = $this->getDataGenerator()->create_category(['parent' => $cat->id]);
$cat2 = $this->getDataGenerator()->create_category(['parent' => $cat->id]);
$course = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'shortname' => 'ANON']);
$cohort1 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat1->id)->id,
'idnumber' => 'one',
]);
$cohort2 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat2->id)->id,
'idnumber' => 'two',
]);
$enrolmentdata = [
'customint1' => $cohort2->id,
'cohortidnumber' => $cohort2->idnumber,
];
$error = $cohortplugin->validate_plugin_data_context($enrolmentdata, $course->id);
$this->assertInstanceOf('lang_string', $error);
$this->assertEquals('contextcohortnotallowed', $error->get_identifier());
$enrolmentdata = [
'customint1' => $cohort1->id,
'cohortidnumber' => $cohort1->idnumber,
'courseid' => $course->id,
'id' => null,
'status' => ENROL_INSTANCE_ENABLED,
];
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$error = $cohortplugin->validate_plugin_data_context($enrolmentdata, $course->id);
$this->assertNull($error);
}
/**
* Test the behaviour of fill_enrol_custom_fields().
*
* @covers ::fill_enrol_custom_fields
*/
public function test_fill_enrol_custom_fields(): void {
$this->resetAfterTest();
$cohortplugin = enrol_get_plugin('cohort');
$cat = $this->getDataGenerator()->create_category();
$course = $this->getDataGenerator()->create_course(['category' => $cat->id, 'shortname' => 'ANON']);
$cohort = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat->id)->id,
'idnumber' => 'one',
]);
$group = $this->getDataGenerator()->create_group(['courseid' => $course->id]);
$enrolmentdata['cohortidnumber'] = $cohort->idnumber;
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$this->assertArrayHasKey('customint1', $enrolmentdata);
$this->assertEquals($cohort->id, $enrolmentdata['customint1']);
$this->assertArrayNotHasKey('customint2', $enrolmentdata);
$enrolmentdata['cohortidnumber'] = 'notexist';
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$this->assertArrayHasKey('customint1', $enrolmentdata);
$this->assertFalse($enrolmentdata['customint1']);
$this->assertArrayNotHasKey('customint2', $enrolmentdata);
$enrolmentdata['cohortidnumber'] = $cohort->idnumber;
$enrolmentdata['addtogroup'] = COHORT_NOGROUP;
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$this->assertArrayHasKey('customint1', $enrolmentdata);
$this->assertEquals($cohort->id, $enrolmentdata['customint1']);
$this->assertArrayHasKey('customint2', $enrolmentdata);
$this->assertEquals(COHORT_NOGROUP, $enrolmentdata['customint2']);
unset($enrolmentdata['addtogroup']);
$enrolmentdata['groupname'] = $group->name;
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$this->assertArrayHasKey('customint1', $enrolmentdata);
$this->assertEquals($cohort->id, $enrolmentdata['customint1']);
$this->assertArrayHasKey('customint2', $enrolmentdata);
$this->assertEquals($group->id, $enrolmentdata['customint2']);
$enrolmentdata['groupname'] = 'notexist';
$enrolmentdata = $cohortplugin->fill_enrol_custom_fields($enrolmentdata, $course->id);
$this->assertArrayHasKey('customint1', $enrolmentdata);
$this->assertEquals($cohort->id, $enrolmentdata['customint1']);
$this->assertArrayHasKey('customint2', $enrolmentdata);
$this->assertFalse($enrolmentdata['customint2']);
}
/**
* Test the behaviour of validate_enrol_plugin_data().
*
* @covers ::validate_enrol_plugin_data
*/
public function test_validate_enrol_plugin_data(): void {
$this->resetAfterTest();
$this->setAdminUser();
$cat = $this->getDataGenerator()->create_category();
$cat1 = $this->getDataGenerator()->create_category(['parent' => $cat->id]);
$cat2 = $this->getDataGenerator()->create_category(['parent' => $cat->id]);
$course = $this->getDataGenerator()->create_course(['category' => $cat1->id, 'shortname' => 'ANON']);
$group1 = $this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'Group 1']);
$cohort1 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat1->id)->id,
'idnumber' => 'one',
]);
$cohort2 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat2->id)->id,
'idnumber' => 'two',
]);
enrol::enable_plugin('cohort', false);
$cohortplugin = enrol_get_plugin('cohort');
// Plugin is disabled in system and cohort name is missing in csv.
$enrolmentdata = [];
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata);
$this->assertArrayHasKey('plugindisabled', $errors);
$this->assertArrayHasKey('missingmandatoryfields', $errors);
enrol::enable_plugin('cohort', true);
// Unknown cohort idnumber and missing role.
$enrolmentdata['cohortidnumber'] = 'test';
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata);
$this->assertArrayHasKey('missingmandatoryfields', $errors);
$this->assertArrayHasKey('unknowncohort', $errors);
// Non-valid 'addtogroup' option.
$enrolmentdata['cohortidnumber'] = $cohort1->idnumber;
$enrolmentdata['addtogroup'] = 2;
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertArrayHasKey('erroraddtogroup', $errors);
// Options 'addtogroup' and 'groupname' are not allowed together.
$enrolmentdata['addtogroup'] = 0;
$enrolmentdata['groupname'] = 'test';
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertArrayHasKey('erroraddtogroupgroupname', $errors);
// Cohort is not allowed on a given category context.
$enrolmentdata['cohortidnumber'] = $cohort2->idnumber;
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertArrayHasKey('contextnotallowed', $errors);
// Group does not exist.
unset($enrolmentdata['addtogroup']);
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertArrayHasKey('errorinvalidgroup', $errors);
// Unknown role.
$enrolmentdata['role'] = 'test';
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertArrayHasKey('unknownrole', $errors);
// Valid data when trying to create a group.
$enrolmentdata['cohortidnumber'] = $cohort1->idnumber;
$enrolmentdata['role'] = 'student';
$enrolmentdata['addtogroup'] = 1;
unset($enrolmentdata['groupname']);
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertEmpty($errors);
// Valid data when trying to add to existing group.
$enrolmentdata['groupname'] = $group1->name;
unset($enrolmentdata['addtogroup']);
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertEmpty($errors);
// Valid data when trying without group mode.
$enrolmentdata['addtogroup'] = 0;
unset($enrolmentdata['groupname']);
$errors = $cohortplugin->validate_enrol_plugin_data($enrolmentdata, $course->id);
$this->assertEmpty($errors);
}
/**
* Test the behaviour of find_instance().
*
* @covers ::find_instance
*/
public function test_find_instance(): void {
global $DB;
$this->resetAfterTest();
$cat = $this->getDataGenerator()->create_category();
$course = $this->getDataGenerator()->create_course(['category' => $cat->id, 'shortname' => 'ANON']);
$cohort1 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat->id)->id,
'idnumber' => 'one',
]);
$cohort2 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat->id)->id,
'idnumber' => 'two',
]);
$cohort3 = $this->getDataGenerator()->create_cohort([
'contextid' => \context_coursecat::instance($cat->id)->id,
'idnumber' => 'three',
]);
$studentrole = $DB->get_record('role', ['shortname' => 'student']);
$teacherrole = $DB->get_record('role', ['shortname' => 'teacher']);
$managerrole = $DB->get_record('role', ['shortname' => 'manager']);
$cohortplugin = enrol_get_plugin('cohort');
// Add three cohort enrol instances.
$instanceid1 = $cohortplugin->add_instance($course, ['customint1' => $cohort1->id, 'roleid' => $teacherrole->id]);
$instanceid2 = $cohortplugin->add_instance($course, ['customint1' => $cohort2->id, 'roleid' => $managerrole->id]);
$instanceid3 = $cohortplugin->add_instance($course, ['customint1' => $cohort2->id, 'roleid' => $studentrole->id]);
$instance1 = $DB->get_record('enrol', ['id' => $instanceid1]);
$instance2 = $DB->get_record('enrol', ['id' => $instanceid2]);
$enrolmentdata = [];
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertNull($instance);
// Unknown idnumber.
$enrolmentdata['cohortidnumber'] = 'test';
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertNull($instance);
// Unknown role.
$enrolmentdata['role'] = 'test';
$enrolmentdata['cohortidnumber'] = $cohort1->idnumber;
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertNull($instance);
// Cohort3 instance has not matching role and cohort.
$enrolmentdata['role'] = $teacherrole->shortname;
$enrolmentdata['cohortidnumber'] = $cohort3->idnumber;
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertNull($instance);
// Cohort2 instance has matching cohort, but not matching role.
$enrolmentdata['role'] = $teacherrole->shortname;
$enrolmentdata['cohortidnumber'] = $cohort2->idnumber;
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertNull($instance);
$enrolmentdata['role'] = $teacherrole->shortname;
$enrolmentdata['cohortidnumber'] = $cohort1->idnumber;
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertEquals($instance1->id, $instance->id);
$enrolmentdata['role'] = $managerrole->shortname;
$enrolmentdata['cohortidnumber'] = $cohort2->idnumber;
$instance = $cohortplugin->find_instance($enrolmentdata, $course->id);
$this->assertEquals($instance2->id, $instance->id);
}
}
@@ -0,0 +1,395 @@
<?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/>.
/**
* Base class for unit tests for enrol_cohort.
*
* @package enrol_cohort
* @category test
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace enrol_cohort\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\local\request\writer;
use core_privacy\local\request\approved_contextlist;
use enrol_cohort\privacy\provider;
/**
* Unit tests for the enrol_cohort implementation of the privacy API.
*
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends \core_privacy\tests\provider_testcase {
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$user1 = $this->getDataGenerator()->create_user();
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
cohort_add_member($cohort1->id, $user1->id);
enrol_cohort_sync($trace, $course1->id);
// Check if user1 is enrolled into course1 in group 1.
$this->assertEquals(1, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('groups_members', array(
'groupid' => $group1->id,
'userid' => $user1->id,
'component' => 'enrol_cohort')
));
// Check context course fro provider to user1.
$context = \context_course::instance($course1->id);
$contextlist = provider::get_contexts_for_userid($user1->id);
$this->assertEquals($context->id, $contextlist->current()->id);
}
/**
* Test that user data is exported correctly.
*/
public function test_export_user_data(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$user1 = $this->getDataGenerator()->create_user();
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
cohort_add_member($cohort1->id, $user1->id);
enrol_cohort_sync($trace, $course1->id);
// Check if user1 is enrolled into course1 in group 1.
$this->assertEquals(1, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('groups_members', array(
'groupid' => $group1->id,
'userid' => $user1->id,
'component' => 'enrol_cohort')
));
$this->setUser($user1);
$contextlist = provider::get_contexts_for_userid($user1->id);
$approvedcontextlist = new approved_contextlist($user1, 'enrol_cohort', $contextlist->get_contextids());
provider::export_user_data($approvedcontextlist);
foreach ($contextlist as $context) {
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$data = $writer->get_data([
get_string('pluginname', 'enrol_cohort'),
get_string('groups', 'core_group')
]);
$this->assertTrue($writer->has_any_data());
if ($context->contextlevel == CONTEXT_COURSE) {
$exportedgroups = $data->groups;
// User1 only belongs to group1 via enrol_cohort.
$this->assertCount(1, $exportedgroups);
$exportedgroup = reset($exportedgroups);
$this->assertEquals($group1->name, $exportedgroup->name);
}
}
}
/**
* Test for provider::delete_data_for_all_users_in_context().
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user3->id);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(
3,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
$coursecontext1 = \context_course::instance($course1->id);
provider::delete_data_for_all_users_in_context($coursecontext1);
$this->assertEquals(
0,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
}
/**
* Test for provider::delete_data_for_user().
*/
public function test_delete_data_for_user(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$course2 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$group2 = $this->getDataGenerator()->create_group(array('courseid' => $course2->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
$cohortplugin->add_instance($course2, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group2->id)
);
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
$this->getDataGenerator()->enrol_user($user3->id, $course1->id);
$this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
$this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user3->id));
cohort_add_member($cohort1->id, $user1->id);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(
3,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
$this->assertEquals(
1,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course2->id])
);
$this->setUser($user1);
$coursecontext1 = \context_course::instance($course1->id);
$coursecontext2 = \context_course::instance($course2->id);
$approvedcontextlist = new \core_privacy\tests\request\approved_contextlist($user1, 'enrol_cohort',
[$coursecontext1->id, $coursecontext2->id]);
provider::delete_data_for_user($approvedcontextlist);
// Check we have 2 users in groups because we are deleted user1.
$this->assertEquals(
2,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
// Check we have not users in groups.
$this->assertEquals(
0,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course2->id])
);
}
/**
* Test for provider::delete_data_for_users().
*/
public function test_delete_data_for_users(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$course2 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$group2 = $this->getDataGenerator()->create_group(array('courseid' => $course2->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
$cohortplugin->add_instance($course2, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group2->id)
);
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
$this->getDataGenerator()->enrol_user($user3->id, $course1->id);
$this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user2->id));
$this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user3->id));
cohort_add_member($cohort1->id, $user1->id);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(
3,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
$this->assertEquals(
1,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course2->id])
);
$coursecontext1 = \context_course::instance($course1->id);
$approveduserlist = new \core_privacy\local\request\approved_userlist($coursecontext1, 'enrol_cohort',
[$user1->id, $user2->id]);
provider::delete_data_for_users($approveduserlist);
// Check we have 2 users in groups because we have deleted user1.
// User2's membership is manual and is not as the result of a cohort enrolment.
$this->assertEquals(
2,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course1->id])
);
// Check that course2 is not touched.
$this->assertEquals(
1,
$DB->count_records_sql("SELECT COUNT(gm.id)
FROM {groups_members} gm
JOIN {groups} g ON gm.groupid = g.id
WHERE g.courseid = ?", [$course2->id])
);
}
/**
* Test for provider::get_users_in_context().
*/
public function test_get_users_in_context(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
$cohortplugin = enrol_get_plugin('cohort');
$cat1 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
$group1 = $this->getDataGenerator()->create_group(array('courseid' => $course1->id));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$cohort1 = $this->getDataGenerator()->create_cohort(
array('contextid' => \context_coursecat::instance($cat1->id)->id));
$cohortplugin->add_instance($course1, array(
'customint1' => $cohort1->id,
'roleid' => $studentrole->id,
'customint2' => $group1->id)
);
$user1 = $this->getDataGenerator()->create_user();
cohort_add_member($cohort1->id, $user1->id);
enrol_cohort_sync($trace, $course1->id);
// Check if user1 is enrolled into course1 in group 1.
$this->assertEquals(1, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('groups_members', array(
'groupid' => $group1->id,
'userid' => $user1->id,
'component' => 'enrol_cohort')
));
$context = \context_course::instance($course1->id);
$userlist = new \core_privacy\local\request\userlist($context, 'enrol_cohort');
\enrol_cohort\privacy\provider::get_users_in_context($userlist);
$this->assertEquals([$user1->id], $userlist->get_userids());
}
}
+749
View File
@@ -0,0 +1,749 @@
<?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 enrol_cohort;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot.'/enrol/cohort/locallib.php');
require_once($CFG->dirroot.'/cohort/lib.php');
require_once($CFG->dirroot.'/group/lib.php');
/**
* Cohort enrolment sync functional test.
*
* @package enrol_cohort
* @category test
* @copyright 2012 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class sync_test extends \advanced_testcase {
protected function enable_plugin() {
$enabled = enrol_get_plugins(true);
$enabled['cohort'] = true;
$enabled = array_keys($enabled);
set_config('enrol_plugins_enabled', implode(',', $enabled));
}
protected function disable_plugin() {
$enabled = enrol_get_plugins(true);
unset($enabled['cohort']);
$enabled = array_keys($enabled);
set_config('enrol_plugins_enabled', implode(',', $enabled));
}
public function test_handler_sync(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
// Setup a few courses and categories.
$cohortplugin = enrol_get_plugin('cohort');
$manualplugin = enrol_get_plugin('manual');
$studentrole = $DB->get_record('role', array('shortname'=>'student'));
$this->assertNotEmpty($studentrole);
$teacherrole = $DB->get_record('role', array('shortname'=>'teacher'));
$this->assertNotEmpty($teacherrole);
$managerrole = $DB->get_record('role', array('shortname'=>'manager'));
$this->assertNotEmpty($managerrole);
$cat1 = $this->getDataGenerator()->create_category();
$cat2 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course2 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course3 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$course4 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$maninstance1 = $DB->get_record('enrol', array('courseid'=>$course1->id, 'enrol'=>'manual'), '*', MUST_EXIST);
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$user4 = $this->getDataGenerator()->create_user();
$user5 = $this->getDataGenerator()->create_user();
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$cohort2 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat2->id)->id));
$cohort3 = $this->getDataGenerator()->create_cohort();
$cohort4 = $this->getDataGenerator()->create_cohort();
$this->enable_plugin();
$manualplugin->enrol_user($maninstance1, $user4->id, $teacherrole->id);
$manualplugin->enrol_user($maninstance1, $user3->id, $managerrole->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort2->id, 'roleid'=>$teacherrole->id));
$cohortinstance2 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course2, array('customint1'=>$cohort2->id, 'roleid'=>$studentrole->id));
$cohortinstance3 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course2, array('customint1' => $cohort2->id, 'roleid' => $studentrole->id, 'status' => ENROL_INSTANCE_DISABLED));
$cohortinstance4 = $DB->get_record('enrol', array('id' => $id));
$id = $cohortplugin->add_instance($course3, array('customint1' => $cohort4->id, 'roleid' => $studentrole->id));
$cohortinstance5 = $DB->get_record('enrol', array('id' => $id));
// Test cohort member add event.
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
$this->assertEquals(5, $DB->count_records('user_enrolments', array()));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user1->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user2->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user4->id)));
$this->assertEquals(5, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user4->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
cohort_add_member($cohort2->id, $user3->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance3->id, 'userid'=>$user3->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance4->id, 'userid' => $user3->id)));
$this->assertEquals(7, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course2->id)->id, 'userid'=>$user3->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance3->id)));
cohort_add_member($cohort3->id, $user3->id);
cohort_add_member($cohort4->id, $user5->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
// Test cohort remove action.
$this->assertEquals(ENROL_EXT_REMOVED_UNENROL, $cohortplugin->get_config('unenrolaction'));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
cohort_remove_member($cohort1->id, $user2->id);
cohort_remove_member($cohort1->id, $user4->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user4->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertEquals(ENROL_USER_SUSPENDED, $DB->get_field('user_enrolments', 'status',
array('userid' => $user2->id, 'enrolid' => $cohortinstance1->id)));
$this->assertEquals(ENROL_USER_SUSPENDED, $DB->get_field('user_enrolments', 'status',
array('userid' => $user4->id, 'enrolid' => $cohortinstance1->id)));
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user2->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user4->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
cohort_remove_member($cohort1->id, $user2->id);
cohort_remove_member($cohort1->id, $user4->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user2->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user4->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$this->assertEquals(ENROL_USER_SUSPENDED, $DB->get_field('user_enrolments', 'status',
array('userid' => $user2->id, 'enrolid' => $cohortinstance1->id)));
$this->assertEquals(ENROL_USER_SUSPENDED, $DB->get_field('user_enrolments', 'status',
array('userid' => $user4->id, 'enrolid' => $cohortinstance1->id)));
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user2->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user4->id, 'roleid' => $studentrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
cohort_remove_member($cohort1->id, $user2->id);
cohort_remove_member($cohort1->id, $user4->id);
$this->assertEquals(6, $DB->count_records('user_enrolments', array()));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user2->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user4->id)));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user4->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
cohort_remove_member($cohort2->id, $user3->id);
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance3->id, 'userid'=>$user3->id)));
$this->assertEquals(4, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course2->id)->id, 'userid'=>$user3->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance3->id)));
// Test cohort deleting.
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
cohort_add_member($cohort2->id, $user3->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
cohort_delete_cohort($cohort4);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$cohortinstance5 = $DB->get_record('enrol', array('id' => $cohortinstance5->id), '*', MUST_EXIST);
$this->assertEquals(ENROL_INSTANCE_DISABLED, $cohortinstance5->status);
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
cohort_delete_cohort($cohort2);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$cohortinstance2 = $DB->get_record('enrol', array('id'=>$cohortinstance2->id), '*', MUST_EXIST);
$cohortinstance3 = $DB->get_record('enrol', array('id'=>$cohortinstance3->id), '*', MUST_EXIST);
$this->assertEquals(ENROL_INSTANCE_DISABLED, $cohortinstance2->status);
$this->assertEquals(ENROL_INSTANCE_DISABLED, $cohortinstance3->status);
$this->assertFalse($DB->record_exists('role_assignments', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance3->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
cohort_delete_cohort($cohort1);
$this->assertEquals(5, $DB->count_records('user_enrolments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('enrol', array('id'=>$cohortinstance1->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
// Cleanup after previous test (remove the extra user_enrolment).
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
// Test group sync.
$id = groups_create_group((object)array('name'=>'Group 1', 'courseid'=>$course1->id));
$group1 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$id = groups_create_group((object)array('name'=>'Group 2', 'courseid'=>$course1->id));
$group2 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id, 'customint2'=>$group1->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
$this->assertTrue(is_enrolled(\context_course::instance($course1->id), $user4));
$this->assertTrue(groups_add_member($group1, $user4));
$this->assertTrue(groups_add_member($group2, $user4));
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_add_member($cohort1->id, $user1->id);
$this->assertTrue(groups_is_member($group1->id, $user1->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user1->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
cohort_add_member($cohort1->id, $user4->id);
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
cohort_remove_member($cohort1->id, $user1->id);
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_remove_member($cohort1->id, $user4->id);
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertTrue(groups_is_member($group2->id, $user4->id));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
cohort_add_member($cohort1->id, $user1->id);
cohort_remove_member($cohort1->id, $user1->id);
$this->assertTrue(groups_is_member($group1->id, $user1->id));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
cohort_add_member($cohort1->id, $user1->id);
cohort_remove_member($cohort1->id, $user1->id);
$this->assertTrue(groups_is_member($group1->id, $user1->id));
// Test deleting of instances.
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user3->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertEquals(5, $DB->count_records('groups_members', array()));
$this->assertEquals(3, $DB->count_records('groups_members', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$cohortplugin->delete_instance($cohortinstance1);
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
$this->assertEquals(0, $DB->count_records('role_assignments', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertEquals(2, $DB->count_records('groups_members', array()));
$this->assertEquals(0, $DB->count_records('groups_members', array('component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
}
public function test_sync_course(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
// Setup a few courses and categories.
$cohortplugin = enrol_get_plugin('cohort');
$manualplugin = enrol_get_plugin('manual');
$studentrole = $DB->get_record('role', array('shortname'=>'student'));
$this->assertNotEmpty($studentrole);
$teacherrole = $DB->get_record('role', array('shortname'=>'teacher'));
$this->assertNotEmpty($teacherrole);
$managerrole = $DB->get_record('role', array('shortname'=>'manager'));
$this->assertNotEmpty($managerrole);
$cat1 = $this->getDataGenerator()->create_category();
$cat2 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course2 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course3 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$course4 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$maninstance1 = $DB->get_record('enrol', array('courseid'=>$course1->id, 'enrol'=>'manual'), '*', MUST_EXIST);
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$user4 = $this->getDataGenerator()->create_user();
$user5 = $this->getDataGenerator()->create_user();
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$cohort2 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat2->id)->id));
$cohort3 = $this->getDataGenerator()->create_cohort();
$cohort4 = $this->getDataGenerator()->create_cohort();
$this->disable_plugin(); // Prevents event sync.
$manualplugin->enrol_user($maninstance1, $user4->id, $teacherrole->id);
$manualplugin->enrol_user($maninstance1, $user3->id, $managerrole->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort2->id, 'roleid'=>$teacherrole->id));
$cohortinstance2 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course2, array('customint1'=>$cohort2->id, 'roleid'=>$studentrole->id));
$cohortinstance3 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course2, array('customint1' => $cohort2->id, 'roleid' => $studentrole->id, 'status' => ENROL_INSTANCE_DISABLED));
$cohortinstance4 = $DB->get_record('enrol', array('id' => $id));
$id = $cohortplugin->add_instance($course3, array('customint1' => $cohort4->id, 'roleid' => $studentrole->id));
$cohortinstance5 = $DB->get_record('enrol', array('id' => $id));
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
cohort_add_member($cohort2->id, $user3->id);
cohort_add_member($cohort3->id, $user3->id);
cohort_add_member($cohort4->id, $user5->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
// Test sync of one course only.
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
$this->enable_plugin();
enrol_cohort_sync($trace, $course2->id);
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
$this->assertEquals(3, $DB->count_records('user_enrolments', array()));
$DB->delete_records('cohort_members', array('cohortid'=>$cohort3->id)); // Use low level DB api to prevent events!
$DB->delete_records('cohort', array('id'=>$cohort3->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user1->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user2->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user4->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance4->id, 'userid' => $user3->id)));
$this->assertEquals(7, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user4->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
// Use low level DB api to prevent events!
$DB->delete_records('cohort_members', array('cohortid' => $cohort2->id, 'userid' => $user3->id));
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
$this->assertEquals(7, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user3->id, 'roleid' => $teacherrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id)));
cohort_add_member($cohort2->id, $user3->id);
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
$DB->delete_records('cohort_members', array('cohortid'=>$cohort2->id, 'userid'=>$user3->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
$DB->delete_records('cohort_members', array('cohortid'=>$cohort1->id, 'userid'=>$user1->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(5, $DB->count_records('user_enrolments', array()));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user1->id)));
$this->assertEquals(5, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
$DB->delete_records('cohort_members', array('cohortid' => $cohort4->id));
$DB->delete_records('cohort', array('id' => $cohort4->id));
enrol_cohort_sync($trace, $course3->id);
$this->assertEquals(5, $DB->count_records('user_enrolments', array()));
$this->assertEquals(5, $DB->count_records('role_assignments', array()));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
$DB->delete_records('cohort_members', array('cohortid'=>$cohort1->id)); // Use low level DB api to prevent events!
$DB->delete_records('cohort', array('id'=>$cohort1->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(5, $DB->count_records('user_enrolments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(3, $DB->count_records('user_enrolments', array()));
$this->assertEquals(3, $DB->count_records('role_assignments', array()));
// Test group sync.
$this->disable_plugin(); // No event sync.
// Trigger sync to remove left over role assignments.
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$id = groups_create_group((object)array('name'=>'Group 1', 'courseid'=>$course1->id));
$group1 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$id = groups_create_group((object)array('name'=>'Group 2', 'courseid'=>$course1->id));
$group2 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id, 'customint2'=>$group1->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$this->assertTrue(is_enrolled(\context_course::instance($course1->id), $user4));
$this->assertTrue(groups_add_member($group1, $user4));
$this->assertTrue(groups_add_member($group2, $user4));
$this->enable_plugin(); // No event sync.
$this->assertEquals(3, $DB->count_records('user_enrolments', array()));
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user4->id);
cohort_add_member($cohort2->id, $user4->id);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(7, $DB->count_records('user_enrolments', array()));
// This used to be 7 - but now add_instance triggers an immediate sync.
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertTrue(groups_is_member($group1->id, $user1->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user1->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$cohortinstance1->customint2 = $group2->id;
$DB->update_record('enrol', $cohortinstance1);
enrol_cohort_sync($trace, $course1->id);
$this->assertFalse(groups_is_member($group1->id, $user1->id));
$this->assertTrue(groups_is_member($group2->id, $user1->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group2->id, 'userid'=>$user1->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertTrue(groups_is_member($group2->id, $user4->id));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group2->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
cohort_remove_member($cohort1->id, $user1->id);
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_remove_member($cohort1->id, $user4->id);
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertTrue(groups_is_member($group2->id, $user4->id));
}
public function test_sync_all_courses(): void {
global $DB;
$this->resetAfterTest();
$trace = new \null_progress_trace();
// Setup a few courses and categories.
$cohortplugin = enrol_get_plugin('cohort');
$manualplugin = enrol_get_plugin('manual');
$studentrole = $DB->get_record('role', array('shortname'=>'student'));
$this->assertNotEmpty($studentrole);
$teacherrole = $DB->get_record('role', array('shortname'=>'teacher'));
$this->assertNotEmpty($teacherrole);
$managerrole = $DB->get_record('role', array('shortname'=>'manager'));
$this->assertNotEmpty($managerrole);
$cat1 = $this->getDataGenerator()->create_category();
$cat2 = $this->getDataGenerator()->create_category();
$course1 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course2 = $this->getDataGenerator()->create_course(array('category'=>$cat1->id));
$course3 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$course4 = $this->getDataGenerator()->create_course(array('category'=>$cat2->id));
$maninstance1 = $DB->get_record('enrol', array('courseid'=>$course1->id, 'enrol'=>'manual'), '*', MUST_EXIST);
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
$user4 = $this->getDataGenerator()->create_user();
$user5 = $this->getDataGenerator()->create_user();
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$cohort2 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat2->id)->id));
$cohort3 = $this->getDataGenerator()->create_cohort();
$cohort4 = $this->getDataGenerator()->create_cohort();
$this->disable_plugin(); // Prevents event sync.
$manualplugin->enrol_user($maninstance1, $user4->id, $teacherrole->id);
$manualplugin->enrol_user($maninstance1, $user3->id, $managerrole->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort2->id, 'roleid'=>$teacherrole->id));
$cohortinstance2 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course2, array('customint1'=>$cohort2->id, 'roleid'=>$studentrole->id));
$cohortinstance3 = $DB->get_record('enrol', array('id'=>$id));
$id = $cohortplugin->add_instance($course3, array('customint1' => $cohort4->id, 'roleid' => $studentrole->id));
$cohortinstance4 = $DB->get_record('enrol', array('id' => $id));
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort1->id, $user4->id);
cohort_add_member($cohort2->id, $user3->id);
cohort_add_member($cohort3->id, $user3->id);
cohort_add_member($cohort4->id, $user5->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
// Test sync of one course only.
enrol_cohort_sync($trace, null);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertEquals(2, $DB->count_records('user_enrolments', array()));
$this->enable_plugin();
enrol_cohort_sync($trace, null);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user1->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user2->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user4->id)));
$this->assertTrue($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user2->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user4->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
$DB->delete_records('cohort_members', array('cohortid' => $cohort2->id, 'userid' => $user3->id));
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue($DB->record_exists('role_assignments', array(
'contextid' => \context_course::instance($course1->id)->id,
'userid' => $user3->id, 'roleid' => $teacherrole->id,
'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id)));
cohort_add_member($cohort2->id, $user3->id);
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
$DB->delete_records('cohort_members', array('cohortid'=>$cohort2->id, 'userid'=>$user3->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(7, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
$DB->delete_records('cohort_members', array('cohortid'=>$cohort1->id, 'userid'=>$user1->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(6, $DB->count_records('user_enrolments', array()));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance2->id, 'userid'=>$user3->id)));
$this->assertFalse($DB->record_exists('user_enrolments', array('enrolid'=>$cohortinstance1->id, 'userid'=>$user1->id)));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user3->id, 'roleid'=>$teacherrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance2->id)));
$this->assertFalse($DB->record_exists('role_assignments', array('contextid'=>\context_course::instance($course1->id)->id, 'userid'=>$user1->id, 'roleid'=>$studentrole->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
$DB->delete_records('cohort_members', array('cohortid' => $cohort4->id)); // Use low level DB api to prevent events!
$DB->delete_records('cohort', array('id' => $cohort4->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course3->id);
$this->assertEquals(6, $DB->count_records('user_enrolments', array()));
$this->assertEquals(6, $DB->count_records('role_assignments', array()));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
$DB->delete_records('cohort_members', array('cohortid' => $cohort1->id)); // Use low level DB api to prevent events!
$DB->delete_records('cohort', array('id' => $cohort1->id)); // Use low level DB api to prevent events!
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(6, $DB->count_records('user_enrolments', array()));
$this->assertEquals(4, $DB->count_records('role_assignments', array()));
$cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
$this->assertEquals(4, $DB->count_records('role_assignments', array()));
// Test group sync.
$this->disable_plugin(); // No event sync
// Trigger sync to remove extra role assignments.
enrol_cohort_sync($trace, $course1->id);
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$id = groups_create_group((object)array('name'=>'Group 1', 'courseid'=>$course1->id));
$group1 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$id = groups_create_group((object)array('name'=>'Group 2', 'courseid'=>$course1->id));
$group2 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$id = groups_create_group((object)array('name'=>'Group 2', 'courseid'=>$course2->id));
$group3 = $DB->get_record('groups', array('id'=>$id), '*', MUST_EXIST);
$cohort1 = $this->getDataGenerator()->create_cohort(array('contextid'=>\context_coursecat::instance($cat1->id)->id));
$id = $cohortplugin->add_instance($course1, array('customint1'=>$cohort1->id, 'roleid'=>$studentrole->id, 'customint2'=>$group1->id));
$cohortinstance1 = $DB->get_record('enrol', array('id'=>$id));
$this->assertTrue(groups_add_member($group1, $user4));
$this->assertTrue(groups_add_member($group2, $user4));
$this->assertEquals(4, $DB->count_records('user_enrolments', array()));
$this->assertEquals(2, $DB->count_records('role_assignments', array()));
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user4->id);
cohort_add_member($cohort2->id, $user4->id);
cohort_add_member($cohort2->id, $user3->id);
$this->enable_plugin();
enrol_cohort_sync($trace, null);
$this->assertEquals(8, $DB->count_records('user_enrolments', array()));
$this->assertEquals(8, $DB->count_records('role_assignments', array()));
$this->assertTrue(groups_is_member($group1->id, $user1->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user1->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(is_enrolled(\context_course::instance($course1->id), $user4));
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(is_enrolled(\context_course::instance($course2->id), $user3));
$this->assertFalse(groups_is_member($group3->id, $user3->id));
$cohortinstance1->customint2 = $group2->id;
$DB->update_record('enrol', $cohortinstance1);
$cohortinstance3->customint2 = $group3->id;
$DB->update_record('enrol', $cohortinstance3);
enrol_cohort_sync($trace, null);
$this->assertFalse(groups_is_member($group1->id, $user1->id));
$this->assertTrue(groups_is_member($group2->id, $user1->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group2->id, 'userid'=>$user1->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertTrue(groups_is_member($group2->id, $user4->id));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group1->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertFalse($DB->record_exists('groups_members', array('groupid'=>$group2->id, 'userid'=>$user4->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance1->id)));
$this->assertTrue(groups_is_member($group3->id, $user3->id));
$this->assertTrue($DB->record_exists('groups_members', array('groupid'=>$group3->id, 'userid'=>$user3->id, 'component'=>'enrol_cohort', 'itemid'=>$cohortinstance3->id)));
cohort_remove_member($cohort1->id, $user1->id);
$this->assertFalse(groups_is_member($group1->id, $user1->id));
cohort_remove_member($cohort1->id, $user4->id);
$this->assertTrue(groups_is_member($group1->id, $user4->id));
$this->assertTrue(groups_is_member($group2->id, $user4->id));
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Cohort enrolment plugin version specification.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'enrol_cohort'; // Full name of the plugin (used for diagnostics)