Commit 70085ef7 authored by David Matamoros's avatar David Matamoros
Browse files

MDL-72588 reportbuilder: implement audience helpers and classes.



Create the base audience class, to be extended by all audience types
across the site. Implement types allowing audiences to be created per
user, cohort or system role assignment.

The helper class is used for interrogating report audience instances
and retrieving access lists of those users able to view specific
reports.

Co-authored-by: Paul Holden's avatarPaul Holden <paulh@moodle.com>
parent 9113f9d2
<?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 core_cohort\reportbuilder\audience;
use context;
use context_system;
use core_course_category;
use stdClass;
use core_reportbuilder\local\audiences\base;
use core_reportbuilder\local\helpers\database;
use MoodleQuickForm;
/**
* The backend class for Cohort member audience type
*
* @package core_reportbuilder
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cohortmember extends base {
/**
* Adds audience's elements to the given mform
*
* @param MoodleQuickForm $mform The form to add elements to
*/
public function get_config_form(MoodleQuickForm $mform): void {
$cohorts = self::get_cohorts();
$mform->addElement('autocomplete', 'cohorts', get_string('selectfromcohort', 'cohort'),
$cohorts, ['multiple' => true]);
$mform->addRule('cohorts', null, 'required', null, 'client');
}
/**
* Helps to build SQL to retrieve users that matches the current report audience
*
* @param string $usertablealias
* @return array array of three elements [$join, $where, $params]
*/
public function get_sql(string $usertablealias): array {
global $DB;
$cm = database::generate_alias();
$cohorts = $this->get_configdata()['cohorts'];
$prefix = database::generate_param_name() . '_';
[$insql, $inparams] = $DB->get_in_or_equal($cohorts, SQL_PARAMS_NAMED, $prefix);
$join = "JOIN {cohort_members} {$cm}
ON ({$cm}.userid = {$usertablealias}.id)";
return [$join, "{$cm}.cohortid " . $insql, $inparams];
}
/**
* Return user friendly name of this audience type
*
* @return string
*/
public function get_name(): string {
return get_string('memberofcohort', 'cohort');
}
/**
* Return the description for the audience.
*
* @return string
*/
public function get_description(): string {
global $DB;
$cohortlist = [];
$cohortids = $this->get_configdata()['cohorts'];
$cohorts = $DB->get_records_list('cohort', 'id', $cohortids, 'name');
foreach ($cohorts as $cohort) {
$cohortlist[] = format_string($cohort->name, true, ['context' => $cohort->contextid, 'escape' => false]);
}
return $this->format_description_for_multiselect($cohortlist);
}
/**
* If the current user is able to add this audience.
*
* @return bool
*/
public function user_can_add(): bool {
// Check system context first.
if (has_capability('moodle/cohort:view', context_system::instance())) {
return true;
}
// If there is at least one category with given permissions, user can add.
return !empty(core_course_category::make_categories_list('moodle/cohort:view'));
}
/**
* Returns if this audience type is available for the user
*
* Check if there are available cohorts in the system for this user to use.
*
* @return bool
*/
public function is_available(): bool {
return !empty(self::get_cohorts());
}
/**
* If the current user is able to edit this audience.
*
* @return bool
*/
public function user_can_edit(): bool {
global $DB;
$canedit = true;
$cohortids = $this->get_configdata()['cohorts'];
$cohorts = $DB->get_records_list('cohort', 'id', $cohortids);
foreach ($cohorts as $cohort) {
$context = context::instance_by_id($cohort->contextid, MUST_EXIST);
$canedit = $canedit && has_capability('moodle/cohort:view', $context);
if ($canedit === false) {
break;
}
}
return $canedit;
}
/**
* Cohorts selector.
*
* @return array
*/
private static function get_cohorts(): array {
global $CFG;
require_once($CFG->dirroot.'/cohort/lib.php');
$cohortslist = [];
// Search cohorts user can view.
$usercohorts = cohort_get_all_cohorts(0, 0);
// The previous method doesn't check cohorts on system context.
$syscontext = context_system::instance();
$cohorts = array_filter($usercohorts['cohorts'], static function(stdClass $cohort) use ($syscontext): bool {
return ($cohort->contextid != $syscontext->id) || has_capability('moodle/cohort:view', $syscontext);
});
foreach ($cohorts as $cohort) {
$cohortslist[$cohort->id] = format_string($cohort->name, true, [
'context' => $cohort->contextid,
'escape' => false,
]);
}
return $cohortslist;
}
}
<?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 core_cohort\reportbuilder\audience;
use advanced_testcase;
use context;
use core_reportbuilder_generator;
use core_user\reportbuilder\datasource\users;
/**
* Unit tests for cohort member report audience type
*
* @package core_reportbuilder
* @covers \core_cohort\reportbuilder\audience\cohortmember
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cohortmember_test extends advanced_testcase {
/**
* Test that this audience type description is generated correctly
*/
public function test_get_description(): void {
$this->resetAfterTest();
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
$cohort = self::getDataGenerator()->create_cohort();
$audience = cohortmember::create($report->get('id'), ['cohorts' => [$cohort->id]]);
$this->assertEquals($cohort->name, $audience->get_description());
}
/**
* Test if user can add this audience type to the report
*/
public function test_user_can_add(): void {
$this->resetAfterTest();
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
// Admin user.
self::setAdminUser();
$cohort = self::getDataGenerator()->create_cohort();
$context = context::instance_by_id($cohort->contextid);
$audience = cohortmember::create($report->get('id'), ['cohorts' => [$cohort->id]]);
$this->assertTrue($audience->user_can_add());
// Non-priveleged user.
$user = self::getDataGenerator()->create_user();
self::setUser($user);
$this->assertFalse($audience->user_can_add());
// Grant priveleges to user (moodle/cohort:view).
$roleid = create_role('Dummy role', 'dummyrole', 'dummy role description');
assign_capability('moodle/cohort:view', CAP_ALLOW, $roleid, $context->id);
role_assign($roleid, $user->id, $context->id);
$this->assertTrue($audience->user_can_add());
}
/**
* Test if user can edit this audience type
*/
public function test_user_can_edit(): void {
$this->resetAfterTest();
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
$cohort = self::getDataGenerator()->create_cohort();
$context = context::instance_by_id($cohort->contextid);
$audience = cohortmember::create($report->get('id'), ['cohorts' => [$cohort->id]]);
// Admin user.
self::setAdminUser();
$this->assertTrue($audience->user_can_edit());
// Non-priveleged user.
$user = self::getDataGenerator()->create_user();
self::setUser($user);
$this->assertFalse($audience->user_can_edit());
// Grant priveleges to user (moodle/cohort:view).
$roleid = create_role('Dummy role', 'dummyrole', 'dummy role description');
assign_capability('moodle/cohort:view', CAP_ALLOW, $roleid, $context->id);
role_assign($roleid, $user->id, $context->id);
$this->assertTrue($audience->user_can_edit());
}
/**
* Test that sql generated is correct
*/
public function test_get_sql(): void {
global $DB;
$this->resetAfterTest();
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
$cohort = self::getDataGenerator()->create_cohort();
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$user3 = $this->getDataGenerator()->create_user();
// Add user1 into cohort.
cohort_add_member($cohort->id, $user1->id);
// Add user3 into cohort.
cohort_add_member($cohort->id, $user3->id);
$audience = cohortmember::create($report->get('id'), ['cohorts' => [$cohort->id]]);
[$join, $where, $params] = $audience->get_sql('u');
$query = 'SELECT u.* FROM {user} u ' . $join . ' WHERE ' . $where;
$records = $DB->get_records_sql($query, $params);
$this->assertEqualsCanonicalizing([$user1->id, $user3->id], array_column($records, 'id'));
}
/**
* Test if this audience type is available to use
*/
public function test_is_available(): void {
$this->resetAfterTest();
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
self::setAdminUser();
// Check with no cohorts available in the system.
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
$audience = cohortmember::create($report->get('id'), ['cohorts' => []]);
$this->assertFalse($audience->is_available());
// Check with cohorts available in the system.
self::getDataGenerator()->create_cohort();
$report = $generator->create_report([
'name' => 'My report',
'source' => users::class,
'default' => false,
]);
$audience2 = cohortmember::create($report->get('id'), ['cohorts' => []]);
$this->assertTrue($audience2->is_available());
}
}
......@@ -81,6 +81,7 @@ $string['cachedef_postprocessedcss'] = 'Post processed CSS';
$string['cachedef_tagindexbuilder'] = 'Search results for tagged items';
$string['cachedef_questiondata'] = 'Question definitions';
$string['cachedef_recommendation_favourite_course_content_items'] = 'Recommendation of course content items';
$string['cachedef_reportbuilder_allowed_reports'] = 'Users allowed reports according to audience';
$string['cachedef_repositories'] = 'Repositories instances data';
$string['cachedef_roledefs'] = 'Role definitions';
$string['cachedef_grade_categories'] = 'Grade category queries';
......
......@@ -31,6 +31,7 @@ $string['iso6391'] = 'en';
$string['iso6392'] = 'eng';
$string['labelsep'] = ': ';
$string['listsep'] = ',';
$string['listitemssep'] = ', ';
$string['locale'] = 'en_AU.UTF-8';
$string['localecldr'] = 'en-AU';
$string['localewin'] = 'English_Australia.1252';
......
......@@ -24,6 +24,7 @@
$string['actions'] = 'Actions';
$string['addcolumn'] = 'Add column \'{$a}\'';
$string['addusers'] = 'Add users manually';
$string['aggregatecolumn'] = 'Aggregate column \'{$a}\'';
$string['aggregationavg'] = 'Average';
$string['aggregationcount'] = 'Count';
......@@ -35,6 +36,8 @@ $string['aggregationmin'] = 'Minimum';
$string['aggregationnone'] = 'No aggregation';
$string['aggregationpercent'] = 'Percentage';
$string['aggregationsum'] = 'Sum';
$string['allsiteusers'] = 'All site users';
$string['allusers'] = 'All users';
$string['apply'] = 'Apply';
$string['columnadded'] = 'Added column \'{$a}\'';
$string['columnaggregated'] = 'Aggregated column \'{$a}\'';
......@@ -115,8 +118,10 @@ $string['filters'] = 'Filters';
$string['filters_help'] = 'Report filters allow users viewing the report to further limit the data being displayed, by selecting their own values for each filter. Filter values are stored on a per-user basis.';
$string['filtersreset'] = 'Filters reset';
$string['filterstartswith'] = 'Starts with';
$string['hassystemrole'] = 'Assigned system role';
$string['includedefaultsetup'] = 'Include default setup';
$string['includedefaultsetup_help'] = 'Populate report with default layout as defined by the selected source. These include pre-defined columns, filters and conditions.';
$string['manuallyaddedusers'] = 'Manually added users';
$string['movecolumn'] = 'Move column \'{$a}\'';
$string['movecondition'] = 'Move condition \'{$a}\'';
$string['movefilter'] = 'Move filter \'{$a}\'';
......
......@@ -523,4 +523,13 @@ $definitions = array(
'changesincourse',
],
],
// Users allowed reports according to audience.
'reportbuilder_allowed_reports' => [
'mode' => cache_store::MODE_APPLICATION,
'simplekeys' => true,
'simpledata' => true,
'staticacceleration' => true,
'ttl' => 1800,
],
);
<?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 core_reportbuilder\local\audiences;
use core_plugin_manager;
use MoodleQuickForm;
use stdClass;
use core\output\notification;
use core_reportbuilder\local\models\audience;
use core_reportbuilder\report_access_exception;
/**
* Audience base class
*
* @package core_reportbuilder
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class base {
/** @var int Maximim number of multi-select elements to show in description, before appending "plus X more" */
private const MULTI_SELECT_LIMIT = 5;
/** @var audience The persistent object associated with this audience */
protected $audience;
/**
* Protected constructor, please use the static instance method.
*/
protected function __construct() {
}
/**
* Loads an existing instance of audience with persistent
*
* @param int $id
* @param null|stdClass $record
* @return self|null
*/
final public static function instance(int $id = 0, ?stdClass $record = null): ?self {
$persistent = new audience($id, $record);
// Needed for get_audience_types() method.
if (!$classname = $persistent->get('classname')) {
// Use the called class name.
$classname = get_called_class();
$persistent->set('classname', $classname);
}
// Check if audience type class still exists in the system.
if (!class_exists($classname)) {
return null;
}
$instance = new $classname();
$instance->audience = $persistent;
return $instance;
}
/**
* Creates a new audience and saves it to database
*
* @param int $reportid
* @param array $configdata
* @return self
*/
final public static function create(int $reportid, array $configdata): self {
$record = new stdClass();
$record->reportid = $reportid;
$record->classname = get_called_class();
$record->configdata = json_encode($configdata);
$instance = self::instance(0, $record);
$instance->audience->save();
return $instance;
}
/**
* Helps to build SQL to retrieve users that matches the current audience
*
* Implementations must use api::generate_alias() for table/column aliases
* and api::generate_param_name() for named parameters
*
* @param string $usertablealias
* @return array array of three elements [$join, $where, $params]
*/
abstract public function get_sql(string $usertablealias): array;
/**
* Returns string for audience category.
*
* @return string
*/
final public function get_category(): string {
[$component] = explode('\\', get_class($this));
if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
return $plugininfo->displayname;
}
return get_string('site');
}
/**
* If the current user is able to add this audience type
*
* @return bool
*/
abstract public function user_can_add(): bool;
/**
* If the current user is able to edit this audience type
*
* @return bool
*/
abstract public function user_can_edit(): bool;
/**
* If the current user is able to use this audience type
*
* This method needs to return true if audience type is available to user for
* reasons other than permission check, which is done in {@see user_can_add}.
* (e.g. user can add cohort audience type only if there is at least one cohort
* they can access).
*
* @return bool
*/
public function is_available(): bool {
return true;
}
/**
* Return user friendly name of the audience type
*
* @return string
*/
abstract public function get_name(): string;
/**
* Return the description of this audience type
*
* @return string
*/
abstract public function get_description(): string;
/**
* Helper to format descriptions for audience types that may contain many selected elements, limiting number show according
* to {@see MULTI_SELECT_LIMIT} constant value
*
* @param array $elements
* @return string
*/
protected function format_description_for_multiselect(array $elements): string {
global $OUTPUT;
// Warn user if there are no elements (because they may no longer exist).
$elementcount = count($elements);
if ($elementcount === 0) {
$notification = new notification(get_string('nothingtodisplay'), notification::NOTIFY_WARNING);