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']));
}
}