Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue #42: add user enrolment condition #93

Merged
merged 1 commit into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,12 @@ Conditions are simple predicates which assert something about a user in the syst
* Cohort membership (if a user is a member of cohort(s)).
* Course completed (if a user has completed a course).
* Course not completed (if a user has not completed a course).
* User last login (time since a user last logged in).
* User created time (time since a user was created).
* User standard profile fields (e.g. first name, last name, username, auth method and etc).
* User custom profile fields (text and menu types are supported).
* User enrolment (if a user is enrolled into a course).
* User last login (time since a user last logged in).
* User role (if a user has a role in a given context)
* User standard profile fields (e.g. first name, last name, username, auth method and etc).

## Rules

Expand Down
339 changes: 339 additions & 0 deletions classes/local/tool_dynamic_cohorts/condition/user_enrolment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,339 @@
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.

namespace tool_dynamic_cohorts\local\tool_dynamic_cohorts\condition;

use tool_dynamic_cohorts\condition_base;
use tool_dynamic_cohorts\condition_sql;
use context_course;

/**
* Condition based on user's enrolment.
*
* @package tool_dynamic_cohorts
* @copyright 2024 Catalyst IT
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class user_enrolment extends condition_base {

/**
* Operator for not enrolled users.
*/
public const OPERATOR_NOT_ENROLLED = 0;

/**
* Operator for enrolled users.
*/
public const OPERATOR_ENROLLED = 1;

/**
* Condition name.
*
* @return string
*/
public function get_name(): string {
return get_string('condition:user_enrolment', 'tool_dynamic_cohorts');
}

/**
* Gets a list of all roles.
*
* @return array
*/
protected function get_roles(): array {
$roles = [
0 => get_string('any'),
];
foreach (role_get_names() as $role) {
if ($role->archetype === 'guest') {
continue;
}
$roles[$role->id] = $role->localname;
}

return $roles;
}

/**
* Returns a list of enrolment methods.
*
* @return array
*/
protected function get_enrolment_methods(): array {
$enrolmentmethods = ['' => get_string('any')];
foreach (enrol_get_plugins(false) as $method) {
$name = $method->get_name();
$enrolmentmethods[$name] = get_string('pluginname', 'enrol_' . $name);
}

return $enrolmentmethods;
}

/**
* Gets a list of operators.
*
* @return array A list of operators.
*/
protected function get_operators(): array {
return [
self::OPERATOR_ENROLLED => get_string('enrolled', 'tool_dynamic_cohorts'),
self::OPERATOR_NOT_ENROLLED => get_string('notenrolled', 'tool_dynamic_cohorts'),
];
}

/**
* Add config form elements.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_add(\MoodleQuickForm $mform): void {
// Operator.
$mform->addElement(
'select',
'operator',
get_string('operator', 'tool_dynamic_cohorts'),
$this->get_operators()
);

// Course.
$mform->addElement('course', 'courseid', get_string('course'));
$mform->setType('courseid', PARAM_INT);
$mform->hideIf('courseid', 'contextlevel', 'in', [CONTEXT_SYSTEM, CONTEXT_COURSECAT]);

// Enrolment method.
$mform->addElement(
'select',
'enrolmethod',
get_string('enrolmethod', 'tool_dynamic_cohorts'),
$this->get_enrolment_methods()
);
$mform->setType('enrolmethod', PARAM_COMPONENT);

// Role.
$mform->addElement('select', 'roleid', get_string('role'), $this->get_roles());
$mform->setType('roleid', PARAM_INT);
}

/**
* Validate config form elements.
*
* @param array $data Data to validate.
* @return array
*/
public function config_form_validate(array $data): array {
$errors = [];

if (empty($data['courseid'])) {
$errors['courseid'] = get_string('required');
}

return $errors;
}

/**
* Gets operator.
*
* @return int
*/
protected function get_operator_value(): int {
return $this->get_config_data()['operator'] ?? self::OPERATOR_ENROLLED;
}

/**
* Gets configured role ID.
*
* @return int
*/
protected function get_roleid_value(): int {
return $this->get_config_data()['roleid'] ?? 0;
}

/**
* Gets configured enrolment method.
*
* @return string
*/
protected function get_enrolment_method_value(): string {
return $this->get_config_data()['enrolmethod'] ?? '';
}

/**
* Gets configured course ID.
*
* @return int
*/
protected function get_courseid_value(): int {
return $this->get_config_data()['courseid'] ?? 0;
}

/**
* Human-readable description of the configured condition.
*
* @return string
*/
public function get_config_description(): string {
global $DB;

$coursename = $DB->get_field('course', 'fullname', ['id' => $this->get_courseid_value()]);
$coursename = format_string($coursename, true, ['context' => \context_system::instance(), 'escape' => false]);

return get_string('condition:user_enrolment_description', 'tool_dynamic_cohorts', (object) [
'operator' => strtolower($this->get_operators()[$this->get_operator_value()]),
'role' => $this->get_roles()[$this->get_roleid_value()],
'coursename' => $coursename,
'courseid' => $this->get_courseid_value(),
'enrolmethod' => $this->get_enrolment_methods()[$this->get_enrolment_method_value()],
]);
}

/**
* Human-readable description of the broken condition.
*
* @return string
*/
public function get_broken_description(): string {
global $DB;

// Missing role.
if (!array_key_exists($this->get_roleid_value(), $this->get_roles())) {
return get_string('missingrole', 'tool_dynamic_cohorts');
}

// Missing course.
if (!$DB->get_record('course', ['id' => $this->get_courseid_value()])) {
return get_string('missingcourse', 'tool_dynamic_cohorts');
}

// Missing enrolment method.
if (!array_key_exists($this->get_enrolment_method_value(), $this->get_enrolment_methods())) {
return get_string('missingenrolmentmethod', 'tool_dynamic_cohorts', $this->get_enrolment_method_value());
}

return parent::get_broken_description();
}

