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
@@ -0,0 +1,295 @@
<?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\table;
use context;
use moodle_url;
use renderable;
use table_sql;
use html_writer;
use core_table\dynamic;
use core_reportbuilder\local\helpers\database;
use core_reportbuilder\local\filters\base;
use core_reportbuilder\local\models\report;
use core_reportbuilder\local\report\base as base_report;
use core_reportbuilder\local\report\filter;
use core\output\notification;
defined('MOODLE_INTERNAL') || die;
require_once("{$CFG->libdir}/tablelib.php");
/**
* Base report dynamic table 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_report_table extends table_sql implements dynamic, renderable {
/** @var report $persistent */
protected $persistent;
/** @var base_report $report */
protected $report;
/** @var string $groupbysql */
protected $groupbysql = '';
/** @var bool $editing */
protected $editing = false;
/**
* Initialises table SQL properties
*
* @param string $fields
* @param string $from
* @param array $joins
* @param string $where
* @param array $params
* @param array $groupby
*/
protected function init_sql(string $fields, string $from, array $joins, string $where, array $params,
array $groupby = []): void {
$wheres = [];
if ($where !== '') {
$wheres[] = $where;
}
// Track the index of conditions/filters as we iterate over them.
$conditionindex = $filterindex = 0;
// For each condition, we need to ensure their values are always accounted for in the report.
$conditionvalues = $this->report->get_condition_values();
foreach ($this->report->get_active_conditions() as $condition) {
[$conditionsql, $conditionparams] = $this->get_filter_sql($condition, $conditionvalues, 'c' . $conditionindex++);
if ($conditionsql !== '') {
$joins = array_merge($joins, $condition->get_joins());
$wheres[] = "({$conditionsql})";
$params = array_merge($params, $conditionparams);
}
}
// For each filter, we also need to apply their values (will differ according to user viewing the report).
if (!$this->editing) {
$filtervalues = $this->report->get_filter_values();
foreach ($this->report->get_active_filters() as $filter) {
[$filtersql, $filterparams] = $this->get_filter_sql($filter, $filtervalues, 'f' . $filterindex++);
if ($filtersql !== '') {
$joins = array_merge($joins, $filter->get_joins());
$wheres[] = "({$filtersql})";
$params = array_merge($params, $filterparams);
}
}
}
// Join all the filters into a SQL WHERE clause, falling back to all records.
if (!empty($wheres)) {
$wheresql = implode(' AND ', $wheres);
} else {
$wheresql = '1=1';
}
if (!empty($groupby)) {
$this->groupbysql = 'GROUP BY ' . implode(', ', $groupby);
}
// Add unique table joins.
$from .= ' ' . implode(' ', array_unique($joins));
$this->set_sql($fields, $from, $wheresql, $params);
$counttablealias = database::generate_alias();
$this->set_count_sql("
SELECT COUNT(1)
FROM (SELECT {$fields}
FROM {$from}
WHERE {$wheresql}
{$this->groupbysql}
) {$counttablealias}", $params);
}
/**
* Whether the current report table is being edited, in which case certain actions are not applied to it, e.g. user filtering
* and sorting. Default class value is false
*
* @param bool $editing
*/
public function set_report_editing(bool $editing): void {
$this->editing = $editing;
}
/**
* Return SQL fragments from given filter instance suitable for inclusion in table SQL
*
* @param filter $filter
* @param array $filtervalues
* @param string $paramprefix
* @return array [$sql, $params]
*/
private function get_filter_sql(filter $filter, array $filtervalues, string $paramprefix): array {
/** @var base $filterclass */
$filterclass = $filter->get_filter_class();
// Retrieve SQL fragments from the filter instance, process parameters if required.
[$sql, $params] = $filterclass::create($filter)->get_sql_filter($filtervalues);
if ($paramprefix !== '' && count($params) > 0) {
return database::sql_replace_parameters(
$sql,
$params,
fn(string $param) => "{$paramprefix}_{$param}",
);
}
return [$sql, $params];
}
/**
* Generate suitable SQL for the table
*
* @return string
*/
protected function get_table_sql(): string {
$sql = "SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where} {$this->groupbysql}";
$sort = $this->get_sql_sort();
if ($sort) {
$sql .= " ORDER BY {$sort}";
}
return $sql;
}
/**
* Override parent method of the same, to make use of a recordset and avoid issues with duplicate values in the first column
*
* @param int $pagesize
* @param bool $useinitialsbar
*/
public function query_db($pagesize, $useinitialsbar = true): void {
global $DB;
if (!$this->is_downloading()) {
$this->pagesize($pagesize, $DB->count_records_sql($this->countsql, $this->countparams));
$this->rawdata = $DB->get_recordset_sql($this->get_table_sql(), $this->sql->params, $this->get_page_start(),
$this->get_page_size());
} else {
$this->rawdata = $DB->get_recordset_sql($this->get_table_sql(), $this->sql->params);
}
}
/**
* Override parent method of the same, to ensure that any columns with custom sort fields are accounted for
*
* Because the base table_sql has "special" handling of fullname columns {@see table_sql::contains_fullname_columns}, we need
* to handle that here to ensure that any that are being sorted take priority over reportbuilders own aliases of the same
* columns. This prevents them appearing multiple times in a query, which SQL Server really doesn't like
*
* @return string
*/
public function get_sql_sort() {
$columnsbyalias = $this->report->get_active_columns_by_alias();
$columnsortby = [];
// First pass over sorted columns, to extract all the fullname fields from table_sql.
$sortedcolumns = $this->get_sort_columns();
$sortedcolumnsfullname = array_filter($sortedcolumns, static function(string $alias): bool {
return !preg_match('/^c[\d]+_/', $alias);
}, ARRAY_FILTER_USE_KEY);
// Iterate over all sorted report columns, replace with columns own fields if applicable.
foreach ($sortedcolumns as $alias => $order) {
$column = $columnsbyalias[$alias] ?? null;
// If the column is not being aggregated and defines custom sort fields, then use them.
if ($column && !$column->get_aggregation() &&
($sortfields = $column->get_sort_fields())) {
foreach ($sortfields as $sortfield) {
$columnsortby[$sortfield] = $order;
}
} else {
$columnsortby[$alias] = $order;
}
}
// Now ensure that any fullname sorted columns have duplicated aliases removed.
$columnsortby = array_filter($columnsortby, static function(string $alias) use ($sortedcolumnsfullname): bool {
if (preg_match('/^c[\d]+_(?<column>.*)$/', $alias, $matches)) {
return !array_key_exists($matches['column'], $sortedcolumnsfullname);
}
return true;
}, ARRAY_FILTER_USE_KEY);
return static::construct_order_by($columnsortby);
}
/**
* Get the context for the table (that of the report persistent)
*
* @return context
*/
public function get_context(): context {
return $this->persistent->get_context();
}
/**
* Set the base URL of the table to the current page URL
*/
public function guess_base_url(): void {
$this->baseurl = new moodle_url('/');
}
/**
* Override print_nothing_to_display to modity the output styles.
*/
public function print_nothing_to_display() {
global $OUTPUT;
echo $this->get_dynamic_table_html_start();
echo $this->render_reset_button();
if ($notice = $this->report->get_default_no_results_notice()) {
echo $OUTPUT->render(new notification($notice->out(), notification::NOTIFY_INFO, false));
}
echo $this->get_dynamic_table_html_end();
}
/**
* Override start of HTML to remove top pagination.
*/
public function start_html() {
// Render the dynamic table header.
echo $this->get_dynamic_table_html_start();
// Render button to allow user to reset table preferences.
echo $this->render_reset_button();
$this->wrap_html_start();
$this->set_caption($this->report::get_name(), ['class' => 'sr-only']);
echo html_writer::start_tag('div');
echo html_writer::start_tag('table', $this->attributes) . $this->render_caption();
}
}
@@ -0,0 +1,401 @@
<?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\table;
use core\output\notification;
use html_writer;
use moodle_exception;
use moodle_url;
use stdClass;
use core_reportbuilder\{datasource, manager};
use core_reportbuilder\local\models\report;
use core_reportbuilder\local\report\column;
use core_reportbuilder\output\column_aggregation_editable;
use core_reportbuilder\output\column_heading_editable;
/**
* Custom report dynamic table class
*
* @package core_reportbuilder
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class custom_report_table extends base_report_table {
/** @var datasource $report */
protected $report;
/** @var string Unique ID prefix for the table */
private const UNIQUEID_PREFIX = 'custom-report-table-';
/** @var bool Whether report is being edited (we don't want user filters/sorting to be applied when editing) */
protected const REPORT_EDITING = true;
/** @var float $querytimestart Time we began executing table SQL */
private $querytimestart = 0.0;
/**
* Table constructor. Note that the passed unique ID value must match the pattern "custom-report-table-(\d+)" so that
* dynamic updates continue to load the same report
*
* @param string $uniqueid
* @param string $download
* @throws moodle_exception For invalid unique ID
*/
public function __construct(string $uniqueid, string $download = '') {
if (!preg_match('/^' . self::UNIQUEID_PREFIX . '(?<id>\d+)$/', $uniqueid, $matches)) {
throw new moodle_exception('invalidcustomreportid', 'core_reportbuilder', '', null, $uniqueid);
}
parent::__construct($uniqueid);
$this->define_baseurl(new moodle_url('/reportbuilder/edit.php', ['id' => $matches['id']]));
// Load the report persistent, and accompanying report instance.
$this->persistent = new report($matches['id']);
$this->report = manager::get_report_from_persistent($this->persistent);
$fields = $groupby = [];
$maintable = $this->report->get_main_table();
$maintablealias = $this->report->get_main_table_alias();
$joins = $this->report->get_joins();
[$where, $params] = $this->report->get_base_condition();
$this->set_attribute('data-region', 'reportbuilder-table');
$this->set_attribute('class', $this->attributes['class'] . ' reportbuilder-table');
// Download options.
$this->showdownloadbuttonsat = [TABLE_P_BOTTOM];
$this->is_downloading($download ?? null, $this->persistent->get_formatted_name());
// Retrieve all report columns, exit early if there are none. Defining empty columns prevents errors during out().
$columns = $this->get_active_columns();
if (empty($columns)) {
$this->init_sql("{$maintablealias}.*", "{{$maintable}} {$maintablealias}", $joins, '1=0', []);
$this->define_columns([0]);
return;
}
// If we are aggregating any columns, we should group by the remaining ones.
$aggregatedcolumns = array_filter($columns, static function(column $column): bool {
return !empty($column->get_aggregation());
});
// Also take account of the report setting to show unique rows (only if no columns are being aggregated).
$hasaggregatedcolumns = !empty($aggregatedcolumns);
$showuniquerows = !$hasaggregatedcolumns && $this->persistent->get('uniquerows');
$columnheaders = $columnsattributes = [];
foreach ($columns as $column) {
$columnheading = $column->get_persistent()->get_formatted_heading($this->report->get_context());
$columnheaders[$column->get_column_alias()] = $columnheading !== '' ? $columnheading : $column->get_title();
// We need to determine for each column whether we should group by it's fields, to support aggregation.
$columnaggregation = $column->get_aggregation();
if ($showuniquerows || ($hasaggregatedcolumns && empty($columnaggregation))) {
$groupby = array_merge($groupby, $column->get_groupby_sql());
}
// Add each columns fields, joins and params to our report.
$fields = array_merge($fields, $column->get_fields());
$joins = array_merge($joins, $column->get_joins());
$params = array_merge($params, $column->get_params());
// Disable sorting for some columns.
if (!$column->get_is_sortable()) {
$this->no_sorting($column->get_column_alias());
}
// Add column attributes needed for card view.
$settings = $this->report->get_settings_values();
$showfirsttitle = $settings['cardview_showfirsttitle'] ?? false;
$visiblecolumns = max($settings['cardview_visiblecolumns'] ?? 1, count($this->columns));
if ($showfirsttitle || $column->get_persistent()->get('columnorder') > 1) {
$column->add_attributes(['data-cardtitle' => $columnheaders[$column->get_column_alias()]]);
}
if ($column->get_persistent()->get('columnorder') > $visiblecolumns) {
$column->add_attributes(['data-cardviewhidden' => '']);
}
// Generate column attributes to be included in each cell.
$columnsattributes[$column->get_column_alias()] = $column->get_attributes();
}
$this->define_columns(array_keys($columnheaders));
$this->define_headers(array_values($columnheaders));
// Add column attributes to the table.
$this->set_columnsattributes($columnsattributes);
// Table configuration.
$this->initialbars(false);
$this->collapsible(false);
$this->pageable(true);
$this->set_default_per_page($this->report->get_default_per_page());
// Initialise table SQL properties.
$this->set_report_editing(static::REPORT_EDITING);
$fieldsql = implode(', ', $fields);
$this->init_sql($fieldsql, "{{$maintable}} {$maintablealias}", $joins, $where, $params, $groupby);
}
/**
* Return a new instance of the class for given report ID
*
* @param int $reportid
* @param string $download
* @return static
*/
public static function create(int $reportid, string $download = ''): self {
return new static(self::UNIQUEID_PREFIX . $reportid, $download);
}
/**
* Get user preferred sort columns, overriding those of parent. If user has no preferences then use report defaults
*
* @return array
*/
public function get_sort_columns(): array {
$sortcolumns = parent::get_sort_columns();
if ($this->editing || empty($sortcolumns)) {
$sortcolumns = [];
$columns = $this->get_active_columns();
// We need to sort the columns by the configured sorting order.
usort($columns, static function(column $a, column $b): int {
return ($a->get_persistent()->get('sortorder') < $b->get_persistent()->get('sortorder')) ? -1 : 1;
});
foreach ($columns as $column) {
$persistent = $column->get_persistent();
if ($column->get_is_sortable() && $persistent->get('sortenabled')) {
$sortcolumns[$column->get_column_alias()] = $persistent->get('sortdirection');
}
}
}
return $sortcolumns;
}
/**
* Format each row of returned data, executing defined callbacks for the row and each column
*
* @param array|stdClass $row
* @return array
*/
public function format_row($row) {
$columns = $this->get_active_columns();
$formattedrow = [];
foreach ($columns as $column) {
$formattedrow[$column->get_column_alias()] = $column->format_value((array) $row);
}
return $formattedrow;
}
/**
* Download is disabled when editing the report
*
* @return string
*/
public function download_buttons(): string {
return '';
}
/**
* Get the columns of the custom report, returned instances being valid and available for the user
*
* @return column[]
*/
protected function get_active_columns(): array {
return $this->report->get_active_columns();
}
/**
* Override parent method for printing headers so we can render our custom controls in each cell
*/
public function print_headers() {
global $OUTPUT, $PAGE;
$columns = $this->get_active_columns();
if (empty($columns)) {
return;
}
$columns = array_values($columns);
$renderer = $PAGE->get_renderer('core');
echo html_writer::start_tag('thead');
echo html_writer::start_tag('tr');
foreach ($this->headers as $index => $title) {
$column = $columns[$index];
$headingeditable = new column_heading_editable(0, $column->get_persistent());
$aggregationeditable = new column_aggregation_editable(0, $column->get_persistent());
// Render table header cell, with all editing controls.
$headercell = $OUTPUT->render_from_template('core_reportbuilder/table_header_cell', [
'entityname' => $this->report->get_entity_title($column->get_entity_name()),
'name' => $column->get_title(),
'headingeditable' => $headingeditable->render($renderer),
'aggregationeditable' => $aggregationeditable->render($renderer),
'movetitle' => get_string('movecolumn', 'core_reportbuilder', $column->get_title()),
]);
echo html_writer::tag('th', $headercell, [
'class' => 'border-right border-left',
'scope' => 'col',
'data-region' => 'column-header',
'data-column-id' => $column->get_persistent()->get('id'),
'data-column-name' => $column->get_title(),
'data-column-position' => $index + 1,
]);
}
echo html_writer::end_tag('tr');
echo html_writer::end_tag('thead');
}
/**
* Override print_nothing_to_display to ensure that column headers are always added.
*/
public function print_nothing_to_display() {
global $OUTPUT;
$this->start_html();
$this->print_headers();
echo html_writer::end_tag('table');
echo html_writer::end_tag('div');
$this->wrap_html_finish();
// With the live editing disabled we need to notify user that data is shown only in preview mode.
if ($this->editing && !self::show_live_editing()) {
$notificationmsg = get_string('customreportsliveeditingdisabled', 'core_reportbuilder');
$notificationtype = notification::NOTIFY_WARNING;
} else {
$notificationmsg = get_string('nothingtodisplay');
$notificationtype = notification::NOTIFY_INFO;
}
$notification = (new notification($notificationmsg, $notificationtype, false))
->set_extra_classes(['mt-3']);
echo $OUTPUT->render($notification);
echo $this->get_dynamic_table_html_end();
}
/**
* Provide additional table debugging during editing
*/
public function wrap_html_finish(): void {
global $OUTPUT;
if ($this->editing && debugging('', DEBUG_DEVELOPER)) {
$params = array_map(static function(string $param, $value): array {
return ['param' => $param, 'value' => var_export($value, true)];
}, array_keys($this->sql->params), $this->sql->params);
echo $OUTPUT->render_from_template('core_reportbuilder/local/report/debug', [
'query' => $this->get_table_sql(),
'params' => $params,
'duration' => $this->querytimestart ?
format_time($this->querytimestart - microtime(true)) : null,
]);
}
}
/**
* Override get_row_cells_html to add an extra cell with the toggle button for card view.
*
* @param string $rowid
* @param array $row
* @param array|null $suppresslastrow
* @return string
*/
public function get_row_cells_html(string $rowid, array $row, ?array $suppresslastrow): string {
$html = parent::get_row_cells_html($rowid, $row, $suppresslastrow);
// Add extra 'td' in the row with card toggle button (only visible in card view).
$visiblecolumns = $this->report->get_settings_values()['cardview_visiblecolumns'] ?? 1;
if ($visiblecolumns < count($this->columns)) {
$buttonicon = html_writer::tag('i', '', ['class' => 'fa fa-angle-down']);
// We need a cleaned version (without tags/entities) of the first row column to use as toggle button.
$rowfirstcolumn = strip_tags((string) reset($row));
$buttontitle = $rowfirstcolumn !== ''
? get_string('showhide', 'core_reportbuilder', html_entity_decode($rowfirstcolumn, ENT_COMPAT))
: get_string('showhidecard', 'core_reportbuilder');
$button = html_writer::tag('button', $buttonicon, [
'type' => 'button',
'class' => 'btn collapsed',
'title' => $buttontitle,
'data-toggle' => 'collapse',
'data-action' => 'toggle-card'
]);
$html .= html_writer::tag('td', $button, ['class' => 'card-toggle d-none']);
}
return $html;
}
/**
* Overriding this method to handle live editing setting.
* @param int $pagesize
* @param bool $useinitialsbar
* @param string $downloadhelpbutton
*/
public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') {
$this->pagesize = $pagesize;
$this->setup();
// If the live editing setting is disabled, we not need to fetch custom report data except in preview mode.
if (!$this->editing || self::show_live_editing()) {
$this->querytimestart = microtime(true);
$this->query_db($pagesize, $useinitialsbar);
$this->build_table();
$this->close_recordset();
}
$this->finish_output();
}
/**
* Whether or not report data should be included in the table while in editing mode
*
* @return bool
*/
private static function show_live_editing(): bool {
global $CFG;
return !empty($CFG->customreportsliveediting);
}
/**
* Check if the user has the capability to access this table.
*
* @return bool Return true if capability check passed.
*/
public function has_capability(): bool {
return \core_reportbuilder\permission::can_edit_report($this->persistent);
}
}
@@ -0,0 +1,40 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
declare(strict_types=1);
namespace core_reportbuilder\table;
use core_table\local\filter\filterset;
/**
* Custom report dynamic table filterset class
*
* @package core_reportbuilder
* @copyright 2021 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class custom_report_table_filterset extends filterset {
/**
* Get the required filters
*
* @return array.
*/
public function get_required_filters(): array {
return [];
}
}
@@ -0,0 +1,86 @@
<?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\table;
use moodle_url;
/**
* Custom report view dynamic table class
*
* @package core_reportbuilder
* @copyright 2021 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class custom_report_table_view extends custom_report_table {
/** @var bool We're pre/viewing the report, not editing it */
protected const REPORT_EDITING = false;
/**
* Override printed headers, to use those of grandparent class
*/
public function print_headers() {
$columns = $this->get_active_columns();
if (empty($columns)) {
return;
}
base_report_table::print_headers();
}
/**
* Override base implementation, return pagesize as defined in table filterset
*
* @return int
*/
public function get_default_per_page(): int {
$filterset = $this->get_filterset();
return $filterset->get_filter('pagesize')->current();
}
/**
* Get the html for the download buttons
*
* @return string
*/
public function download_buttons(): string {
global $OUTPUT;
if (!$this->is_downloading()) {
return $OUTPUT->download_dataformat_selector(
get_string('downloadas', 'table'),
new moodle_url('/reportbuilder/download.php'),
'download',
['id' => $this->persistent->get('id')]
);
}
return '';
}
/**
* Check if the user has the capability to access this table.
*
* @return bool Return true if capability check passed.
*/
public function has_capability(): bool {
return \core_reportbuilder\permission::can_view_report($this->persistent);
}
}
@@ -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 core_reportbuilder\table;
use core_table\local\filter\filterset;
use core_table\local\filter\integer_filter;
/**
* Custom report dynamic table filterset class
*
* @package core_reportbuilder
* @copyright 2021 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class custom_report_table_view_filterset extends filterset {
/**
* Get the required filters
*
* @return array.
*/
public function get_required_filters(): array {
return [
'pagesize' => integer_filter::class,
];
}
}
@@ -0,0 +1,316 @@
<?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\table;
use action_menu;
use action_menu_filler;
use core_table\local\filter\filterset;
use html_writer;
use moodle_exception;
use stdClass;
use core_reportbuilder\{manager, system_report};
use core_reportbuilder\local\models\report;
/**
* System report dynamic table class
*
* @package core_reportbuilder
* @copyright 2020 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class system_report_table extends base_report_table {
/** @var system_report $report */
protected $report;
/** @var string Unique ID prefix for the table */
private const UNIQUEID_PREFIX = 'system-report-table-';
/**
* Table constructor. Note that the passed unique ID value must match the pattern "system-report-table-(\d+)" so that
* dynamic updates continue to load the same report
*
* @param string $uniqueid
* @param array $parameters
* @throws moodle_exception For invalid unique ID
*/
public function __construct(string $uniqueid, array $parameters = []) {
if (!preg_match('/^' . self::UNIQUEID_PREFIX . '(?<id>\d+)$/', $uniqueid, $matches)) {
throw new moodle_exception('invalidsystemreportid', 'core_reportbuilder', '', null, $uniqueid);
}
parent::__construct($uniqueid);
// If we are loading via a dynamic table AJAX request, defer the report loading until the filterset is added to
// the table, as it is used to populate the report $parameters during construction.
$serviceinfo = optional_param('info', null, PARAM_RAW);
if ($serviceinfo !== 'core_table_get_dynamic_table_content') {
$this->load_report_instance((int) $matches['id'], $parameters);
}
}
/**
* Load the report persistent, and accompanying system report instance.
*
* @param int $reportid
* @param array $parameters
*/
private function load_report_instance(int $reportid, array $parameters): void {
global $PAGE;
$this->persistent = new report($reportid);
$this->report = manager::get_report_from_persistent($this->persistent, $parameters);
// TODO: can probably be removed pending MDL-72974.
$PAGE->set_context($this->persistent->get_context());
$fields = $this->report->get_base_fields();
$maintable = $this->report->get_main_table();
$maintablealias = $this->report->get_main_table_alias();
$joins = $this->report->get_joins();
[$where, $params] = $this->report->get_base_condition();
$this->set_attribute('data-region', 'reportbuilder-table');
$this->set_attribute('class', $this->attributes['class'] . ' reportbuilder-table');
// Download options.
$this->showdownloadbuttonsat = [TABLE_P_BOTTOM];
$this->is_downloading($parameters['download'] ?? null, $this->report->get_downloadfilename());
// Retrieve all report columns. If we are downloading the report, remove as required.
$columns = $this->report->get_active_columns();
if ($this->is_downloading()) {
$columns = array_diff_key($columns,
array_flip($this->report->get_exclude_columns_for_download()));
}
$columnheaders = $columnsattributes = [];
// Check whether report has checkbox toggle defined, note that select all is excluded during download.
if (($checkbox = $this->report->get_checkbox_toggleall(true)) && !$this->is_downloading()) {
$columnheaders['selectall'] = $PAGE->get_renderer('core')->render($checkbox);
$this->no_sorting('selectall');
}
$columnindex = 1;
foreach ($columns as $identifier => $column) {
$column->set_index($columnindex++);
$columnheaders[$column->get_column_alias()] = $column->get_title();
// Specify whether column should behave as a user fullname column unless the column has a custom title set.
if (preg_match('/^user:fullname.*$/', $column->get_unique_identifier()) && !$column->has_custom_title()) {
$this->userfullnamecolumns[] = $column->get_column_alias();
}
// Add each columns fields, joins and params to our report.
$fields = array_merge($fields, $column->get_fields());
$joins = array_merge($joins, $column->get_joins());
$params = array_merge($params, $column->get_params());
// Disable sorting for some columns.
if (!$column->get_is_sortable()) {
$this->no_sorting($column->get_column_alias());
}
// Generate column attributes to be included in each cell.
$columnsattributes[$column->get_column_alias()] = $column->get_attributes();
}
// If the report has any actions then append appropriate column, note that actions are excluded during download.
if ($this->report->has_actions() && !$this->is_downloading()) {
$columnheaders['actions'] = html_writer::tag('span', get_string('actions', 'core_reportbuilder'), [
'class' => 'sr-only',
]);
$this->no_sorting('actions');
}
$this->define_columns(array_keys($columnheaders));
$this->define_headers(array_values($columnheaders));
// Add column attributes to the table.
$this->set_columnsattributes($columnsattributes);
// Initial table sort column.
if ($sortcolumn = $this->report->get_initial_sort_column()) {
$this->sortable(true, $sortcolumn->get_column_alias(), $this->report->get_initial_sort_direction());
}
// Table configuration.
$this->initialbars(false);
$this->collapsible(false);
$this->pageable(true);
$this->set_default_per_page($this->report->get_default_per_page());
// Initialise table SQL properties.
$fieldsql = implode(', ', $fields);
$this->init_sql($fieldsql, "{{$maintable}} {$maintablealias}", $joins, $where, $params);
}
/**
* Return a new instance of the class for given report ID. We include report parameters here so they are present during
* initialisation
*
* @param int $reportid
* @param array $parameters
* @return static
*/
public static function create(int $reportid, array $parameters): self {
return new static(self::UNIQUEID_PREFIX . $reportid, $parameters);
}
/**
* Set the filterset in the table class. We set the report parameters here so that they are persisted while paging
*
* @param filterset $filterset
*/
public function set_filterset(filterset $filterset): void {
$reportid = $filterset->get_filter('reportid')->current();
$parameters = $filterset->get_filter('parameters')->current();
$this->load_report_instance($reportid, json_decode($parameters, true));
parent::set_filterset($filterset);
}
/**
* Override parent method for retrieving row class with that defined by the system report
*
* @param array|stdClass $row
* @return string
*/
public function get_row_class($row) {
return $this->report->get_row_class((object) $row);
}
/**
* Format each row of returned data, executing defined callbacks for the row and each column
*
* @param array|stdClass $row
* @return array
*/
public function format_row($row) {
global $PAGE;
$this->report->row_callback((object) $row);
// Walk over the row, and for any key that matches one of our column aliases, call that columns format method.
$columnsbyalias = $this->report->get_active_columns_by_alias();
$row = (array) $row;
array_walk($row, static function(&$value, $key) use ($columnsbyalias, $row): void {
if (array_key_exists($key, $columnsbyalias)) {
$value = $columnsbyalias[$key]->format_value($row);
}
});
// Check whether report has checkbox toggle defined.
if ($checkbox = $this->report->get_checkbox_toggleall(false, (object) $row)) {
$row['selectall'] = $PAGE->get_renderer('core')->render($checkbox);
}
// Now check for any actions.
if ($this->report->has_actions()) {
$row['actions'] = $this->format_row_actions((object) $row);
}
return $row;
}
/**
* Return formatted actions column for the row
*
* @param stdClass $row
* @return string
*/
private function format_row_actions(stdClass $row): string {
global $OUTPUT;
$menu = new action_menu();
$menu->set_menu_trigger($OUTPUT->pix_icon('a/setting', get_string('actions', 'core_reportbuilder')));
$actions = array_filter($this->report->get_actions(), function($action) use ($row) {
// Only return dividers and action items who can be displayed for current users.
return $action instanceof action_menu_filler || $action->get_action_link($row);
});
$totalactions = count($actions);
$actionvalues = array_values($actions);
foreach ($actionvalues as $position => $action) {
if ($action instanceof action_menu_filler) {
$ispreviousdivider = array_key_exists($position - 1, $actionvalues) &&
($actionvalues[$position - 1] instanceof action_menu_filler);
$isnextdivider = array_key_exists($position + 1, $actionvalues) &&
($actionvalues[$position + 1] instanceof action_menu_filler);
$isfirstdivider = ($position === 0);
$islastdivider = ($position === $totalactions - 1);
// Avoid add divider at last/first position and having multiple fillers in a row.
if ($ispreviousdivider || $isnextdivider || $isfirstdivider || $islastdivider) {
continue;
}
$actionlink = $action;
} else {
// Ensure the action link can be displayed for the current row.
$actionlink = $action->get_action_link($row);
}
if ($actionlink) {
$menu->add($actionlink);
}
}
return $OUTPUT->render($menu);
}
/**
* Get the html for the download buttons
*
* @return string
*/
public function download_buttons(): string {
global $OUTPUT;
if ($this->report->can_be_downloaded() && !$this->is_downloading()) {
return $OUTPUT->download_dataformat_selector(
get_string('downloadas', 'table'),
new \moodle_url('/reportbuilder/download.php'),
'download',
[
'id' => $this->persistent->get('id'),
'parameters' => json_encode($this->report->get_parameters()),
]
);
}
return '';
}
/**
* Check if the user has the capability to access this table.
*
* @return bool Return true if capability check passed.
*/
public function has_capability(): bool {
try {
$this->report->require_can_view();
return true;
} catch (\core_reportbuilder\report_access_exception $e) {
return false;
}
}
}
@@ -0,0 +1,45 @@
<?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\table;
use core_table\local\filter\filterset;
use core_table\local\filter\integer_filter;
use core_table\local\filter\string_filter;
/**
* System report dynamic table filterset class
*
* @package core_reportbuilder
* @copyright 2020 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class system_report_table_filterset extends filterset {
/**
* Get the required filters
*
* @return array.
*/
public function get_required_filters(): array {
return [
'reportid' => integer_filter::class,
'parameters' => string_filter::class,
];
}
}