Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,27 @@ Set via the block's edit form (`edit_form.php`):
Multiple instances are allowed per page (`instance_allow_multiple()`), so you can pin several
reports side by side.

## Migrating from Configurable Reports

Each `block_configurable_reports` block can be replaced with a "List of reports" block in one step.
It works from database rows only, so it still runs after Configurable Reports has been removed from
disk.

1. Import the reports with report_sql (**Import from Configurable Reports**), then publish them and
set each report's audience there. This plugin does not import or publish reports, and Configurable
Reports permissions are not migrated.
2. Open **Site administration > Plugins > Blocks > SQL report** and follow the migration link
(`/blocks/sqlreports/migrate_bcr.php`). It lists the blocks it will replace; confirm to run it.
Or from the command line: `php blocks/sqlreports/cli/migrate_bcr.php --dry-run`, then without
`--dry-run`.

Each new block keeps the old block's page placement (context, pages, region, weight), its per-page
hidden/shown state, per-user collapsed state, the `moodle/block:view` and `moodle/block:edit`
permission overrides, its title, and its "global" / "course" report settings (as "Show site reports"
and "Show course reports"). Configurable Reports' default title is not carried over. Each block is
migrated in its own transaction, so one failure leaves that block unchanged and the rest go ahead.
Blocks already replaced are gone, so running it again is safe.

## Capabilities