/**
* Gets SQL data for building SQL.
*
* @return condition_sql
*/
public function get_sql(): condition_sql {
$sql = new condition_sql('', '1=0', []);

if (!$this->is_broken()) {
$join = '';
$params = [];

// Enrolment tables.
$uetable = condition_sql::generate_table_alias();
$enroltable = condition_sql::generate_table_alias();

// Course parameter.
$courseidparam = condition_sql::generate_param_alias();
$params[$courseidparam] = $this->get_courseid_value();

// In case we are filtering by enrolment method.
$enrolmethodwhere = '';
$enrolmethod = $this->get_enrolment_method_value();
if (!empty($enrolmethod)) {
$enrolmethodparam = condition_sql::generate_param_alias();
$params[$enrolmethodparam] = $enrolmethod;
$enrolmethodwhere = "AND $enroltable.enrol = :{$enrolmethodparam}";
}

// In case we are filtering by role.
$rolesql = '';
$rolewhere = '';
$roleid = $this->get_roleid_value();
if (!empty($roleid)) {
$outertable = condition_sql::generate_table_alias();
$ratable = condition_sql::generate_table_alias();
$roleidparam = condition_sql::generate_param_alias();
$params[$roleidparam] = $roleid;

$context = context_course::instance($this->get_courseid_value());
$contexidtparam = condition_sql::generate_param_alias();
$params[$contexidtparam] = $context->id;

$rolesql = "LEFT JOIN (SELECT $ratable.userid
FROM {role_assignments} $ratable
WHERE $ratable.roleid = :{$roleidparam}
AND $ratable.contextid = :{$contexidtparam}
) {$outertable} ON {$uetable}.userid = {$outertable}.userid ";

$rolewhere = "AND {$outertable}.userid is NOT NULL";
}

$operator = $this->get_operator_value() == self::OPERATOR_ENROLLED ? 'EXISTS' : 'NOT EXISTS';

$where = "{$operator} (SELECT 1 FROM {user_enrolments} {$uetable}
JOIN {enrol} {$enroltable} ON ({$enroltable}.id = {$uetable}.enrolid AND {$enroltable}.status = 0)
$rolesql
WHERE {$uetable}.userid = u.id
AND $enroltable.courseid = :{$courseidparam}
AND {$uetable}.status = 0
$enrolmethodwhere
$rolewhere)";

$sql = new condition_sql($join, $where, $params);
}

return $sql;
}

/**
* Is condition broken.
*
* @return bool
*/
public function is_broken(): bool {
global $DB;

if ($this->get_config_data()) {
// Check role exists.
if (!array_key_exists($this->get_roleid_value(), $this->get_roles())) {
return true;
}

// Check course exists.
if (!$DB->get_record('course', ['id' => $this->get_courseid_value()])) {
return true;
}

// Check enrolment method exists.
if (!array_key_exists($this->get_enrolment_method_value(), $this->get_enrolment_methods())) {
return true;
}
}

return false;
}

/**
* Gets a list of event classes the condition will be triggered on.
*
* @return string[]
*/
public function get_events(): array {
return [
'core\event\role_assigned',
'core\event\role_unassigned',
'core\event\user_enrolment_created',
'core\event\user_enrolment_updated',
'core\event\user_enrolment_deleted',
];
}
}
6 changes: 6 additions & 0 deletions lang/en/tool_dynamic_cohorts.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@
$string['condition:course_not_completed'] = 'Course not completed';
$string['condition:course_not_completed_description'] = 'Users who have not completed course "{$a->course}"';
$string['condition:profile_field_description'] = 'Users with {$a->field} {$a->fieldoperator} {$a->fieldvalue}';
$string['condition:user_enrolment'] = 'User enrolment';
$string['condition:user_enrolment_description'] = 'Users who are {$a->operator} into course "{$a->coursename}" (id {$a->courseid}) with "{$a->role}" role using "{$a->enrolmethod}" enrolment method';
$string['condition:user_last_login'] = 'User last login';
$string['condition:user_created'] = 'User created time';
$string['condition:user_profile'] = 'User standard profile field';
Expand All @@ -82,6 +84,8 @@
$string['edit_rule'] = 'Edit rule';
$string['enabled'] = 'Enabled';
$string['enable_confirm'] = 'Are you sure you want to enable rule {$a}?';
$string['enrolmethod'] = 'Enrolment method';
$string['enrolled'] = 'Enrolled';
$string['ever'] = 'Ever';
$string['everloggedin'] = 'Users who have logged in at least once';
$string['event:conditioncreated'] = 'Condition created';
Expand Down Expand Up @@ -112,11 +116,13 @@
$string['matchingusers'] = 'Matching users';
$string['missingcourse'] = 'Missing course';
$string['missingcoursecat'] = 'Missing course category';
$string['missingenrolmentmethod'] = 'Missing enrolment method {$a}';
$string['missingrole'] = 'Missing role';
$string['name'] = 'Rule name';
$string['name_help'] = 'A human readable name of this rule.';
$string['never'] = 'Never';
$string['neverloggedin'] = 'Users who have never logged in';
$string['notenrolled'] = 'Not enrolled';
$string['operator'] = 'Operator';
$string['or'] = 'OR';
$string['pleaseselectcohort'] = 'Please select a cohort';
Expand Down
Loading
Loading