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
+275
View File
@@ -0,0 +1,275 @@
<?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/>.
/**
* Class exposing the api for the cohortroles tool.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles;
use stdClass;
use context_system;
use core_competency\invalid_persistent_exception;
/**
* Class for doing things with cohort roles.
*
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api {
/**
* Create a cohort role assignment from a record containing all the data for the class.
*
* Requires moodle/role:manage capability at the system context.
*
* @param stdClass $record Record containing all the data for an instance of the class.
* @return competency
*/
public static function create_cohort_role_assignment(stdClass $record) {
$cohortroleassignment = new cohort_role_assignment(0, $record);
$context = context_system::instance();
// First we do a permissions check.
require_capability('moodle/role:manage', $context);
// Validate before we check for existing records.
if (!$cohortroleassignment->is_valid()) {
throw new invalid_persistent_exception($cohortroleassignment->get_errors());
}
$existing = cohort_role_assignment::get_record((array) $record);
if (!empty($existing)) {
return false;
} else {
// OK - all set.
$cohortroleassignment->create();
}
return $cohortroleassignment;
}
/**
* Delete a cohort role assignment by id.
*
* Requires moodle/role:manage capability at the system context.
*
* @param int $id The record to delete. This will also remove this role from the user for all users in the system.
* @return boolean
*/
public static function delete_cohort_role_assignment($id) {
$cohortroleassignment = new cohort_role_assignment($id);
$context = context_system::instance();
// First we do a permissions check.
require_capability('moodle/role:manage', $context);
// OK - all set.
return $cohortroleassignment->delete();
}
/**
* Perform a search based on the provided filters and return a paginated list of records.
*
* Requires moodle/role:manage capability at the system context.
*
* @param string $sort The column to sort on
* @param string $order ('ASC' or 'DESC')
* @param int $skip Number of records to skip (pagination)
* @param int $limit Max of records to return (pagination)
* @return array of cohort_role_assignment
*/
public static function list_cohort_role_assignments($sort = '', $order = 'ASC', $skip = 0, $limit = 0) {
$context = context_system::instance();
// First we do a permissions check.
require_capability('moodle/role:manage', $context);
// OK - all set.
return cohort_role_assignment::get_records(array(), $sort, $order, $skip, $limit);
}
/**
* Perform a search based on the provided filters and return a paginated list of records.
*
* Requires moodle/role:manage capability at system context.
*
* @return int
*/
public static function count_cohort_role_assignments() {
$context = context_system::instance();
// First we do a permissions check.
require_capability('moodle/role:manage', $context);
// OK - all set.
return cohort_role_assignment::count_records();
}
/**
* Sync all roles - adding and deleting role assignments as required.
*
* Slow. Should only be called from a background task.
*
* Requires moodle/role:manage capability at the system context.
*
* @return array('rolesadded' => array of (useridassignedto, useridassignedover, roleid),
* 'rolesremoved' => array of (useridassignedto, useridassignedover, roleid))
*/
public static function sync_all_cohort_roles() {
global $DB;
$context = context_system::instance();
// First we do a permissions check.
require_capability('moodle/role:manage', $context);
// Ok ready to go.
$rolesadded = array();
$rolesremoved = array();
// Remove any cohort role mappings for roles which have been deleted.
// The role assignments are not a consideration because these will have been removed when the role was.
$DB->delete_records_select('tool_cohortroles', "roleid NOT IN (SELECT id FROM {role})");
// Get all cohort role assignments and group them by user and role.
$all = cohort_role_assignment::get_records(array(), 'userid, roleid');
// We build an better structure to loop on.
$info = array();
foreach ($all as $cra) {
if (!isset($info[$cra->get('userid')])) {
$info[$cra->get('userid')] = array();
}
if (!isset($info[$cra->get('userid')][$cra->get('roleid')])) {
$info[$cra->get('userid')][$cra->get('roleid')] = array();
}
array_push($info[$cra->get('userid')][$cra->get('roleid')], $cra->get('cohortid'));
}
// Then for each user+role combo - find user context in the cohort without a role assigned.
foreach ($info as $userid => $roles) {
foreach ($roles as $roleid => $cohorts) {
list($cohortsql, $params) = $DB->get_in_or_equal($cohorts, SQL_PARAMS_NAMED);
$params['usercontext'] = CONTEXT_USER;
$params['roleid'] = $roleid;
$params['userid'] = $userid;
$sql = 'SELECT DISTINCT u.id AS userid, ra.id, ctx.id AS contextid
FROM {user} u
JOIN {cohort_members} cm ON u.id = cm.userid
JOIN {context} ctx ON u.id = ctx.instanceid AND ctx.contextlevel = :usercontext
LEFT JOIN {role_assignments} ra ON ra.contextid = ctx.id
AND ra.roleid = :roleid
AND ra.userid = :userid
WHERE cm.cohortid ' . $cohortsql . '
AND u.deleted = 0
AND ra.id IS NULL';
$toadd = $DB->get_records_sql($sql, $params);
foreach ($toadd as $add) {
role_assign($roleid, $userid, $add->contextid, 'tool_cohortroles');
$rolesadded[] = array(
'useridassignedto' => $userid,
'useridassignedover' => $add->userid,
'roleid' => $roleid
);
}
}
}
// And for each user+role combo - find user context not in the cohort with a role assigned.
// If the role was assigned by this component, unassign the role.
foreach ($info as $userid => $roles) {
foreach ($roles as $roleid => $cohorts) {
// Now we are looking for entries NOT in the cohort.
list($cohortsql, $params) = $DB->get_in_or_equal($cohorts, SQL_PARAMS_NAMED);
$params['usercontext'] = CONTEXT_USER;
$params['roleid'] = $roleid;
$params['userid'] = $userid;
$params['component'] = 'tool_cohortroles';
$sql = 'SELECT u.id as userid, ra.id, ctx.id AS contextid
FROM {user} u
JOIN {context} ctx ON u.id = ctx.instanceid AND ctx.contextlevel = :usercontext
JOIN {role_assignments} ra ON ra.contextid = ctx.id AND ra.roleid = :roleid AND ra.userid = :userid
LEFT JOIN {cohort_members} cm ON u.id = cm.userid
AND cm.cohortid ' . $cohortsql . '
WHERE ra.component = :component AND cm.cohortid IS NULL';
$toremove = $DB->get_records_sql($sql, $params);
foreach ($toremove as $remove) {
role_unassign($roleid, $userid, $remove->contextid, 'tool_cohortroles');
$rolesremoved[] = array(
'useridassignedto' => $userid,
'useridassignedover' => $remove->userid,
'roleid' => $roleid
);
}
}
}
// Clean the legacy role assignments which are stale.
$paramsclean['usercontext'] = CONTEXT_USER;
$paramsclean['component'] = 'tool_cohortroles';
$sql = 'SELECT DISTINCT(ra.id), ra.roleid, ra.userid, ra.contextid, ctx.instanceid
FROM {role_assignments} ra
JOIN {context} ctx ON ctx.id = ra.contextid AND ctx.contextlevel = :usercontext
JOIN {cohort_members} cm ON cm.userid = ctx.instanceid
LEFT JOIN {tool_cohortroles} tc ON tc.cohortid = cm.cohortid
AND tc.userid = ra.userid
AND tc.roleid = ra.roleid
WHERE ra.component = :component
AND tc.id is null';
if ($candidatelegacyassignments = $DB->get_records_sql($sql, $paramsclean)) {
$sql = 'SELECT DISTINCT(ra.id)
FROM {role_assignments} ra
JOIN {context} ctx ON ctx.id = ra.contextid AND ctx.contextlevel = :usercontext
JOIN {cohort_members} cm ON cm.userid = ctx.instanceid
JOIN {tool_cohortroles} tc ON tc.cohortid = cm.cohortid AND tc.userid = ra.userid
WHERE ra.component = :component';
if ($currentvalidroleassignments = $DB->get_records_sql($sql, $paramsclean)) {
foreach ($candidatelegacyassignments as $candidate) {
if (!array_key_exists($candidate->id, $currentvalidroleassignments)) {
role_unassign($candidate->roleid, $candidate->userid, $candidate->contextid, 'tool_cohortroles');
$rolesremoved[] = array(
'useridassignedto' => $candidate->userid,
'useridassignedover' => $candidate->instanceid,
'roleid' => $candidate->roleid
);
}
}
} else {
foreach ($candidatelegacyassignments as $candidate) {
role_unassign($candidate->roleid, $candidate->userid, $candidate->contextid, 'tool_cohortroles');
$rolesremoved[] = array(
'useridassignedto' => $candidate->userid,
'useridassignedover' => $candidate->instanceid,
'roleid' => $candidate->roleid
);
}
}
}
return array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
}
}
@@ -0,0 +1,106 @@
<?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/>.
/**
* Class for cohort_role_assignment persistence.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles;
use lang_string;
use core_competency\persistent;
/**
* Class for loading/storing cohort_role_assignments from the DB.
*
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cohort_role_assignment extends persistent {
/** Table name for user_competency persistency */
const TABLE = 'tool_cohortroles';
/**
* Return the definition of the properties of this model.
*
* @return array
*/
protected static function define_properties() {
return array(
'userid' => array(
'type' => PARAM_INT,
),
'roleid' => array(
'type' => PARAM_INT,
),
'cohortid' => array(
'type' => PARAM_INT,
)
);
}
/**
* Validate the user ID.
*
* @param int $value The value.
* @return true|lang_string
*/
protected function validate_userid($value) {
global $DB;
if (!$DB->record_exists('user', array('id' => $value))) {
return new lang_string('invaliduserid', 'error');
}
return true;
}
/**
* Validate the role ID.
*
* @param int $value The value.
* @return true|lang_string
*/
protected function validate_roleid($value) {
global $DB;
if (!$DB->record_exists('role', array('id' => $value))) {
return new lang_string('invalidroleid', 'error');
}
return true;
}
/**
* Validate the cohort ID.
*
* @param int $value The value.
* @return true|lang_string
*/
protected function validate_cohortid($value) {
global $DB;
if (!$DB->record_exists('cohort', array('id' => $value))) {
return new lang_string('invalidcohortid', 'error');
}
return true;
}
}
@@ -0,0 +1,77 @@
<?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 tool_cohortroles\form;
defined('MOODLE_INTERNAL') || die();
use moodleform;
use context_system;
require_once($CFG->libdir . '/formslib.php');
/**
* Assign role to cohort form.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class assign_role_cohort extends moodleform {
/**
* Form definition.
*/
public function definition() {
global $PAGE;
$mform = $this->_form;
$roles = get_roles_for_contextlevels(CONTEXT_USER);
if (empty($roles)) {
$output = $PAGE->get_renderer('tool_cohortroles');
$warning = $output->notify_problem(get_string('noassignableroles', 'tool_cohortroles'));
$mform->addElement('html', $warning);
return;
}
$options = array(
'ajax' => 'core_user/form_user_selector',
'multiple' => true
);
$mform->addElement('autocomplete', 'userids', get_string('selectusers', 'tool_cohortroles'), array(), $options);
$mform->addRule('userids', null, 'required');
$names = role_get_names();
$options = array();
foreach ($roles as $idx => $roleid) {
$options[$roleid] = $names[$roleid]->localname;
}
$mform->addElement('select', 'roleid', get_string('selectrole', 'tool_cohortroles'), $options);
$mform->addRule('roleid', null, 'required');
$context = context_system::instance();
$options = array(
'multiple' => true,
'data-contextid' => $context->id,
'data-includes' => 'all'
);
$mform->addElement('cohort', 'cohortids', get_string('selectcohorts', 'tool_cohortroles'), $options);
$mform->addRule('cohortids', null, 'required');
$mform->addElement('submit', 'submit', get_string('assign', 'tool_cohortroles'));
}
}
@@ -0,0 +1,43 @@
<?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/>.
declare(strict_types=1);
namespace tool_cohortroles;
use core\event\user_deleted;
/**
* Plugin event observer callbacks
*
* @package tool_cohortroles
* @copyright 2023 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class observers {
/**
* User deleted event, remove cohort role assignments specific to them
*
* @param user_deleted $event
*/
public static function user_deleted(user_deleted $event): void {
$cohortroleassignments = cohort_role_assignment::get_records(['userid' => $event->objectid]);
foreach ($cohortroleassignments as $cohortroleassignment) {
$cohortroleassignment->delete();
}
}
}
@@ -0,0 +1,242 @@
<?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 role assignments table
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles\output;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/tablelib.php');
use context_helper;
use context_system;
use html_writer;
use moodle_url;
use table_sql;
/**
* Cohort role assignments table.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cohort_role_assignments_table extends table_sql {
/** @var context_system */
protected ?context_system $context = null;
/** @var array */
protected array $rolenames = [];
/**
* Sets up the table.
*
* @param string $uniqueid Unique id of table.
* @param moodle_url $url The base URL.
*/
public function __construct($uniqueid, $url) {
global $CFG;
parent::__construct($uniqueid);
$context = context_system::instance();
$this->context = $context;
$this->rolenames = role_get_names();
// This object should not be used without the right permissions.
require_capability('moodle/role:manage', $context);
$this->useridfield = 'userid';
// Define columns in the table.
$this->define_table_columns();
$this->define_baseurl($url);
// Define configs.
$this->define_table_configs();
}
/**
* Role name column.
*
* @param array $data Row data.
* @return string
*/
protected function col_rolename($data) {
return $this->rolenames[$data->roleid]->localname;
}
/**
* Cohort name column.
*
* @param array $data Row data.
* @return string
*/
protected function col_cohortname($data) {
global $OUTPUT;
$record = (object) array(
'id' => $data->cohortid,
'idnumber' => $data->cohortidnumber,
'description' => $data->cohortdescription,
'visible' => $data->cohortvisible,
'name' => $data->cohortname,
'theme' => $data->cohorttheme
);
$context = context_helper::instance_by_id($data->cohortcontextid);
$exporter = new \core_cohort\external\cohort_summary_exporter($record, array('context' => $context));
$cohort = $exporter->export($OUTPUT);
$html = $OUTPUT->render_from_template('tool_cohortroles/cohort-in-list', $cohort);
return $html;
}
/**
* Actions column.
*
* @param array $data Row data.
* @return string
*/
protected function col_actions($data) {
global $OUTPUT;
$action = new \confirm_action(get_string('removecohortroleassignmentconfirm', 'tool_cohortroles'));
$url = new moodle_url($this->baseurl);
$url->params(array('removecohortroleassignment' => $data->id, 'sesskey' => sesskey()));
$pix = new \pix_icon('t/delete', get_string('removecohortroleassignment', 'tool_cohortroles'));
return $OUTPUT->action_link($url, '', $action, null, $pix);
}
/**
* Setup the headers for the table.
*/
protected function define_table_columns() {
// TODO Does not support custom user profile fields (MDL-70456).
$extrafields = \core_user\fields::get_identity_fields($this->context, false);
// Define headers and columns.
$cols = array(
'cohortname' => get_string('cohort', 'cohort'),
'rolename' => get_string('role'),
'fullname' => get_string('name'),
);
// Add headers for extra user fields.
foreach ($extrafields as $field) {
if (get_string_manager()->string_exists($field, 'moodle')) {
$cols[$field] = get_string($field);
} else {
$cols[$field] = $field;
}
}
// Add remaining headers.
$cols = array_merge($cols, array('actions' => get_string('actions')));
$this->define_columns(array_keys($cols));
$this->define_headers(array_values($cols));
}
/**
* Define table configs.
*/
protected function define_table_configs() {
$this->collapsible(false);
$this->sortable(true, 'lastname', SORT_ASC);
$this->pageable(true);
$this->no_sorting('actions');
}
/**
* Builds the SQL query.
*
* @param bool $count When true, return the count SQL.
* @return array containing sql to use and an array of params.
*/
protected function get_sql_and_params($count = false) {
$fields = 'uca.id, uca.cohortid, uca.userid, uca.roleid, ';
$fields .= 'c.name as cohortname, c.idnumber as cohortidnumber, c.contextid as cohortcontextid, ';
$fields .= 'c.visible as cohortvisible, c.description as cohortdescription, c.theme as cohorttheme';
// Add extra user fields that we need for the graded user.
// TODO Does not support custom user profile fields (MDL-70456).
$userfieldsapi = \core_user\fields::for_identity($this->context, false)->with_name();
$fields .= $userfieldsapi->get_sql('u')->selects;
if ($count) {
$select = "COUNT(1)";
} else {
$select = "$fields";
}
$sql = "SELECT $select
FROM {tool_cohortroles} uca
JOIN {user} u ON u.id = uca.userid
JOIN {cohort} c ON c.id = uca.cohortid";
// Check if any additional filtering is required.
[$sqlwhere, $params] = $this->get_sql_where();
if ($sqlwhere) {
$sql .= " WHERE {$sqlwhere}";
}
// Add order by if needed.
if (!$count && $sqlsort = $this->get_sql_sort()) {
$sql .= " ORDER BY " . $sqlsort;
}
return array($sql, $params);
}
/**
* Override the default implementation to set a notification.
*/
public function print_nothing_to_display() {
global $OUTPUT;
echo $this->render_reset_button();
$this->print_initials_bar();
echo $OUTPUT->notification(get_string('nothingtodisplay'), 'info', false);
}
/**
* Query the DB.
*
* @param int $pagesize size of page for paginated displayed table.
* @param bool $useinitialsbar do you want to use the initials bar.
*/
public function query_db($pagesize, $useinitialsbar = true) {
global $DB;
list($countsql, $countparams) = $this->get_sql_and_params(true);
list($sql, $params) = $this->get_sql_and_params();
$total = $DB->count_records_sql($countsql, $countparams);
$this->pagesize($pagesize, $total);
$this->rawdata = $DB->get_records_sql($sql, $params, $this->get_page_start(), $this->get_page_size());
// Set initial bars.
if ($useinitialsbar) {
$this->initialbars($total > $pagesize);
}
}
}
@@ -0,0 +1,76 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Renderer class for cohort roles
*
* @package tool_cohortroles
* @copyright 2016 Issam Taboubi <issam.taboubi@umontreal.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles\output;
defined('MOODLE_INTERNAL') || die();
use plugin_renderer_base;
use renderable;
/**
* Renderer class for cohort roles
*
* @package tool_cohortroles
* @copyright 2016 Issam Taboubi <issam.taboubi@umontreal.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends plugin_renderer_base {
/**
* Output a nofication.
*
* @param string $message the message to print out
* @return string HTML fragment.
* @see \core\output\notification
*/
public function notify_message($message) {
$n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
return $this->render($n);
}
/**
* Output an error notification.
*
* @param string $message the message to print out
* @return string HTML fragment.
* @see \core\output\notification
*/
public function notify_problem($message) {
$n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
return $this->render($n);
}
/**
* Output a success notification.
*
* @param string $message the message to print out
* @return string HTML fragment.
* @see \core\output\notification
*/
public function notify_success($message) {
$n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
return $this->render($n);
}
}
@@ -0,0 +1,328 @@
<?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 tool_cohortroles.
*
* @package tool_cohortroles
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles\privacy;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\context;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\transform;
use core_privacy\local\request\writer;
use core_privacy\local\request\userlist;
use \core_privacy\local\request\approved_userlist;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for tool_cohortroles implementing metadata and plugin providers.
*
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
// The tool_cohortroles plugin utilises the mdl_tool_cohortroles table.
$collection->add_database_table(
'tool_cohortroles',
[
'id' => 'privacy:metadata:tool_cohortroles:id',
'cohortid' => 'privacy:metadata:tool_cohortroles:cohortid',
'roleid' => 'privacy:metadata:tool_cohortroles:roleid',
'userid' => 'privacy:metadata:tool_cohortroles:userid',
'timecreated' => 'privacy:metadata:tool_cohortroles:timecreated',
'timemodified' => 'privacy:metadata:tool_cohortroles:timemodified',
'usermodified' => 'privacy:metadata:tool_cohortroles:usermodified'
],
'privacy:metadata:tool_cohortroles'
);
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 {
$contextlist = new contextlist();
// When we process user deletions and expiries, we always delete from the user context.
// As a result the cohort role assignments would be deleted, which has a knock-on effect with courses
// as roles may change and data may be removed earlier than it should be.
// Retrieve the context associated with tool_cohortroles records.
$sql = "SELECT DISTINCT c.contextid
FROM {tool_cohortroles} tc
JOIN {cohort} c
ON tc.cohortid = c.id
JOIN {context} ctx
ON ctx.id = c.contextid
WHERE tc.userid = :userid
AND (ctx.contextlevel = :contextlevel1
OR ctx.contextlevel = :contextlevel2)";
$params = [
'userid' => $userid,
'contextlevel1' => CONTEXT_SYSTEM,
'contextlevel2' => CONTEXT_COURSECAT
];
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific 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();
// When we process user deletions and expiries, we always delete from the user context.
// As a result the cohort role assignments would be deleted, which has a knock-on effect with courses
// as roles may change and data may be removed earlier than it should be.
$allowedcontextlevels = [
CONTEXT_SYSTEM,
CONTEXT_COURSECAT
];
if (!in_array($context->contextlevel, $allowedcontextlevels)) {
return;
}
$sql = "SELECT tc.userid as userid
FROM {tool_cohortroles} tc
JOIN {cohort} c
ON tc.cohortid = c.id
WHERE c.contextid = :contextid";
$params = [
'contextid' => $context->id
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* 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) {
global $DB;
// Remove contexts different from SYSTEM or COURSECAT.
$contextids = array_reduce($contextlist->get_contexts(), function($carry, $context) {
if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
$carry[] = $context->id;
}
return $carry;
}, []);
if (empty($contextids)) {
return;
}
$userid = $contextlist->get_user()->id;
list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
// Retrieve the tool_cohortroles records created for the user.
$sql = "SELECT cr.id as cohortroleid,
c.name as cohortname,
c.idnumber as cohortidnumber,
c.description as cohortdescription,
c.contextid as contextid,
r.shortname as roleshortname,
cr.userid as userid,
cr.timecreated as timecreated,
cr.timemodified as timemodified
FROM {tool_cohortroles} cr
JOIN {cohort} c ON c.id = cr.cohortid
JOIN {role} r ON r.id = cr.roleid
WHERE cr.userid = :userid
AND c.contextid {$contextsql}";
$params = ['userid' => $userid] + $contextparams;
$cohortroles = $DB->get_records_sql($sql, $params);
foreach ($cohortroles as $cohortrole) {
// The tool_cohortroles data export is organised in:
// {User Context}/Cohort roles management/{cohort name}/{role shortname}/data.json.
$subcontext = [
get_string('pluginname', 'tool_cohortroles'),
$cohortrole->cohortname,
$cohortrole->roleshortname
];
$data = (object) [
'cohortname' => $cohortrole->cohortname,
'cohortidnumber' => $cohortrole->cohortidnumber,
'cohortdescription' => $cohortrole->cohortdescription,
'roleshortname' => $cohortrole->roleshortname,
'userid' => transform::user($cohortrole->userid),
'timecreated' => transform::datetime($cohortrole->timecreated),
'timemodified' => transform::datetime($cohortrole->timemodified)
];
$context = \context::instance_by_id($cohortrole->contextid);
writer::with_context($context)->export_data($subcontext, $data);
}
}
/**
* Delete all data for all users in the specified context.
*
* @param context $context The specific context to delete data for.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
global $DB;
// When we process user deletions and expiries, we always delete from the user context.
// As a result the cohort role assignments would be deleted, which has a knock-on effect with courses
// as roles may change and data may be removed earlier than it should be.
$allowedcontextlevels = [
CONTEXT_SYSTEM,
CONTEXT_COURSECAT
];
if (!in_array($context->contextlevel, $allowedcontextlevels)) {
return;
}
$cohortids = $DB->get_fieldset_select('cohort', 'id', 'contextid = :contextid',
['contextid' => $context->id]);
// Delete the tool_cohortroles records created in the specific context.
$DB->delete_records_list('tool_cohortroles', 'cohortid', $cohortids);
}
/**
* 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) {
global $DB;
// When we process user deletions and expiries, we always delete from the user context.
// As a result the cohort role assignments would be deleted, which has a knock-on effect with courses
// as roles may change and data may be removed earlier than it should be.
$userids = $userlist->get_userids();
if (empty($userids)) {
return;
}
$context = $userlist->get_context();
$allowedcontextlevels = [
CONTEXT_SYSTEM,
CONTEXT_COURSECAT
];
if (!in_array($context->contextlevel, $allowedcontextlevels)) {
return;
}
$cohortids = $DB->get_fieldset_select('cohort', 'id', 'contextid = :contextid',
['contextid' => $context->id]);
if (empty($cohortids)) {
return;
}
list($cohortsql, $cohortparams) = $DB->get_in_or_equal($cohortids, SQL_PARAMS_NAMED);
list($usersql, $userparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
$params = $cohortparams + $userparams;
$select = "cohortid {$cohortsql} AND userid {$usersql}";
// Delete the tool_cohortroles records created in the specific context for an approved list of users.
$DB->delete_records_select('tool_cohortroles', $select, $params);
}
/**
* 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) {
global $DB;
// When we process user deletions and expiries, we always delete from the user context.
// As a result the cohort role assignments would be deleted, which has a knock-on effect with courses
// as roles may change and data may be removed earlier than it should be.
// Remove contexts different from SYSTEM or COURSECAT.
$contextids = array_reduce($contextlist->get_contexts(), function($carry, $context) {
if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
$carry[] = $context->id;
}
return $carry;
}, []);
if (empty($contextids)) {
return;
}
$userid = $contextlist->get_user()->id;
list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
$selectcontext = "contextid {$contextsql}";
// Get the cohorts in the specified contexts.
$cohortids = $DB->get_fieldset_select('cohort', 'id', $selectcontext, $contextparams);
if (empty($cohortids)) {
return;
}
list($cohortsql, $cohortparams) = $DB->get_in_or_equal($cohortids, SQL_PARAMS_NAMED);
$selectcohort = "cohortid {$cohortsql} AND userid = :userid";
$params = ['userid' => $userid] + $cohortparams;
// Delete the tool_cohortroles records created for the userid.
$DB->delete_records_select('tool_cohortroles', $selectcohort, $params);
}
}
@@ -0,0 +1,56 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Scheduled task for syncing cohort roles.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles\task;
use core\task\scheduled_task;
use tool_cohortroles\api;
/**
* Scheduled task for syncing cohort roles.
*
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cohort_role_sync extends scheduled_task {
/**
* Get name.
* @return string
*/
public function get_name() {
// Shown in admin screens.
return get_string('taskname', 'tool_cohortroles');
}
/**
* Execute.
*/
public function execute() {
mtrace('Sync cohort roles...');
$result = api::sync_all_cohort_roles();
mtrace('Added ' . count($result['rolesadded']));
mtrace('Removed ' . count($result['rolesremoved']));
}
}
+32
View File
@@ -0,0 +1,32 @@
<?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/>.
/**
* Plugin event observers
*
* @package tool_cohortroles
* @copyright 2023 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$observers = [
[
'eventname' => '\core\event\user_deleted',
'callback' => '\tool_cohortroles\observers::user_deleted',
],
];
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="admin/tool/cohortroles/db" VERSION="20151201" COMMENT="XMLDB file for Moodle admin/tool/cohortroles"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../lib/xmldb/xmldb.xsd"
>
<TABLES>
<TABLE NAME="tool_cohortroles" COMMENT="Mapping of users to cohort role assignments.">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="cohortid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The cohort to sync"/>
<FIELD NAME="roleid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The role to assign"/>
<FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The user to sync"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The time this record was created"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The time this record was modified."/>
<FIELD NAME="usermodified" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false" COMMENT="Who last modified this record?"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
</KEYS>
<INDEXES>
<INDEX NAME="cohortuserrole" UNIQUE="true" FIELDS="cohortid, roleid, userid"/>
</INDEXES>
</TABLE>
</TABLES>
</XMLDB>
+37
View File
@@ -0,0 +1,37 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Tasks definitions.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$tasks = array(
array(
'classname' => 'tool_cohortroles\task\cohort_role_sync',
'blocking' => 0,
'minute' => 'R',
'hour' => '*',
'day' => '*',
'dayofweek' => '*',
'month' => '*'
),
);
+55
View File
@@ -0,0 +1,55 @@
<?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/>.
/**
* Plugin upgrade code
*
* @package tool_cohortroles
* @copyright 2020 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Function to upgrade tool_cohortroles.
*
* @param int $oldversion the version we are upgrading from
* @return bool result
*/
function xmldb_tool_cohortroles_upgrade($oldversion) {
global $DB;
// Automatically generated Moodle v4.1.0 release upgrade line.
// Put any upgrade step following this.
// Automatically generated Moodle v4.2.0 release upgrade line.
// Put any upgrade step following this.
if ($oldversion < 2023042401) {
// Delete any tool_cohortroles mappings for users who no longer exist.
$DB->delete_records_select('tool_cohortroles', 'userid NOT IN (SELECT id FROM {user} WHERE deleted = 0)');
// Cohortroles savepoint reached.
upgrade_plugin_savepoint(true, 2023042401, 'tool', 'cohortroles');
}
// Automatically generated Moodle v4.3.0 release upgrade line.
// Put any upgrade step following this.
// Automatically generated Moodle v4.4.0 release upgrade line.
// Put any upgrade step following this.
return true;
}
+98
View File
@@ -0,0 +1,98 @@
<?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/>.
/**
* Assign roles for a user.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__ . '/../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/tablelib.php');
$removeid = optional_param('removecohortroleassignment', 0, PARAM_INT);
admin_externalpage_setup('toolcohortroles');
$context = context_system::instance();
$pageurl = new moodle_url('/admin/tool/cohortroles/index.php');
$output = $PAGE->get_renderer('tool_cohortroles');
echo $output->header();
$title = get_string('assignroletocohort', 'tool_cohortroles');
echo $output->heading($title);
$form = new tool_cohortroles\form\assign_role_cohort();
if ($removeid) {
require_sesskey();
$result = \tool_cohortroles\api::delete_cohort_role_assignment($removeid);
if ($result) {
$notification = get_string('cohortroleassignmentremoved', 'tool_cohortroles');
echo $output->notify_success($notification);
} else {
$notification = get_string('cohortroleassignmentnotremoved', 'tool_cohortroles');
echo $output->notify_problem($notification);
}
echo $output->continue_button(new moodle_url($pageurl));
} else if ($data = $form->get_data()) {
require_sesskey();
// We must create them all or none.
$saved = 0;
// Loop through userids and cohortids only if both of them are not empty.
if (!empty($data->userids) && !empty($data->cohortids)) {
foreach ($data->userids as $userid) {
foreach ($data->cohortids as $cohortid) {
$params = (object) array('userid' => $userid, 'cohortid' => $cohortid, 'roleid' => $data->roleid);
$result = \tool_cohortroles\api::create_cohort_role_assignment($params);
if ($result) {
$saved++;
}
}
}
}
if ($saved == 0) {
$notification = get_string('nocohortroleassignmentssaved', 'tool_cohortroles');
echo $output->notify_problem($notification);
} else if ($saved == 1) {
$notification = get_string('onecohortroleassignmentsaved', 'tool_cohortroles');
echo $output->notify_success($notification);
} else {
$notification = get_string('acohortroleassignmentssaved', 'tool_cohortroles', $saved);
echo $output->notify_success($notification);
}
echo $output->continue_button(new moodle_url($pageurl));
} else {
$form->display();
$title = get_string('existingcohortroles', 'tool_cohortroles');
echo $output->heading($title);
$table = new tool_cohortroles\output\cohort_role_assignments_table('cohort-role-assignments', $pageurl);
echo $table->out(50, true);
echo $output->spacer();
echo $output->notify_message(get_string('backgroundsync', 'tool_cohortroles'));
}
echo $output->footer();
@@ -0,0 +1,52 @@
<?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 'tool_userroles', language 'en'
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['acohortroleassignmentssaved'] = '{$a} cohort role assignments were saved.';
$string['assign'] = 'Assign';
$string['assignroletocohort'] = 'Assign user-context roles to all cohort members';
$string['backgroundsync'] = 'Note: New cohort role assignments will not take effect immediately. Role assignment changes will be made by a scheduled task.';
$string['cohortroleassignmentremoved'] = 'The cohort role assignment was removed.';
$string['cohortroleassignmentnotremoved'] = 'The cohort role assignment was not removed.';
$string['cohortroles'] = 'Cohort roles';
$string['existingcohortroles'] = 'Existing cohort role assignments';
$string['managecohortroles'] = 'Assign user roles to cohort';
$string['noassignableroles'] = 'There are currently no roles that can be assigned in the user context. <a href="../../roles/manage.php">Manage roles</a>';
$string['nocohortroleassignmentssaved'] = 'No cohort role assignments were saved.';
$string['onecohortroleassignmentsaved'] = 'One cohort role assignment was saved.';
$string['pluginname'] = 'Cohort roles management';
$string['removecohortroleassignment'] = 'Remove cohort role assignment';
$string['removecohortroleassignmentconfirm'] = 'Are you sure you want to remove this cohort role assignment? This role will be removed for this user in all other user contexts.';
$string['selectcohorts'] = 'Select cohorts';
$string['selectrole'] = 'Select role';
$string['selectusers'] = 'Select users to assign role';
$string['taskname'] = 'Sync cohort role assignments';
$string['thisuserroles'] = 'Roles assigned relative to this user';
$string['privacy:metadata:tool_cohortroles'] = 'The Cohort roles management plugin stores user cohort role mappings.';
$string['privacy:metadata:tool_cohortroles:id'] = 'The ID of the cohort role mapping record';
$string['privacy:metadata:tool_cohortroles:cohortid'] = 'The ID of the cohort';
$string['privacy:metadata:tool_cohortroles:roleid'] = 'The ID of the role';
$string['privacy:metadata:tool_cohortroles:userid'] = 'The ID of the user';
$string['privacy:metadata:tool_cohortroles:timecreated'] = 'The time when the cohort role mapping was created';
$string['privacy:metadata:tool_cohortroles:timemodified'] = 'The time when the cohort role mapping was modified';
$string['privacy:metadata:tool_cohortroles:usermodified'] = 'The ID of the user who last modified the cohort role mapping';
+42
View File
@@ -0,0 +1,42 @@
<?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/>.
/**
* Link to user roles management.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
// This tool's required capabilities.
$capabilities = [
'moodle/cohort:view',
'moodle/role:manage'
];
// Check if the user has all of the required capabilities.
$context = context_system::instance();
$hasaccess = has_all_capabilities($capabilities, $context);
// Add this admin page only if the user has all of the required capabilities.
if ($hasaccess) {
$str = get_string('managecohortroles', 'tool_cohortroles');
$url = new moodle_url('/admin/tool/cohortroles/index.php');
$ADMIN->add('roles', new admin_externalpage('toolcohortroles', $str, $url, $capabilities));
}
@@ -0,0 +1,51 @@
{{!
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/>.
}}
{{!
@template tool_cohortroles/cohort-in-list
Moodle template for displaying a cohort in a list.
Classes required for JS:
* none
Data attributes required for JS:
* none
Context variables required for this template:
* id cohort id field
* name cohort name field
* idnumber cohort idnumber field
* description cohort description field
* visible cohort visible field
* theme cohort theme field
Example context (json):
{ "id": "1",
"name": "Cohort 1",
"visible": true,
"idnumber": "014",
"description": "Some users",
"theme": "classic"
}
}}
<span>
<span>{{name}}</span>
{{#idnumber}}
<span><small>{{idnumber}}</small></span>
{{/idnumber}}
<span><small>( {{contextname}} )</small></span>
</span>
+310
View File
@@ -0,0 +1,310 @@
<?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 tool_cohortroles;
/**
* API tests.
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api_test extends \advanced_testcase {
/** @var \stdClass $cohort */
protected $cohort = null;
/** @var \stdClass $userassignto */
protected $userassignto = null;
/** @var \stdClass $userassignover */
protected $userassignover = null;
/** @var \stdClass $role */
protected $role = null;
/** @var int $roleid */
protected $roleid;
/**
* Setup function- we will create a course and add an assign instance to it.
*/
protected function setUp(): void {
$this->resetAfterTest(true);
// Create some users.
$this->cohort = $this->getDataGenerator()->create_cohort();
$this->userassignto = $this->getDataGenerator()->create_user();
$this->userassignover = $this->getDataGenerator()->create_user();
$this->roleid = create_role('Sausage Roll', 'sausageroll', 'mmmm');
cohort_add_member($this->cohort->id, $this->userassignover->id);
}
public function test_create_cohort_role_assignment_without_permission(): void {
$this->setUser($this->userassignto);
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$this->expectException(\required_capability_exception::class);
api::create_cohort_role_assignment($params);
}
public function test_create_cohort_role_assignment_with_invalid_data(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => -8,
'cohortid' => $this->cohort->id
);
$this->expectException(\core_competency\invalid_persistent_exception::class);
api::create_cohort_role_assignment($params);
}
public function test_create_cohort_role_assignment(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
$this->assertNotEmpty($result->get('id'));
$this->assertEquals($result->get('userid'), $this->userassignto->id);
$this->assertEquals($result->get('roleid'), $this->roleid);
$this->assertEquals($result->get('cohortid'), $this->cohort->id);
}
public function test_delete_cohort_role_assignment_without_permission(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
$this->setUser($this->userassignto);
$this->expectException(\required_capability_exception::class);
api::delete_cohort_role_assignment($result->get('id'));
}
public function test_delete_cohort_role_assignment_with_invalid_data(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
$this->expectException(\dml_missing_record_exception::class);
api::delete_cohort_role_assignment($result->get('id') + 1);
}
public function test_delete_cohort_role_assignment(): void {
$this->setAdminUser();
// Create a cohort role assigment.
$params = (object) [
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
];
$cohortroleassignment = api::create_cohort_role_assignment($params);
$sync = api::sync_all_cohort_roles();
$rolesadded = [
[
'useridassignedto' => $this->userassignto->id,
'useridassignedover' => $this->userassignover->id,
'roleid' => $this->roleid
]
];
$expected = [
'rolesadded' => $rolesadded,
'rolesremoved' => []
];
$this->assertEquals($sync, $expected);
// Delete the cohort role assigment and confirm the roles are removed.
$result = api::delete_cohort_role_assignment($cohortroleassignment->get('id'));
$this->assertTrue($result);
$sync = api::sync_all_cohort_roles();
$expected = [
'rolesadded' => [],
'rolesremoved' => $rolesadded
];
$this->assertEquals($expected, $sync);
}
/**
* Test case verifying that syncing won't remove role assignments if they are valid for another cohort role assignment.
*/
public function test_delete_cohort_role_assignment_cohorts_having_same_members(): void {
$this->setAdminUser();
// Create 2 cohorts, with a 1 user (user1) present in both,
// and user2 and user3 members of 1 cohort each.
$cohort1 = $this->getDataGenerator()->create_cohort();
$cohort2 = $this->getDataGenerator()->create_cohort();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
cohort_add_member($cohort1->id, $user1->id);
cohort_add_member($cohort1->id, $user2->id);
cohort_add_member($cohort2->id, $user1->id);
cohort_add_member($cohort2->id, $user3->id);
// And a role and a user to assign that role to.
$user4 = $this->getDataGenerator()->create_user(); // A cohort manager, for example.
$roleid = create_role('Role 1', 'myrole', 'test');
// Assign the role for user4 in both cohorts.
$params = (object) [
'userid' => $user4->id,
'roleid' => $roleid,
'cohortid' => $cohort1->id
];
$cohort1roleassignment = api::create_cohort_role_assignment($params);
$params->cohortid = $cohort2->id;
$cohort2roleassignment = api::create_cohort_role_assignment($params);
$sync = api::sync_all_cohort_roles();
// There is no guarantee about the order of roles assigned.
// so confirm we have 3 role assignments, and they are for the users 1, 2 and 3.
$this->assertCount(3, $sync['rolesadded']);
$addedusers = array_column($sync['rolesadded'], 'useridassignedover');
$this->assertContains($user1->id, $addedusers);
$this->assertContains($user2->id, $addedusers);
$this->assertContains($user3->id, $addedusers);
// Remove the role assignment for user4/cohort1.
// Verify only 1 role is unassigned as the others are still valid for the other cohort role assignment.
$result = api::delete_cohort_role_assignment($cohort1roleassignment->get('id'));
$this->assertTrue($result);
$sync = api::sync_all_cohort_roles();
$this->assertCount(0, $sync['rolesadded']);
$this->assertCount(1, $sync['rolesremoved']);
$removedusers = array_column($sync['rolesremoved'], 'useridassignedover');
$this->assertContains($user2->id, $removedusers);
}
public function test_list_cohort_role_assignments(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
$list = api::list_cohort_role_assignments();
$list[0]->is_valid();
$this->assertEquals($list[0], $result);
}
public function test_count_cohort_role_assignments(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
$count = api::count_cohort_role_assignments();
$this->assertEquals($count, 1);
}
public function test_sync_all_cohort_roles(): void {
$this->setAdminUser();
$params = (object) array(
'userid' => $this->userassignto->id,
'roleid' => $this->roleid,
'cohortid' => $this->cohort->id
);
$result = api::create_cohort_role_assignment($params);
// Verify roles are assigned when users enter the cohort.
$sync = api::sync_all_cohort_roles();
$rolesadded = array(array(
'useridassignedto' => $this->userassignto->id,
'useridassignedover' => $this->userassignover->id,
'roleid' => $this->roleid
));
$rolesremoved = array();
$expected = array('rolesadded' => $rolesadded,
'rolesremoved' => $rolesremoved);
$this->assertEquals($sync, $expected);
// Verify roles are removed when users leave the cohort.
cohort_remove_member($this->cohort->id, $this->userassignover->id);
$sync = api::sync_all_cohort_roles();
$rolesadded = array();
$rolesremoved = array(array(
'useridassignedto' => $this->userassignto->id,
'useridassignedover' => $this->userassignover->id,
'roleid' => $this->roleid
));
$expected = array('rolesadded' => $rolesadded,
'rolesremoved' => $rolesremoved);
$this->assertEquals($sync, $expected);
// Verify roles assigned by any other component are not removed.
$usercontext = \context_user::instance($this->userassignover->id);
role_assign($this->roleid, $this->userassignto->id, $usercontext->id);
$sync = api::sync_all_cohort_roles();
$rolesadded = array();
$rolesremoved = array();
$expected = array('rolesadded' => $rolesadded,
'rolesremoved' => $rolesremoved);
$this->assertEquals($sync, $expected);
// Remove manual role assignment.
role_unassign($this->roleid, $this->userassignto->id, $usercontext->id);
// Add someone to the cohort again...
cohort_add_member($this->cohort->id, $this->userassignover->id);
$sync = api::sync_all_cohort_roles();
$rolesadded = array(array(
'useridassignedto' => $this->userassignto->id,
'useridassignedover' => $this->userassignover->id,
'roleid' => $this->roleid
));
$rolesremoved = array();
$expected = array('rolesadded' => $rolesadded,
'rolesremoved' => $rolesremoved);
$this->assertEquals($sync, $expected);
// Verify no fatal errors when a cohort is deleted.
cohort_delete_cohort($this->cohort);
$sync = api::sync_all_cohort_roles();
$rolesadded = array();
$rolesremoved = array(array(
'useridassignedto' => $this->userassignto->id,
'useridassignedover' => $this->userassignover->id,
'roleid' => $this->roleid
));
$expected = array('rolesadded' => $rolesadded,
'rolesremoved' => $rolesremoved);
$this->assertEquals($sync, $expected);
}
}
@@ -0,0 +1,380 @@
<?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/>.
/**
* Unit tests for the tool_cohortroles implementation of the privacy API.
*
* @package tool_cohortroles
* @category test
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_cohortroles\privacy;
defined('MOODLE_INTERNAL') || die();
global $CFG;
use core_privacy\local\request\writer;
use core_privacy\local\request\approved_contextlist;
use tool_cohortroles\api;
use tool_cohortroles\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for the tool_cohortroles implementation of the privacy API.
*
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends \core_privacy\tests\provider_testcase {
/**
* Overriding setUp() function to always reset after tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test for provider::get_contexts_for_userid().
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Test setup.
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->setAdminUser();
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
// Create course.
$course = $this->getDataGenerator()->create_course();
$coursectx = \context_course::instance($course->id);
$this->setup_test_scenario_data($user->id, $systemctx, 1);
$this->setup_test_scenario_data($user->id, $coursecategoryctx, 1, 'Sausage roll 2',
'sausageroll2');
$this->setup_test_scenario_data($user->id, $coursectx, 1, 'Sausage roll 3',
'sausageroll3');
// Test the User's assigned cohortroles matches 3.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(3, $cohortroles);
// Test the User's retrieved contextlist returns only the system and course category context.
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(2, $contexts);
$contextlevels = array_column($contexts, 'contextlevel');
$expected = [
CONTEXT_SYSTEM,
CONTEXT_COURSECAT
];
// Test the User's contexts equal the system and course category context.
$this->assertEqualsCanonicalizing($expected, $contextlevels);
}
/**
* Test for provider::export_user_data().
*/
public function test_export_user_data(): void {
// Test setup.
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->setAdminUser();
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
// Create course.
$course = $this->getDataGenerator()->create_course();
$coursectx = \context_course::instance($course->id);
$this->setup_test_scenario_data($user->id, $systemctx, 1);
$this->setup_test_scenario_data($user->id, $coursecategoryctx, 1, 'Sausage roll 2',
'sausageroll2');
$this->setup_test_scenario_data($user->id, $coursectx, 1, 'Sausage roll 3',
'sausageroll3');
// Test the User's retrieved contextlist contains two contexts.
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(2, $contexts);
// Add a system, course category and course context to the approved context list.
$approvedcontextids = [
$systemctx->id,
$coursecategoryctx->id,
$coursectx->id
];
// Retrieve the User's tool_cohortroles data.
$approvedcontextlist = new approved_contextlist($user, 'tool_cohortroles', $approvedcontextids);
provider::export_user_data($approvedcontextlist);
// Test the tool_cohortroles data is exported at the system context level.
$writer = writer::with_context($systemctx);
$this->assertTrue($writer->has_any_data());
// Test the tool_cohortroles data is exported at the course category context level.
$writer = writer::with_context($coursecategoryctx);
$this->assertTrue($writer->has_any_data());
// Test the tool_cohortroles data is not exported at the course context level.
$writer = writer::with_context($coursectx);
$this->assertFalse($writer->has_any_data());
}
/**
* Test for provider::delete_data_for_all_users_in_context().
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Test setup.
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->setAdminUser();
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
$this->setup_test_scenario_data($user->id, $systemctx, 1);
$this->setup_test_scenario_data($user->id, $coursecategoryctx, 1, 'Sausage roll 2',
'sausageroll2');
// Test the User's assigned cohortroles matches 2.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(2, $cohortroles);
// Test the User's retrieved contextlist contains two contexts.
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(2, $contexts);
// Make sure the user data is only being deleted in within the system and course category context.
$usercontext = \context_user::instance($user->id);
// Delete all the User's records in mdl_tool_cohortroles table by the user context.
provider::delete_data_for_all_users_in_context($usercontext);
// Test the cohort roles records in mdl_tool_cohortroles table is still present.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(2, $cohortroles);
// Delete all the User's records in mdl_tool_cohortroles table by the specified system context.
provider::delete_data_for_all_users_in_context($systemctx);
// The user data in the system context should be deleted.
// Test the User's retrieved contextlist contains one context (course category).
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(1, $contexts);
// Delete all the User's records in mdl_tool_cohortroles table by the specified course category context.
provider::delete_data_for_all_users_in_context($coursecategoryctx);
// Test the cohort roles records in mdl_tool_cohortroles table is equals zero.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(0, $cohortroles);
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(0, $contexts);
}
/**
* Test for provider::delete_data_for_user().
*/
public function test_delete_data_for_user(): void {
global $DB;
// Test setup.
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->setAdminUser();
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
$this->setup_test_scenario_data($user->id, $systemctx, 1);
$this->setup_test_scenario_data($user->id, $coursecategoryctx, 1, 'Sausage roll 2',
'sausageroll2');
// Test the User's assigned cohortroles matches 2.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(2, $cohortroles);
// Test the User's retrieved contextlist contains two contexts.
$contextlist = provider::get_contexts_for_userid($user->id);
$contexts = $contextlist->get_contexts();
$this->assertCount(2, $contexts);
// Make sure the user data is only being deleted in within the system and the course category contexts.
$usercontext = \context_user::instance($user->id);
// Delete all the User's records in mdl_tool_cohortroles table by the specified approved context list.
$approvedcontextlist = new approved_contextlist($user, 'tool_cohortroles', [$usercontext->id]);
provider::delete_data_for_user($approvedcontextlist);
// Test the cohort roles records in mdl_tool_cohortroles table are still present.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(2, $cohortroles);
// Delete all the User's records in mdl_tool_cohortroles table by the specified approved context list.
$approvedcontextlist = new approved_contextlist($user, 'tool_cohortroles', $contextlist->get_contextids());
provider::delete_data_for_user($approvedcontextlist);
// Test the records in mdl_tool_cohortroles table is equals zero.
$cohortroles = $DB->get_records('tool_cohortroles', ['userid' => $user->id]);
$this->assertCount(0, $cohortroles);
}
/**
* Test that only users within a course context are fetched.
*/
public function test_get_users_in_context(): void {
$component = 'tool_cohortroles';
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
$this->setAdminUser();
$userlist = new \core_privacy\local\request\userlist($systemctx, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->setup_test_scenario_data($user->id, $systemctx, 1);
$this->setup_test_scenario_data($user->id, $coursecategoryctx, 1, 'Sausage roll 2',
'sausageroll2');
// The list of users within the system context should contain user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$this->assertTrue(in_array($user->id, $userlist->get_userids()));
// The list of users within the course category context should contain user.
$userlist = new \core_privacy\local\request\userlist($coursecategoryctx, $component);
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$this->assertTrue(in_array($user->id, $userlist->get_userids()));
// The list of users within the user context should be empty.
$userlist2 = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(0, $userlist2);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$component = 'tool_cohortroles';
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
// Create user3.
$user3 = $this->getDataGenerator()->create_user();
$usercontext3 = \context_user::instance($user3->id);
// Create course category.
$coursecategory = $this->getDataGenerator()->create_category();
$coursecategoryctx = \context_coursecat::instance($coursecategory->id);
$systemctx = \context_system::instance();
$this->setAdminUser();
$this->setup_test_scenario_data($user1->id, $systemctx, 1);
$this->setup_test_scenario_data($user2->id, $systemctx, 1, 'Sausage roll 2',
'sausageroll2');
$this->setup_test_scenario_data($user3->id, $coursecategoryctx, 1, 'Sausage roll 3',
'sausageroll3');
$userlist1 = new \core_privacy\local\request\userlist($systemctx, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(2, $userlist1);
$this->assertTrue(in_array($user1->id, $userlist1->get_userids()));
$this->assertTrue(in_array($user2->id, $userlist1->get_userids()));
// Convert $userlist1 into an approved_contextlist.
$approvedlist1 = new approved_userlist($systemctx, $component, [$user1->id]);
// Delete using delete_data_for_user.
provider::delete_data_for_users($approvedlist1);
// Re-fetch users in systemcontext.
$userlist1 = new \core_privacy\local\request\userlist($systemctx, $component);
provider::get_users_in_context($userlist1);
// The user data of user1in systemcontext should be deleted.
// The user data of user2 in systemcontext should be still present.
$this->assertCount(1, $userlist1);
$this->assertTrue(in_array($user2->id, $userlist1->get_userids()));
// Convert $userlist1 into an approved_contextlist in the user context.
$approvedlist2 = new approved_userlist($usercontext3, $component, $userlist1->get_userids());
// Delete using delete_data_for_user.
provider::delete_data_for_users($approvedlist2);
// Re-fetch users in systemcontext.
$userlist1 = new \core_privacy\local\request\userlist($systemctx, $component);
provider::get_users_in_context($userlist1);
// The user data in systemcontext should not be deleted.
$this->assertCount(1, $userlist1);
}
/**
* Helper function to setup tool_cohortroles records for testing a specific user.
*
* @param int $userid The ID of the user used for testing.
* @param int $nocohortroles The number of tool_cohortroles to create for the user.
* @param string $rolename The name of the role to be created.
* @param string $roleshortname The short name of the role to be created.
* @throws \core_competency\invalid_persistent_exception
* @throws coding_exception
*/
protected function setup_test_scenario_data($userid, $context, $nocohortroles, $rolename = 'Sausage Roll',
$roleshortname = 'sausageroll') {
$roleid = create_role($rolename, $roleshortname, 'mmmm');
$result = new \stdClass();
$result->contextid = $context->id;
for ($c = 0; $c < $nocohortroles; $c++) {
$cohort = $this->getDataGenerator()->create_cohort($result);
$params = (object)array(
'userid' => $userid,
'roleid' => $roleid,
'cohortid' => $cohort->id
);
api::create_cohort_role_assignment($params);
}
}
}
+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/>.
/**
* Plugin version info
*
* @package tool_cohortroles
* @copyright 2015 Damyon Wiese
* @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 = 'tool_cohortroles'; // Full name of the plugin (used for diagnostics).