Merge branch 'MDL-74271-master-squashed' of https://github.com/andrewnicols/moodle

This commit is contained in:
Jun Pataleta 2022-04-07 20:52:10 +08:00
commit ac3e77b1b1
8 changed files with 820 additions and 192 deletions

View File

@ -37,6 +37,10 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("{$CFG->libdir}/db/upgradelib.php");
/**
* Upgrade the calendar_month block
* @param int $oldversion
@ -58,36 +62,8 @@ function xmldb_block_calendar_month_upgrade($oldversion, $block) {
// Put any upgrade step following this.
if ($oldversion < 2022030200) {
$context = context_system::instance();
// Begin looking for any and all customised /my pages.
$pageselect = 'name = :name and private = :private';
$pageparams['name'] = '__default';
$pageparams['private'] = 1;
$pages = $DB->get_recordset_select('my_pages', $pageselect, $pageparams);
foreach ($pages as $subpage) {
$blockinstance = $DB->get_record('block_instances', ['blockname' => 'calendar_month',
'pagetypepattern' => 'my-index', 'subpagepattern' => $subpage->id]);
if (!$blockinstance) {
// Insert the calendar month into the default index page.
$blockinstance = new stdClass;
$blockinstance->blockname = 'calendar_month';
$blockinstance->parentcontextid = $context->id;
$blockinstance->showinsubcontexts = false;
$blockinstance->pagetypepattern = 'my-index';
$blockinstance->subpagepattern = $subpage->id;
$blockinstance->defaultregion = 'content';
$blockinstance->defaultweight = 0;
$blockinstance->timecreated = time();
$blockinstance->timemodified = time();
$DB->insert_record('block_instances', $blockinstance);
} else if ($blockinstance->defaultregion !== 'content') {
$blockinstance->defaultregion = 'content';
$DB->update_record('block_instances', $blockinstance);
}
}
$pages->close();
// Update all calendar_month blocks in the my-index to be in the main content region.
upgrade_block_set_defaultregion('calendar_month', '__default', 'my-index', 'content');
upgrade_block_savepoint(true, 2022030200, 'calendar_month', false);
}

View File

@ -25,7 +25,8 @@
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/my/lib.php');
require_once("{$CFG->dirroot}/my/lib.php");
require_once("{$CFG->libdir}/db/upgradelib.php");
/**
* Upgrade code for the MyOverview block.
@ -84,104 +85,31 @@ function xmldb_block_myoverview_upgrade($oldversion) {
// Put any upgrade step following this.
if ($oldversion < 2021052504) {
/**
* Small helper function for this version upgrade to delete instances of this block.
*
* @param stdClass $instance DB record of a block that we need to delete within Moodle.
*/
function delete_block_instance(stdClass $instance) {
global $DB;
if ($instance) {
list($sql, $params) = $DB->get_in_or_equal($instance->id, SQL_PARAMS_NAMED);
$params['contextlevel'] = CONTEXT_BLOCK;
$DB->delete_records_select('context', "contextlevel=:contextlevel AND instanceid " . $sql, $params);
$DB->delete_records('block_positions', ['blockinstanceid' => $instance->id]);
$DB->delete_records('block_instances', ['id' => $instance->id]);
$DB->delete_records_list('user_preferences', 'name',
['block' . $instance->id . 'hidden', 'docked_block_instance_' . $instance->id]);
}
}
// Delete the default indexsys version of the block.
$mysubpagepattern = $DB->get_record(
'my_pages',
['userid' => null, 'name' => MY_PAGE_DEFAULT, 'private' => MY_PAGE_PRIVATE],
'id',
IGNORE_MULTIPLE
)->id;
$instanceselect = 'blockname = :blockname and pagetypepattern = :pagetypepattern and subpagepattern = :subpagepattern';
$instanceparams['blockname'] = 'myoverview';
$instanceparams['pagetypepattern'] = 'my-index';
$instanceparams['subpagepattern'] = $mysubpagepattern;
$total = $DB->count_records_select('block_instances', $instanceselect, $instanceparams);
// Check if where have blocks to delete.
if ($total > 0) {
$instances = $DB->get_recordset_select('block_instances', $instanceselect, $instanceparams);
// Show a progress bar.
$pbar = new progress_bar('deleteblockinstances', 500, true);
$i = 0;
$pbar->update($i, $total, "Deleting block instance - $i/$total.");
foreach ($instances as $instance) {
delete_block_instance($instance);
// Update progress.
$pbar->update($i, $total, "Deleting block instance - $i/$total.");
$i++;
}
$instances->close();
// Update progress.
$pbar->update($total, $total, "Deleting block instance - $total/$total.");
}
// Begin looking for any and all instances of course overview in customised /my pages.
$pageselect = 'name = :name and private = :private and userid IS NOT NULL';
$pageparams['name'] = MY_PAGE_DEFAULT;
$pageparams['private'] = MY_PAGE_PRIVATE;
$total = $DB->count_records_select('my_pages', $pageselect, $pageparams);
// Check if where have pages to check for blocks.
if ($total > 0) {
$pages = $DB->get_recordset_select('my_pages', $pageselect, $pageparams);
// Show a progress bar.
$pagepbar = new progress_bar('deletepageblockinstances', 500, true);
$i = 0;
$pagepbar->update($i, $total, "Deleting user page block instance - $i/$total.");
foreach ($pages as $page) {
$blocksql = 'blockname = :blockname and pagetypepattern = :pagetypepattern and subpagepattern = :subpagepattern';
$blockparams['blockname'] = 'myoverview';
$blockparams['pagetypepattern'] = 'my-index';
$blockparams['subpagepattern'] = $page->id;
$instances = $DB->get_records_select('block_instances', $blocksql, $blockparams);
foreach ($instances as $instance) {
delete_block_instance($instance);
}
// Update progress.
$pagepbar->update($i, $total, "Deleting user page block instance - $i/$total.");
$i++;
}
$pages->close();
// Update progress.
$pagepbar->update($total, $total, "Deleting user page block instance - $total/$total.");
}
upgrade_block_delete_instances('myoverview', '__default', 'my-index');
// Add new instance to the /my/courses.php page.
$subpagepattern = $DB->get_record(
'my_pages',
['userid' => null, 'name' => MY_PAGE_COURSES, 'private' => MY_PAGE_PUBLIC],
'id',
IGNORE_MULTIPLE
)->id;
$subpagepattern = $DB->get_record('my_pages', [
'userid' => null,
'name' => MY_PAGE_COURSES,
'private' => MY_PAGE_PUBLIC,
], 'id', IGNORE_MULTIPLE)->id;
$blockname = 'myoverview';
$pagetypepattern = 'my-index';
$blockparams = [
'blockname' => $blockname,
'pagetypepattern' => $pagetypepattern,
'subpagepattern' => $subpagepattern,
];
// See if this block already somehow exists, it should not but who knows.
if (!$DB->record_exists('block_instances', ['blockname' => 'myoverview',
'pagetypepattern' => 'my-index', 'subpagepattern' => $subpagepattern])) {
if (!$DB->record_exists('block_instances', $blockparams)) {
$page = new moodle_page();
$systemcontext = context_system::instance();
$page->set_context($systemcontext);
$page->set_context(context_system::instance());
// Add the block to the default /my/courses.
$page->blocks->add_region('content');
$page->blocks->add_block('myoverview', 'content', 0, false, 'my-index', $subpagepattern);
$page->blocks->add_block($blockname, 'content', 0, false, $pagetypepattern, $subpagepattern);
}
upgrade_block_savepoint(true, 2021052504, 'myoverview', false);

View File

@ -38,6 +38,8 @@
defined('MOODLE_INTERNAL') || die();
require_once("{$CFG->libdir}/db/upgradelib.php");
/**
* Upgrade the recentlyaccesseditems db table.
*
@ -76,36 +78,8 @@ function xmldb_block_recentlyaccesseditems_upgrade($oldversion, $block) {
// Put any upgrade step following this.
if ($oldversion < 2022030200) {
$context = context_system::instance();
// Begin looking for any and all customised /my pages.
$pageselect = 'name = :name and private = :private';
$pageparams['name'] = '__default';
$pageparams['private'] = 1;
$pages = $DB->get_recordset_select('my_pages', $pageselect, $pageparams);
foreach ($pages as $subpage) {
$blockinstance = $DB->get_record('block_instances', ['blockname' => 'recentlyaccesseditems',
'pagetypepattern' => 'my-index', 'subpagepattern' => $subpage->id]);
if (!$blockinstance) {
// Insert the recentlyaccesseditems into the default index page.
$blockinstance = new stdClass;
$blockinstance->blockname = 'recentlyaccesseditems';
$blockinstance->parentcontextid = $context->id;
$blockinstance->showinsubcontexts = false;
$blockinstance->pagetypepattern = 'my-index';
$blockinstance->subpagepattern = $subpage->id;
$blockinstance->defaultregion = 'side-post';
$blockinstance->defaultweight = -10;
$blockinstance->timecreated = time();
$blockinstance->timemodified = time();
$DB->insert_record('block_instances', $blockinstance);
} else if ($blockinstance->defaultregion !== 'side-post') {
$blockinstance->defaultregion = 'side-post';
$DB->update_record('block_instances', $blockinstance);
}
}
$pages->close();
// Update all recentlyaccesseditems blocks in the my-index to be in the main side-post region.
upgrade_block_set_defaultregion('recentlyaccesseditems', '__default', 'my-index', 'side-post');
upgrade_block_savepoint(true, 2022030200, 'recentlyaccesseditems', false);
}

View File

@ -36,6 +36,10 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("{$CFG->libdir}/db/upgradelib.php");
/**
* Upgrade the timeline block
* @param int $oldversion
@ -57,36 +61,8 @@ function xmldb_block_timeline_upgrade($oldversion, $block) {
// Put any upgrade step following this.
if ($oldversion < 2022030200) {
$context = context_system::instance();
// Begin looking for any and all customised /my pages.
$pageselect = 'name = :name and private = :private';
$pageparams['name'] = '__default';
$pageparams['private'] = 1;
$pages = $DB->get_recordset_select('my_pages', $pageselect, $pageparams);
foreach ($pages as $subpage) {
$blockinstance = $DB->get_record('block_instances', ['blockname' => 'timeline',
'pagetypepattern' => 'my-index', 'subpagepattern' => $subpage->id]);
if (!$blockinstance) {
// Insert the timeline into the default index page.
$blockinstance = new stdClass;
$blockinstance->blockname = 'timeline';
$blockinstance->parentcontextid = $context->id;
$blockinstance->showinsubcontexts = false;
$blockinstance->pagetypepattern = 'my-index';
$blockinstance->subpagepattern = $subpage->id;
$blockinstance->defaultregion = 'content';
$blockinstance->defaultweight = -10;
$blockinstance->timecreated = time();
$blockinstance->timemodified = time();
$DB->insert_record('block_instances', $blockinstance);
} else if ($blockinstance->defaultregion !== 'content') {
$blockinstance->defaultregion = 'content';
$DB->update_record('block_instances', $blockinstance);
}
}
$pages->close();
// Update all timeline blocks in the my-index to be in the main content region.
upgrade_block_set_defaultregion('timeline', '__default', 'my-index', 'content');
upgrade_block_savepoint(true, 2022030200, 'timeline', false);
}

View File

@ -7603,16 +7603,23 @@ class context_block extends context {
protected static function create_level_instances() {
global $DB;
$sql = "SELECT ".CONTEXT_BLOCK.", bi.id
FROM {block_instances} bi
WHERE NOT EXISTS (SELECT 'x'
FROM {context} cx
WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
$contextdata = $DB->get_recordset_sql($sql);
foreach ($contextdata as $context) {
context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
}
$contextdata->close();
$sql = <<<EOF
INSERT INTO {context} (
contextlevel,
instanceid
) SELECT
:contextlevel,
bi.id as instanceid
FROM {block_instances} bi
WHERE NOT EXISTS (
SELECT 'x' FROM {context} cx WHERE bi.id = cx.instanceid AND cx.contextlevel = :existingcontextlevel
)
EOF;
$DB->execute($sql, [
'contextlevel' => CONTEXT_BLOCK,
'existingcontextlevel' => CONTEXT_BLOCK,
]);
}
/**

View File

@ -1294,3 +1294,220 @@ function upgrade_add_item_to_usermenu(string $menuitem): void {
set_config('customusermenuitems', implode("\n", $lines));
}
}
/**
* Update all instances of a block shown on a pagetype to a new default region, adding missing block instances where
* none is found.
*
* Note: This is intended as a helper to add blocks to all instances of the standard my-page. It will only work where
* the subpagepattern is a string representation of an integer. If there are any string values this will not work.
*
* @param string $blockname The block name, without the block_ frankenstyle component
* @param string $pagename The type of my-page to match
* @param string $pagetypepattern The page type pattern to match for the block
* @param string $newdefaultregion The new region to set
*/
function upgrade_block_set_defaultregion(
string $blockname,
string $pagename,
string $pagetypepattern,
string $newdefaultregion
): void {
global $DB;
// The subpagepattern is a string.
// In all core blocks it contains a string represnetation of an integer, but it is theoretically possible for a
// community block to do something different.
// This function is not suited to those cases.
$subpagepattern = $DB->sql_cast_char2int('bi.subpagepattern');
$subpageempty = $DB->sql_isnotempty('block_instances', 'bi.subpagepattern', true, false);
// If a subquery returns any NULL then the NOT IN returns no results at all.
// By adding a join in the inner select on my_pages we remove any possible nulls and prevent any need for
// additional casting to filter out the nulls.
$sql = <<<EOF
INSERT INTO {block_instances} (
blockname,
parentcontextid,
showinsubcontexts,
pagetypepattern,
subpagepattern,
defaultregion,
defaultweight,
timecreated,
timemodified
) SELECT
:selectblockname AS blockname,
:selectparentcontext AS parentcontextid,
0 AS showinsubcontexts,
:selectpagetypepattern AS pagetypepattern,
mp.id AS subpagepattern,
:selectdefaultregion AS defaultregion,
0 AS defaultweight,
:selecttimecreated AS timecreated,
:selecttimemodified AS timemodified
FROM {my_pages} mp
WHERE mp.id NOT IN (
SELECT mpi.id FROM {my_pages} mpi
JOIN {block_instances} bi
ON bi.blockname = :blockname
AND bi.subpagepattern IS NOT NULL AND {$subpageempty}
AND bi.pagetypepattern = :pagetypepattern
AND {$subpagepattern} = mpi.id
)
AND mp.private = 1
AND mp.name = :pagename
EOF;
$context = context_system::instance();
$result = $DB->execute($sql, [
'selectblockname' => $blockname,
'selectparentcontext' => $context->id,
'selectpagetypepattern' => $pagetypepattern,
'selectdefaultregion' => $newdefaultregion,
'selecttimecreated' => time(),
'selecttimemodified' => time(),
'pagetypepattern' => $pagetypepattern,
'blockname' => $blockname,
'pagename' => $pagename,
]);
// Update the existing instances.
$sql = <<<EOF
UPDATE {block_instances}
SET defaultregion = :newdefaultregion
WHERE id IN (
SELECT * FROM (
SELECT bi.id
FROM {my_pages} mp
JOIN {block_instances} bi
ON bi.blockname = :blockname
AND bi.subpagepattern IS NOT NULL AND {$subpageempty}
AND bi.pagetypepattern = :pagetypepattern
AND {$subpagepattern} = mp.id
WHERE mp.private = 1
AND mp.name = :pagename
AND bi.defaultregion <> :existingnewdefaultregion
) bid
)
EOF;
$DB->execute($sql, [
'newdefaultregion' => $newdefaultregion,
'pagetypepattern' => $pagetypepattern,
'blockname' => $blockname,
'existingnewdefaultregion' => $newdefaultregion,
'pagename' => $pagename,
]);
// Note: This can be time consuming!
\context_helper::create_instances(CONTEXT_BLOCK);
}
/**
* Remove all instances of a block on pages of the specified pagetypepattern.
*
* Note: This is intended as a helper to add blocks to all instances of the standard my-page. It will only work where
* the subpagepattern is a string representation of an integer. If there are any string values this will not work.
*
* @param string $blockname The block name, without the block_ frankenstyle component
* @param string $pagename The type of my-page to match
* @param string $pagetypepattern This is typically used on the 'my-index'
*/
function upgrade_block_delete_instances(
string $blockname,
string $pagename,
string $pagetypepattern
): void {
global $DB;
$deleteblockinstances = function (string $instanceselect, array $instanceparams) use ($DB) {
$deletesql = <<<EOF
SELECT c.id AS cid
FROM {context} c
JOIN {block_instances} bi ON bi.id = c.instanceid AND c.contextlevel = :contextlevel
WHERE {$instanceselect}
EOF;
$DB->delete_records_subquery('context', 'id', 'cid', $deletesql, array_merge($instanceparams, [
'contextlevel' => CONTEXT_BLOCK,
]));
$deletesql = <<<EOF
SELECT bp.id AS bpid
FROM {block_positions} bp
JOIN {block_instances} bi ON bi.id = bp.blockinstanceid
WHERE {$instanceselect}
EOF;
$DB->delete_records_subquery('block_positions', 'id', 'bpid', $deletesql, $instanceparams);
$blockhidden = $DB->sql_concat("'block'", 'bi.id', "'hidden'");
$blockdocked = $DB->sql_concat("'docked_block_instance_'", 'bi.id');
$deletesql = <<<EOF
SELECT p.id AS pid
FROM {user_preferences} p
JOIN {block_instances} bi ON p.name IN ({$blockhidden}, {$blockdocked})
WHERE {$instanceselect}
EOF;
$DB->delete_records_subquery('user_preferences', 'id', 'pid', $deletesql, $instanceparams);
$deletesql = <<<EOF
SELECT bi.id AS bid
FROM {block_instances} bi
WHERE {$instanceselect}
EOF;
$DB->delete_records_subquery('block_instances', 'id', 'bid', $deletesql, $instanceparams);
};
// Delete the default indexsys version of the block.
$subpagepattern = $DB->get_record('my_pages', [
'userid' => null,
'name' => $pagename,
'private' => MY_PAGE_PRIVATE,
], 'id', IGNORE_MULTIPLE)->id;
$instanceselect = <<<EOF
blockname = :blockname
AND pagetypepattern = :pagetypepattern
AND subpagepattern = :subpagepattern
EOF;
$params = [
'blockname' => $blockname,
'pagetypepattern' => $pagetypepattern,
'subpagepattern' => $subpagepattern,
];
$deleteblockinstances($instanceselect, $params);
// The subpagepattern is a string.
// In all core blocks it contains a string represnetation of an integer, but it is theoretically possible for a
// community block to do something different.
// This function is not suited to those cases.
$subpagepattern = $DB->sql_cast_char2int('bi.subpagepattern');
// Look for any and all instances of the block in customised /my pages.
$subpageempty = $DB->sql_isnotempty('block_instances', 'bi.subpagepattern', true, false);
$instanceselect = <<<EOF
bi.id IN (
SELECT * FROM (
SELECT bi.id
FROM {my_pages} mp
JOIN {block_instances} bi
ON bi.blockname = :blockname
AND bi.subpagepattern IS NOT NULL AND {$subpageempty}
AND bi.pagetypepattern = :pagetypepattern
AND {$subpagepattern} = mp.id
WHERE mp.private = :private
AND mp.name = :pagename
) bid
)
EOF;
$params = [
'blockname' => $blockname,
'pagetypepattern' => $pagetypepattern,
'pagename' => $pagename,
'private' => MY_PAGE_PRIVATE,
];
$deleteblockinstances($instanceselect, $params);
}

View File

@ -0,0 +1,108 @@
<?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/>.
// Note: Technically this namespace is incorrect, but we should be moving to namespace things and core anyway.
namespace core;
/**
* Unit tests specifically for context_block.
*
* @package core
* @category phpunit
* @copyright 2022 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \context_block
*/
class context_block_test extends \advanced_testcase {
/**
* Test setup.
*/
public function setUp(): void {
global $CFG;
require_once("{$CFG->libdir}/accesslib.php");
}
/**
* Ensure that block contexts are correctly created for blocks where they are missing.
*
* @covers ::create_level_instances
*/
public function test_context_creation(): void {
global $DB;
$this->resetAfterTest();
// Create some parent contexts.
$generator = $this->getDataGenerator();
$user = $generator->create_user();
$coursecat = $generator->create_category();
$course = $generator->create_course(['category' => $coursecat->id]);
$activity = $generator->create_module('forum', ['course' => $course->id]);
$contextlist = [
\context_system::instance(),
\context_user::instance($user->id),
\context_coursecat::instance($coursecat->id),
\context_course::instance($course->id),
\context_module::instance($activity->cmid),
];
// Create a number of blocks of different types in the DB only.
// This is typically seen when creating large numbers in an upgrade script.
$blocks = [];
for ($i = 0; $i < 10; $i++) {
foreach ($contextlist as $context) {
$blocks[] = $DB->insert_record('block_instances', [
'blockname' => 'calendar_month',
'parentcontextid' => $context->id,
'showinsubcontexts' => 1,
'requiredbytheme' => 0,
'pagetypepattern' => 'my-index',
'subpagepattern' => 1,
'defaultregion' => 'content',
'defaultweight' => 1,
'timecreated' => time(),
'timemodified' => time(),
]);
}
}
// Test data created. Call \context_helper::create_instances() which will create the records, and fix the paths.
\context_helper::create_instances(CONTEXT_BLOCK);
foreach ($blocks as $blockid) {
$block = $DB->get_record('block_instances', ['id' => $blockid]);
$context = \context_block::instance($block->id);
$this->assertInstanceOf(\context_block::class, $context);
// Note. There is no point checking the instanceid because the context was fetched using this.
// Ensure that the contextlevel is correct.
$this->assertEquals(CONTEXT_BLOCK, $context->contextlevel);
// Fetch the parent context.
$parentcontext = $context->get_parent_context();
// This hsould match the parent context specified in the block instance configuration.
$this->assertEquals($block->parentcontextid, $parentcontext->id);
// Ensure that the path and depth are correctly specified.
$this->assertEquals($parentcontext->path . "/{$context->id}", $context->path);
$this->assertEquals($parentcontext->depth + 1, $context->depth);
}
}
}

View File

@ -0,0 +1,442 @@
<?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/>.
// Note: This namespace is not technically correct, but we have to make it different to the tests for lib/upgradelib.php
// and this is more correct than alternatives.
namespace core\db;
/**
* Unit tests for the lib/db/upgradelib.php library.
*
* @package core
* @category phpunit
* @copyright 2022 Andrew Lyons <andrew@thelyons.family>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class upgradelib_test extends \advanced_testcase {
/**
* Shared setup for the testcase.
*/
public function setUp(): void {
global $CFG;
require_once("{$CFG->libdir}/db/upgradelib.php");
require_once("{$CFG->dirroot}/my/lib.php");
}
/**
* Ensure that the upgrade_block_set_defaultregion function performs as expected.
*
* Only targetted blocks and pages should be affected.
*
* @covers ::upgrade_block_set_defaultregion
*/
public function test_upgrade_block_set_defaultregion(): void {
global $DB;
$this->resetAfterTest();
// Ensure that only the targetted blocks are affected.
// Create a my-index entry for the Dashboard.
$dashboardid = $DB->insert_record('my_pages', (object) [
'name' => '__default',
'private' => MY_PAGE_PRIVATE,
]);
// Create a page for the my-courses page.
$mycoursesid = $DB->insert_record('my_pages', (object) [
'name' => '__courses',
'private' => MY_PAGE_PRIVATE,
]);
$unchanged = [];
$changed = [];
// Create several blocks of different types.
// These are not linked to the my-index page above, so should not be modified.
$unchanged[] = $this->getDataGenerator()->create_block('online_users', [
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('myoverview', [
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'defaultregion' => 'left-side',
]);
// These are on the my-index above, but are not the block being updated.
$unchanged[] = $this->getDataGenerator()->create_block('online_users', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('myoverview', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// This is on a my-index page, and is the affected block, but is on the mycourses page, not the dashboard.
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $mycoursesid,
'defaultregion' => 'left-side',
]);
// This is on the default dashboard, and is the affected block, but not a my-index page.
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'not-my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// This is the match which should be changed.
$changed[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// Perform the operation.
// Target all calendar_month blocks matching 'my-index' and update them to the 'content' region where they
// belong to the user dashboard ('pagename' == '__default').
upgrade_block_set_defaultregion('calendar_month', '__default', 'my-index', 'content');
// Ensure that the relevant blocks remain unchanged.
foreach ($unchanged as $original) {
$block = $DB->get_record('block_instances', ['id' => $original->id]);
$this->assertEquals($original, $block);
}
// Ensure that only the expected blocks were changed.
foreach ($changed as $original) {
$block = $DB->get_record('block_instances', ['id' => $original->id]);
$this->assertNotEquals($original, $block);
// Only the defaultregion should be updated to content. No other changes are expected.
$expected = (object) $original;
$expected->defaultregion = 'content';
$this->assertEquals($expected, $block);
}
}
/**
* Ensure that the upgrade_block_set_defaultregion function performs as expected.
*
* Missing block entries will be created.
*
* @covers ::upgrade_block_set_defaultregion
*/
public function test_upgrade_block_set_defaultregion_create_missing(): void {
global $DB;
$this->resetAfterTest();
// Ensure that only the targetted blocks are affected.
$dashboards = [];
$mycourses = [];
// Create dashboard pages for a number of users.
while (count($dashboards) < 10) {
$user = $this->getDataGenerator()->create_user();
$dashboards[] = $DB->insert_record('my_pages', (object) [
'userid' => $user->id,
'name' => '__default',
'private' => MY_PAGE_PRIVATE,
]);
$mycourses[] = $DB->insert_record('my_pages', (object) [
'userid' => $user->id,
'name' => '__courses',
'private' => MY_PAGE_PRIVATE,
]);
}
// Enusre that there are no blocks initially.
foreach ($dashboards as $dashboardid) {
$this->assertEquals(0, $DB->count_records('block_instances', [
'subpagepattern' => $dashboardid,
]));
}
// Perform the operation.
// Target all calendar_month blocks matching 'my-index' and update them to the 'content' region where they
// belong to the user dashboard ('pagename' == '__default').
// Any dashboards which are missing the block will have it created by the operation.
upgrade_block_set_defaultregion('calendar_month', '__default', 'my-index', 'content');
// Each of the dashboards should not have a block instance of the calendar_month block in the 'content' region
// on 'my-index' only.
foreach ($dashboards as $dashboardid) {
// Only one block should have been created.
$blocks = $DB->get_records('block_instances', [
'subpagepattern' => $dashboardid,
]);
$this->assertCount(1, $blocks);
$theblock = reset($blocks);
$this->assertEquals('calendar_month', $theblock->blockname);
$this->assertEquals('content', $theblock->defaultregion);
$this->assertEquals('my-index', $theblock->pagetypepattern);
}
// Enusre that there are no blocks on the mycourses page.
foreach ($mycourses as $pageid) {
$this->assertEquals(0, $DB->count_records('block_instances', [
'subpagepattern' => $pageid,
]));
}
}
/**
* Ensure that the upgrade_block_delete_instances function performs as expected.
*
* Missing block entries will be created.
*
* @covers ::upgrade_block_delete_instances
*/
public function test_upgrade_block_delete_instances(): void {
global $DB;
$this->resetAfterTest();
$DB->delete_records('block_instances');
// Ensure that only the targetted blocks are affected.
// Get the my-index entry for the Dashboard.
$dashboardid = $DB->get_record('my_pages', [
'userid' => null,
'name' => '__default',
'private' => MY_PAGE_PRIVATE,
], 'id')->id;
// Get the page for the my-courses page.
$mycoursesid = $DB->get_record('my_pages', [
'name' => MY_PAGE_COURSES,
], 'id')->id;
$dashboards = [];
$mycourses = [];
$unchanged = [];
$unchangedcontexts = [];
$unchangedpreferences = [];
$deleted = [];
$deletedcontexts = [];
$deletedpreferences = [];
// Create several blocks of different types.
// These are not linked to the my page above, so should not be modified.
$unchanged[] = $this->getDataGenerator()->create_block('online_users', [
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('myoverview', [
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'defaultregion' => 'left-side',
]);
// These are on the my-index above, but are not the block being updated.
$unchanged[] = $this->getDataGenerator()->create_block('online_users', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
$unchanged[] = $this->getDataGenerator()->create_block('myoverview', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// This is on a my-index page, and is the affected block, but is on the mycourses page, not the dashboard.
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $mycoursesid,
'defaultregion' => 'left-side',
]);
// This is on the default dashboard, and is the affected block, but not a my-index page.
$unchanged[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'not-my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// This is the match which should be changed.
$deleted[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $dashboardid,
'defaultregion' => 'left-side',
]);
// Create blocks for users with preferences now.
while (count($dashboards) < 10) {
$userunchangedblocks = [];
$userdeletedblocks = [];
$user = $this->getDataGenerator()->create_user();
$userdashboardid = $DB->insert_record('my_pages', (object) [
'userid' => $user->id,
'name' => '__default',
'private' => MY_PAGE_PRIVATE,
]);
$dashboards[] = $userdashboardid;
$usermycoursesid = $DB->insert_record('my_pages', (object) [
'userid' => $user->id,
'name' => '__courses',
'private' => MY_PAGE_PRIVATE,
]);
$mycourses[] = $usermycoursesid;
// These are on the my-index above, but are not the block being updated.
$userunchangedblocks[] = $this->getDataGenerator()->create_block('online_users', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $userdashboardid,
'defaultregion' => 'left-side',
]);
$userunchangedblocks[] = $this->getDataGenerator()->create_block('myoverview', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $userdashboardid,
'defaultregion' => 'left-side',
]);
// This is on a my-index page, and is the affected block, but is on the mycourses page, not the dashboard.
$userunchangedblocks[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $usermycoursesid,
'defaultregion' => 'left-side',
]);
// This is on the default dashboard, and is the affected block, but not a my-index page.
$userunchangedblocks[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'not-my-index',
'subpagepattern' => $userdashboardid,
'defaultregion' => 'left-side',
]);
// This is the match which should be changed.
$userdeletedblocks[] = $this->getDataGenerator()->create_block('calendar_month', [
'pagetypepattern' => 'my-index',
'subpagepattern' => $userdashboardid,
'defaultregion' => 'left-side',
]);
$unchanged += $userunchangedblocks;
$deleted += $userdeletedblocks;
foreach ($userunchangedblocks as $block) {
// Create user preferences for these blocks.
set_user_preference("block{$block->id}hidden", 1, $user);
set_user_preference("docked_block_instance_{$block->id}", 1, $user);
$unchangedpreferences[] = $block->id;
}
foreach ($userdeletedblocks as $block) {
// Create user preferences for these blocks.
set_user_preference("block{$block->id}hidden", 1, $user);
set_user_preference("docked_block_instance_{$block->id}", 1, $user);
$deletedpreferences[] = $block->id;
}
}
// Create missing contexts.
\context_helper::create_instances(CONTEXT_BLOCK);
// Ensure that other related test data is present.
$systemcontext = \context_system::instance();
foreach ($unchanged as $block) {
// Get contexts.
$unchangedcontexts[] = \context_block::instance($block->id);
// Create a block position.
$DB->insert_record('block_positions', [
'blockinstanceid' => $block->id,
'contextid' => $systemcontext->id,
'pagetype' => 'course-view-topics',
'region' => 'site-post',
'weight' => 1,
'visible' => 1,
]);
}
foreach ($deleted as $block) {
// Get contexts.
$deletedcontexts[] = \context_block::instance($block->id);
// Create a block position.
$DB->insert_record('block_positions', [
'blockinstanceid' => $block->id,
'contextid' => $systemcontext->id,
'pagetype' => 'course-view-topics',
'region' => 'site-post',
'weight' => 1,
'visible' => 1,
]);
}
// Perform the operation.
// Target all calendar_month blocks matching 'my-index' and update them to the 'content' region where they
// belong to the user dashboard ('pagename' == '__default').
upgrade_block_delete_instances('calendar_month', '__default', 'my-index');
// Ensure that the relevant blocks remain unchanged.
foreach ($unchanged as $original) {
$block = $DB->get_record('block_instances', ['id' => $original->id]);
$this->assertEquals($original, $block);
// Ensure that the block positions remain.
$this->assertEquals(1, $DB->count_records('block_positions', ['blockinstanceid' => $original->id]));
}
foreach ($unchangedcontexts as $context) {
// Ensure that the context still exists.
$this->assertEquals(1, $DB->count_records('context', ['id' => $context->id]));
}
foreach ($unchangedpreferences as $blockid) {
// Ensure that the context still exists.
$this->assertEquals(1, $DB->count_records('user_preferences', ['name' => "block{$blockid}hidden"]));
$this->assertEquals(1, $DB->count_records('user_preferences', [
'name' => "docked_block_instance_{$blockid}",
]));
}
// Ensure that only the expected blocks were changed.
foreach ($deleted as $original) {
$this->assertCount(0, $DB->get_records('block_instances', ['id' => $original->id]));
// Ensure that the block positions was removed.
$this->assertEquals(0, $DB->count_records('block_positions', ['blockinstanceid' => $original->id]));
}
foreach ($deletedcontexts as $context) {
// Ensure that the context still exists.
$this->assertEquals(0, $DB->count_records('context', ['id' => $context->id]));
}
foreach ($deletedpreferences as $blockid) {
// Ensure that the context still exists.
$this->assertEquals(0, $DB->count_records('user_preferences', ['name' => "block{$blockid}hidden"]));
$this->assertEquals(0, $DB->count_records('user_preferences', [
'name' => "docked_block_instance_{$blockid}",
]));
}
}
}