Defined in `db/access.php`:
Expand All @@ -103,6 +124,9 @@ The block grants *placement*; the report's own Report Builder access still gates
block_sqlreports.php Block class: init, formats, get_content, table/chart/list rendering
classes/display_mode.php Display mode enum (auto / table / chart / list)
classes/local/report_list.php List-of-reports scoping and access (web + mobile)
classes/local/bcr_migrate.php, bcr_migration_item.php Configurable Reports block migration
migrate_bcr.php, cli/migrate_bcr.php Migration admin page and CLI
settings.php Admin settings page (links to the migration)
classes/local/report_list_section.php, report_list_item.php, section_type.php List data types
edit_form.php Per-instance config form
db/access.php Capabilities
Expand All @@ -114,6 +138,7 @@ styles.css Chart modal / fullscreen layout, list styling
tests/block_test.php Block PHPUnit tests
tests/local/report_list_test.php report_list PHPUnit tests
tests/output/mobile_test.php Mobile output PHPUnit tests
tests/local/bcr_migrate_test.php Configurable Reports migration PHPUnit tests
tests/classes/helper.php Shared test helper trait
version.php Version, requires, dependency on report_sql
```
Expand Down
9 changes: 9 additions & 0 deletions block_sqlreports.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ public function instance_allow_multiple(): bool {
return true;
}

/**
* Site-level settings page, which links to the Configurable Reports migration.
*
* @return bool
*/
public function has_config(): bool {
return true;
}

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

namespace block_sqlreports\local;

use block_sqlreports\display_mode;

/**
* Replaces block_configurable_reports (BCR) block instances with block_sqlreports instances.
*
* A BCR block lists reports as links, so each one becomes a block_sqlreports block in
* {@see display_mode::ReportList} mode. Work is done from database rows only, never from the BCR
* plugin code, so it still runs after BCR has been removed from disk, as long as its block rows
* remain.
*
* Carried over as-is, so the new block shows wherever and to whomever the old one did:
* - placement: context, "show in subcontexts", page type and sub-page patterns, default region and weight;
* - per-page visibility and position overrides (`block_positions`, which hold the hide/show state);
* - per-user collapsed/docked state;
* - the block permission overrides for `moodle/block:view` and `moodle/block:edit`;
* - the block title and the "site reports" / "course reports" switches.
*
* Not touched: report publishing and audiences. Those belong to report_sql, and BCR's own
* permissions are not migrated.
*
* @package block_sqlreports
* @copyright 2026 Catalyst IT Australia
* @author Kevin Pham <kevinpham@catalyst-au.net>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class bcr_migrate {
/** Block name of the legacy block. */
private const OLD_BLOCK = 'configurable_reports';

/** Block name of the replacement block. */
private const NEW_BLOCK = 'sqlreports';

/** Block permission overrides that decide who can see or edit a block instance. */
private const BLOCK_CAPABILITIES = ['moodle/block:view', 'moodle/block:edit'];

/** Title BCR saves into a block when the admin never changes it. */
private const BCR_DEFAULT_TITLE = 'Configurable Reports';

/**
* Number of Configurable Reports blocks still waiting to be migrated.
*
* @return int
*/
public static function count_pending(): int {
global $DB;

return $DB->count_records('block_instances', ['blockname' => self::OLD_BLOCK]);
}

/**
* Replace every Configurable Reports block instance.
*
* Each block is migrated in its own transaction, so a failure leaves that block untouched and
* does not stop the others. Re-running only picks up blocks that are still there.
*
* @param bool $dryrun When true, report what would happen without writing anything.
* @return bcr_migration_item[] One item per old block, in id order.
*/
public static function migrate(bool $dryrun = false): array {
if ($dryrun) {
return self::migrate_instances(true);
}

$lockfactory = \core\lock\lock_config::get_lock_factory('block_sqlreports');
$lock = $lockfactory->get_lock('bcr_migrate', 0);
if (!$lock) {
throw new \moodle_exception('locktimeout');
}

try {
return self::migrate_instances(false);
} finally {
$lock->release();
}
}

/**
* Preview or replace pending blocks. Non-dry runs must hold the migration lock.
*
* @param bool $dryrun Whether to preview without changing blocks.
* @return bcr_migration_item[] One item per old block, in id order.
*/
private static function migrate_instances(bool $dryrun): array {
global $DB;
Comment thread
Copilot marked this conversation as resolved.
Resolved

$items = [];
foreach ($DB->get_records('block_instances', ['blockname' => self::OLD_BLOCK], 'id ASC') as $instance) {
$location = self::location($instance);
if ($dryrun) {
$items[] = new bcr_migration_item(
id: (int) $instance->id,
location: $location,
status: bcr_migration_item::MIGRATED
);
continue;
}

$transaction = $DB->start_delegated_transaction();
try {
$newid = self::replace($instance);
$transaction->allow_commit();
$items[] = new bcr_migration_item(
id: (int) $instance->id,
location: $location,
status: bcr_migration_item::MIGRATED,
newid: $newid
);
} catch (\Throwable $e) {
// Rollback rethrows the error it is given, so catch it to carry on with the next block.
try {
$transaction->rollback($e);
} catch (\Throwable $rethrown) {
$e = $rethrown;
}
$items[] = new bcr_migration_item(
id: (int) $instance->id,
location: $location,
status: bcr_migration_item::FAILED,
detail: $e->getMessage()
);
}
}
return $items;
}

/**
* Create the replacement for one old block, move its settings across and delete the old block.
*
* @param \stdClass $old The old block_instances row.
* @return int New block instance id.
*/
private static function replace(\stdClass $old): int {
global $DB;

$now = time();
$newid = (int) $DB->insert_record('block_instances', (object) [
'blockname' => self::NEW_BLOCK,
'parentcontextid' => $old->parentcontextid,
'showinsubcontexts' => $old->showinsubcontexts,
'requiredbytheme' => $old->requiredbytheme,
'pagetypepattern' => $old->pagetypepattern,
'subpagepattern' => $old->subpagepattern,
'defaultregion' => $old->defaultregion,
'defaultweight' => $old->defaultweight,
'configdata' => base64_encode(serialize(self::convert_config($old))),
Comment thread
matthewhilton marked this conversation as resolved.
Resolved
'timecreated' => $now,
'timemodified' => $now,
]);
$newcontext = \context_block::instance($newid);

// Per-page hide/show and position overrides.
foreach ($DB->get_records('block_positions', ['blockinstanceid' => $old->id]) as $position) {
unset($position->id);
$position->blockinstanceid = $newid;
$DB->insert_record('block_positions', $position);
}

// Per-user collapsed and docked state.
foreach (['block%dhidden', 'docked_block_instance_%d'] as $pattern) {
$DB->set_field(
'user_preferences',
'name',
sprintf($pattern, $newid),
['name' => sprintf($pattern, $old->id)]
);
}

// Who can see or edit the block.
$oldcontext = \context_block::instance((int) $old->id, IGNORE_MISSING);
if ($oldcontext) {
[$insql, $params] = $DB->get_in_or_equal(self::BLOCK_CAPABILITIES, SQL_PARAMS_NAMED);
$overrides = $DB->get_records_select(
'role_capabilities',
"contextid = :contextid AND capability $insql",
['contextid' => $oldcontext->id] + $params
);
foreach ($overrides as $override) {
unset($override->id);
$override->contextid = $newcontext->id;
$DB->insert_record('role_capabilities', $override);
}
$userids = $DB->get_fieldset_select(
'role_assignments',
'DISTINCT userid',
'contextid = :contextid',
['contextid' => $oldcontext->id]
);
$DB->set_field('role_assignments', 'contextid', $newcontext->id, ['contextid' => $oldcontext->id]);
foreach ($userids as $userid) {
mark_user_dirty($userid);
}
$oldcontext->delete();
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

// The old block's plugin code may be gone, so remove its rows directly.
$DB->delete_records('block_positions', ['blockinstanceid' => $old->id]);
$DB->delete_records('block_instances', ['id' => $old->id]);

return $newid;
}

/**
* The block_sqlreports configuration equivalent to a BCR block's configuration.
*
* @param \stdClass $old The old block_instances row.
* @return \stdClass
*/
private static function convert_config(\stdClass $old): \stdClass {
// Decoded the same way core does for block config.
$oldconfig = $old->configdata === '' ? new \stdClass() : unserialize_object(base64_decode($old->configdata));

// A BCR block that was never configured shows both lists. Once saved, a missing site-reports
// setting means off.
$unconfigured = (array) $oldconfig === [];
$config = (object) [
'displaymode' => display_mode::ReportList->value,
'showsitereports' => (int) ($unconfigured || !empty($oldconfig->displayglobalreports)),
'showcoursereports' => (int) (!isset($oldconfig->displayreportslist) || $oldconfig->displayreportslist),
];

// BCR saves its default title into the config, which would mislabel the new block.
$title = trim((string) ($oldconfig->title ?? ''));
if ($title !== '' && \core_text::strtolower($title) !== \core_text::strtolower(self::bcr_default_title())) {
$config->title = $title;
}
return $config;
}

/**
* BCR's default block title, in the site language when BCR's strings are still available.
*
* @return string
*/
private static function bcr_default_title(): string {
$strings = get_string_manager();
return $strings->string_exists('pluginname', 'block_configurable_reports')
? get_string('pluginname', 'block_configurable_reports')
: self::BCR_DEFAULT_TITLE;
}

/**
* Human readable location of a block, such as the course it is in.
*
* @param \stdClass $instance The old block_instances row.
* @return string
*/
private static function location(\stdClass $instance): string {
$context = \context::instance_by_id((int) $instance->parentcontextid, IGNORE_MISSING);
return $context ? $context->get_context_name(true, true) : get_string('unknown', 'block_sqlreports');
}
}
Loading
Loading