Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Tests for the block_manager class in ../blocklib.php.
  19   *
  20   * @package   core
  21   * @category  phpunit
  22   * @copyright 2009 Tim Hunt
  23   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  global $CFG;
  29  require_once($CFG->libdir . '/pagelib.php');
  30  require_once($CFG->libdir . '/blocklib.php');
  31  require_once($CFG->dirroot . '/blocks/moodleblock.class.php');
  32  
  33  
  34  /**
  35   * Test various block related classes.
  36   */
  37  class core_blocklib_testcase extends advanced_testcase {
  38      protected $testpage;
  39      protected $blockmanager;
  40      protected $isediting = null;
  41  
  42      protected function setUp(): void {
  43          parent::setUp();
  44          $this->testpage = new moodle_page();
  45          $this->testpage->set_context(context_system::instance());
  46          $this->testpage->set_pagetype('phpunit-block-test');
  47          $this->blockmanager = new testable_block_manager($this->testpage);
  48      }
  49  
  50      protected function tearDown(): void {
  51          $this->testpage = null;
  52          $this->blockmanager = null;
  53          parent::tearDown();
  54      }
  55  
  56      protected function purge_blocks() {
  57          global $DB;
  58          $this->resetAfterTest();
  59  
  60          $bis = $DB->get_records('block_instances');
  61          foreach ($bis as $instance) {
  62              blocks_delete_instance($instance);
  63          }
  64      }
  65  
  66      /**
  67       * Gets the last block created.
  68       *
  69       * @return stdClass a record from block_instances
  70       */
  71      protected function get_last_created_block() {
  72          global $DB;
  73          // The newest block should be the record with the highest id.
  74          $records = $DB->get_records('block_instances', [], 'id DESC', '*', 0, 1);
  75          $return = null;
  76          foreach ($records as $record) {
  77              // There should only be one.
  78              $return = $record;
  79          }
  80          return $return;
  81      }
  82  
  83      public function test_no_regions_initially() {
  84          // Exercise SUT & Validate.
  85          $this->assertEquals(array(), $this->blockmanager->get_regions());
  86      }
  87  
  88      public function test_add_region() {
  89          // Exercise SUT.
  90          $this->blockmanager->add_region('a-region-name', false);
  91          // Validate.
  92          $this->assertEquals(array('a-region-name'), $this->blockmanager->get_regions());
  93      }
  94  
  95      public function test_add_regions() {
  96          // Set up fixture.
  97          $regions = array('a-region', 'another-region');
  98          // Exercise SUT.
  99          $this->blockmanager->add_regions($regions, false);
 100          // Validate.
 101          $this->assertEqualsCanonicalizing($regions, $this->blockmanager->get_regions());
 102      }
 103  
 104      public function test_add_region_twice() {
 105          // Exercise SUT.
 106          $this->blockmanager->add_region('a-region-name', false);
 107          $this->blockmanager->add_region('another-region', false);
 108          // Validate.
 109          $this->assertEqualsCanonicalizing(array('a-region-name', 'another-region'), $this->blockmanager->get_regions());
 110      }
 111  
 112      public function test_cannot_add_region_after_loaded() {
 113          // Set up fixture.
 114          $this->blockmanager->mark_loaded();
 115          // Exercise SUT.
 116          $this->expectException(coding_exception::class);
 117          $this->blockmanager->add_region('too-late', false);
 118      }
 119  
 120      /**
 121       * Testing adding a custom region.
 122       */
 123      public function test_add_custom_region() {
 124          global $SESSION;
 125          // Exercise SUT.
 126          $this->blockmanager->add_region('a-custom-region-name');
 127          // Validate.
 128          $this->assertEquals(array('a-custom-region-name'), $this->blockmanager->get_regions());
 129          $this->assertTrue(isset($SESSION->custom_block_regions));
 130          $this->assertArrayHasKey('phpunit-block-test', $SESSION->custom_block_regions);
 131          $this->assertTrue(in_array('a-custom-region-name', $SESSION->custom_block_regions['phpunit-block-test']));
 132  
 133      }
 134  
 135      /**
 136       * Test adding two custom regions using add_regions method.
 137       */
 138      public function test_add_custom_regions() {
 139          global $SESSION;
 140          // Set up fixture.
 141          $regions = array('a-region', 'another-custom-region');
 142          // Exercise SUT.
 143          $this->blockmanager->add_regions($regions);
 144          // Validate.
 145          $this->assertEqualsCanonicalizing($regions, $this->blockmanager->get_regions());
 146          $this->assertTrue(isset($SESSION->custom_block_regions));
 147          $this->assertArrayHasKey('phpunit-block-test', $SESSION->custom_block_regions);
 148          $this->assertTrue(in_array('another-custom-region', $SESSION->custom_block_regions['phpunit-block-test']));
 149      }
 150  
 151      /**
 152       * Test adding two custom block regions.
 153       */
 154      public function test_add_custom_region_twice() {
 155          // Exercise SUT.
 156          $this->blockmanager->add_region('a-custom-region-name');
 157          $this->blockmanager->add_region('another-custom-region');
 158          // Validate.
 159          $this->assertEqualsCanonicalizing(
 160              array('a-custom-region-name', 'another-custom-region'),
 161              $this->blockmanager->get_regions());
 162      }
 163  
 164      /**
 165       * Test to ensure that we cannot add a region after the blocks have been loaded.
 166       */
 167      public function test_cannot_add_custom_region_after_loaded() {
 168          // Set up fixture.
 169          $this->blockmanager->mark_loaded();
 170          // Exercise SUT.
 171          $this->expectException(coding_exception::class);
 172          $this->blockmanager->add_region('too-late');
 173      }
 174  
 175      public function test_set_default_region() {
 176          // Set up fixture.
 177          $this->blockmanager->add_region('a-region-name', false);
 178          // Exercise SUT.
 179          $this->blockmanager->set_default_region('a-region-name');
 180          // Validate.
 181          $this->assertEquals('a-region-name', $this->blockmanager->get_default_region());
 182      }
 183  
 184      public function test_cannot_set_unknown_region_as_default() {
 185          // Exercise SUT.
 186          $this->expectException(coding_exception::class);
 187          $this->blockmanager->set_default_region('a-region-name');
 188      }
 189  
 190      public function test_cannot_change_default_region_after_loaded() {
 191          // Set up fixture.
 192          $this->blockmanager->mark_loaded();
 193          // Exercise SUT.
 194          $this->expectException(coding_exception::class);
 195          $this->blockmanager->set_default_region('too-late');
 196      }
 197  
 198      public function test_matching_page_type_patterns() {
 199          $this->assertEqualsCanonicalizing(array('site-index', 'site-index-*', 'site-*', '*'),
 200              matching_page_type_patterns('site-index'));
 201  
 202          $this->assertEqualsCanonicalizing(array('mod-quiz-report-overview', 'mod-quiz-report-overview-*', 'mod-quiz-report-*', 'mod-quiz-*', 'mod-*', '*'),
 203              matching_page_type_patterns('mod-quiz-report-overview'));
 204  
 205          $this->assertEqualsCanonicalizing(array('mod-forum-view', 'mod-*-view', 'mod-forum-view-*', 'mod-forum-*', 'mod-*', '*'),
 206              matching_page_type_patterns('mod-forum-view'));
 207  
 208          $this->assertEqualsCanonicalizing(array('mod-forum-index', 'mod-*-index', 'mod-forum-index-*', 'mod-forum-*', 'mod-*', '*'),
 209              matching_page_type_patterns('mod-forum-index'));
 210      }
 211  
 212      protected function get_a_page_and_block_manager($regions, $context, $pagetype, $subpage = '') {
 213          $page = new moodle_page;
 214          $page->set_context($context);
 215          $page->set_pagetype($pagetype);
 216          $page->set_subpage($subpage);
 217          $page->set_url(new moodle_url('/'));
 218  
 219          $blockmanager = new testable_block_manager($page);
 220          $blockmanager->add_regions($regions, false);
 221          $blockmanager->set_default_region($regions[0]);
 222  
 223          return array($page, $blockmanager);
 224      }
 225  
 226      protected function get_a_known_block_type() {
 227          global $DB;
 228          $block = new stdClass;
 229          $block->name = 'ablocktype';
 230          $DB->insert_record('block', $block);
 231          return $block->name;
 232      }
 233  
 234      protected function assertContainsBlocksOfType($typearray, $blockarray) {
 235          if (!$this->assertEquals(count($typearray), count($blockarray), "Blocks array contains the wrong number of elements %s.")) {
 236              return;
 237          }
 238          $types = array_values($typearray);
 239          $i = 0;
 240          foreach ($blockarray as $block) {
 241              $blocktype = $types[$i];
 242              $this->assertEquals($blocktype, $block->name(), "Block types do not match at postition $i %s.");
 243              $i++;
 244          }
 245      }
 246  
 247      public function test_empty_initially() {
 248          $this->purge_blocks();
 249  
 250          // Set up fixture.
 251          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array('a-region'),
 252              context_system::instance(), 'page-type');
 253          // Exercise SUT.
 254          $blockmanager->load_blocks();
 255          // Validate.
 256          $blocks = $blockmanager->get_loaded_blocks();
 257          $this->assertEquals(array('a-region' => array()), $blocks);
 258      }
 259  
 260      public function test_adding_and_retrieving_one_block() {
 261          $this->purge_blocks();
 262  
 263          // Set up fixture.
 264          $regionname = 'a-region';
 265          $blockname = $this->get_a_known_block_type();
 266          $context = context_system::instance();
 267  
 268          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 269              $context, 'page-type');
 270  
 271          // Exercise SUT.
 272          $blockmanager->add_block($blockname, $regionname, 0, false);
 273          $blockmanager->load_blocks();
 274          // Validate.
 275          $blocks = $blockmanager->get_blocks_for_region($regionname);
 276          $this->assertContainsBlocksOfType(array($blockname), $blocks);
 277      }
 278  
 279      public function test_adding_and_retrieving_two_blocks() {
 280          $this->purge_blocks();
 281  
 282          // Set up fixture.
 283          $regionname = 'a-region';
 284          $blockname = $this->get_a_known_block_type();
 285          $context = context_system::instance();
 286  
 287          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 288              $context, 'page-type');
 289  
 290          // Exercise SUT.
 291          $blockmanager->add_block($blockname, $regionname, 0, false);
 292          $blockmanager->add_block($blockname, $regionname, 1, false);
 293          $blockmanager->load_blocks();
 294          // Validate.
 295          $blocks = $blockmanager->get_blocks_for_region($regionname);
 296          $this->assertContainsBlocksOfType(array($blockname, $blockname), $blocks);
 297      }
 298  
 299      public function test_adding_blocks() {
 300          $this->purge_blocks();
 301  
 302          // Set up fixture.
 303          $regionname = 'a-region';
 304          $blockname = $this->get_a_known_block_type();
 305          $context = context_system::instance();
 306  
 307          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 308              $context, 'page-type');
 309  
 310          $blockmanager->add_blocks(array($regionname => array($blockname, $blockname)), null, null, false, 3);
 311          $blockmanager->load_blocks();
 312  
 313          $blocks = $blockmanager->get_blocks_for_region($regionname);
 314  
 315          $this->assertEquals('3', $blocks[0]->instance->weight);
 316          $this->assertEquals('4', $blocks[1]->instance->weight);
 317      }
 318  
 319      /**
 320       * Test block instances.
 321       *
 322       * @return null
 323       */
 324      public function test_block_instances() {
 325          $this->purge_blocks();
 326  
 327          // Set up fixture.
 328          $regionname = 'a-region';
 329          $blockname = $this->get_a_known_block_type();
 330          $context = context_system::instance();
 331  
 332          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 333              $context, 'page-type');
 334  
 335          $blockmanager->add_blocks(array($regionname => array($blockname, $blockname)), null, null, false, 3);
 336          $blockmanager->load_blocks();
 337  
 338          $blocks = $blockmanager->get_blocks_for_region($regionname);
 339  
 340          $this->assertInstanceOf('\block_base', block_instance($blockname, $blocks[0]->instance));
 341          $this->assertInstanceOf('\block_base', block_instance_by_id($blocks[0]->instance->id));
 342      }
 343  
 344      public function test_block_not_included_in_different_context() {
 345          $this->purge_blocks();
 346  
 347          // Set up fixture.
 348          $syscontext = context_system::instance();
 349          $cat = $this->getDataGenerator()->create_category(array('name' => 'testcategory'));
 350          $fakecontext = context_coursecat::instance($cat->id);
 351          $regionname = 'a-region';
 352          $blockname = $this->get_a_known_block_type();
 353  
 354          list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $fakecontext, 'page-type');
 355          list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type');
 356  
 357          $addbm->add_block($blockname, $regionname, 0, false);
 358  
 359          // Exercise SUT.
 360          $viewbm->load_blocks();
 361          // Validate.
 362          $blocks = $viewbm->get_blocks_for_region($regionname);
 363          $this->assertContainsBlocksOfType(array(), $blocks);
 364      }
 365  
 366      public function test_block_included_in_sub_context() {
 367          $this->purge_blocks();
 368  
 369          // Set up fixture.
 370          $syscontext = context_system::instance();
 371          $childcontext = context_coursecat::instance(1);
 372          $regionname = 'a-region';
 373          $blockname = $this->get_a_known_block_type();
 374  
 375          list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type');
 376          list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $childcontext, 'page-type');
 377  
 378          $addbm->add_block($blockname, $regionname, 0, true);
 379  
 380          // Exercise SUT.
 381          $viewbm->load_blocks();
 382          // Validate.
 383          $blocks = $viewbm->get_blocks_for_region($regionname);
 384          $this->assertContainsBlocksOfType(array($blockname), $blocks);
 385      }
 386  
 387      public function test_block_not_included_on_different_page_type() {
 388          $this->purge_blocks();
 389  
 390          // Set up fixture.
 391          $syscontext = context_system::instance();
 392          $regionname = 'a-region';
 393          $blockname = $this->get_a_known_block_type();
 394  
 395          list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type');
 396          list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'other-page-type');
 397  
 398          $addbm->add_block($blockname, $regionname, 0, true);
 399  
 400          // Exercise SUT.
 401          $viewbm->load_blocks();
 402          // Validate.
 403          $blocks = $viewbm->get_blocks_for_region($regionname);
 404          $this->assertContainsBlocksOfType(array(), $blocks);
 405      }
 406  
 407      public function test_block_not_included_on_different_sub_page() {
 408          $this->purge_blocks();
 409  
 410          // Set up fixture.
 411          $regionname = 'a-region';
 412          $blockname = $this->get_a_known_block_type();
 413          $syscontext = context_system::instance();
 414  
 415          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 416              $syscontext, 'page-type', 'sub-page');
 417  
 418          $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, 'other-sub-page');
 419  
 420          // Exercise SUT.
 421          $blockmanager->load_blocks();
 422          // Validate.
 423          $blocks = $blockmanager->get_blocks_for_region($regionname);
 424          $this->assertContainsBlocksOfType(array(), $blocks);
 425      }
 426  
 427      public function test_block_included_with_explicit_sub_page() {
 428          $this->purge_blocks();
 429  
 430          // Set up fixture.
 431          $regionname = 'a-region';
 432          $blockname = $this->get_a_known_block_type();
 433          $syscontext = context_system::instance();
 434  
 435          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 436              $syscontext, 'page-type', 'sub-page');
 437  
 438          $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, $page->subpage);
 439  
 440          // Exercise SUT.
 441          $blockmanager->load_blocks();
 442          // Validate.
 443          $blocks = $blockmanager->get_blocks_for_region($regionname);
 444          $this->assertContainsBlocksOfType(array($blockname), $blocks);
 445      }
 446  
 447      public function test_block_included_with_page_type_pattern() {
 448          $this->purge_blocks();
 449  
 450          // Set up fixture.
 451          $regionname = 'a-region';
 452          $blockname = $this->get_a_known_block_type();
 453          $syscontext = context_system::instance();
 454  
 455          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 456              $syscontext, 'page-type', 'sub-page');
 457  
 458          $blockmanager->add_block($blockname, $regionname, 0, true, 'page-*', $page->subpage);
 459  
 460          // Exercise SUT.
 461          $blockmanager->load_blocks();
 462          // Validate.
 463          $blocks = $blockmanager->get_blocks_for_region($regionname);
 464          $this->assertContainsBlocksOfType(array($blockname), $blocks);
 465      }
 466  
 467      public function test_matching_page_type_patterns_from_pattern() {
 468          $pattern = '*';
 469          $expected = array('*');
 470          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 471  
 472          $pattern = 'admin-*';
 473          $expected = array('admin-*', 'admin', '*');
 474          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 475  
 476          $pattern = 'blog-index';
 477          $expected = array('blog-index', 'blog-index-*', 'blog-*', '*');
 478          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 479  
 480          $pattern = 'course-index-*';
 481          $expected = array('course-index-*', 'course-index', 'course-*', '*');
 482          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 483  
 484          $pattern = 'course-index-category';
 485          $expected = array('course-index-category', 'course-index-category-*', 'course-index-*', 'course-*', '*');
 486          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 487  
 488          $pattern = 'mod-assign-view';
 489          $expected = array('mod-assign-view', 'mod-*-view', 'mod-assign-view-*', 'mod-assign-*', 'mod-*', '*');
 490          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 491  
 492          $pattern = 'mod-assign-index';
 493          $expected = array('mod-assign-index', 'mod-*-index', 'mod-assign-index-*', 'mod-assign-*', 'mod-*', '*');
 494          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 495  
 496          $pattern = 'mod-forum-*';
 497          $expected = array('mod-forum-*', 'mod-forum', 'mod-*', '*');
 498          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 499  
 500          $pattern = 'mod-*-view';
 501          $expected = array('mod-*-view', 'mod', 'mod-*', '*');
 502          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 503  
 504          $pattern = 'mod-*-index';
 505          $expected = array('mod-*-index', 'mod', 'mod-*', '*');
 506          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 507  
 508          $pattern = 'my-index';
 509          $expected = array('my-index', 'my-index-*', 'my-*', '*');
 510          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 511  
 512          $pattern = 'user-profile';
 513          $expected = array('user-profile', 'user-profile-*', 'user-*', '*');
 514          $this->assertEquals($expected, array_values(matching_page_type_patterns_from_pattern($pattern)));
 515      }
 516  
 517      public function test_delete_instances() {
 518          global $DB;
 519          $this->purge_blocks();
 520          $this->setAdminUser();
 521  
 522          $regionname = 'a-region';
 523          $blockname = $this->get_a_known_block_type();
 524          $context = context_system::instance();
 525  
 526          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 527              $context, 'page-type');
 528  
 529          $blockmanager->add_blocks(array($regionname => array($blockname, $blockname, $blockname)), null, null, false, 3);
 530          $blockmanager->load_blocks();
 531  
 532          $blocks = $blockmanager->get_blocks_for_region($regionname);
 533          $blockids = array();
 534          $preferences = array();
 535  
 536          // Create block related data.
 537          foreach ($blocks as $block) {
 538              $instance = $block->instance;
 539              $pref = 'block' . $instance->id . 'hidden';
 540              set_user_preference($pref, '123', 123);
 541              $preferences[] = $pref;
 542              $pref = 'docked_block_instance_' . $instance->id;
 543              set_user_preference($pref, '123', 123);
 544              $preferences[] = $pref;
 545              blocks_set_visibility($instance, $page, 1);
 546              $blockids[] = $instance->id;
 547          }
 548  
 549          // Confirm what has been set.
 550          $this->assertCount(3, $blockids);
 551          list($insql, $inparams) = $DB->get_in_or_equal($blockids);
 552          $this->assertEquals(3, $DB->count_records_select('block_positions', "blockinstanceid $insql", $inparams));
 553          list($insql, $inparams) = $DB->get_in_or_equal($preferences);
 554          $this->assertEquals(6, $DB->count_records_select('user_preferences', "name $insql", $inparams));
 555  
 556          // Keep a block on the side.
 557          $allblockids = $blockids;
 558          $tokeep = array_pop($blockids);
 559  
 560          // Delete and confirm what should have happened.
 561          blocks_delete_instances($blockids);
 562  
 563          // Reload the manager.
 564          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 565              $context, 'page-type');
 566          $blockmanager->load_blocks();
 567          $blocks = $blockmanager->get_blocks_for_region($regionname);
 568  
 569          $this->assertCount(1, $blocks);
 570          list($insql, $inparams) = $DB->get_in_or_equal($allblockids);
 571          $this->assertEquals(1, $DB->count_records_select('block_positions', "blockinstanceid $insql", $inparams));
 572          list($insql, $inparams) = $DB->get_in_or_equal($preferences);
 573          $this->assertEquals(2, $DB->count_records_select('user_preferences', "name $insql", $inparams));
 574  
 575          $this->assertFalse(context_block::instance($blockids[0], IGNORE_MISSING));
 576          $this->assertFalse(context_block::instance($blockids[1], IGNORE_MISSING));
 577          context_block::instance($tokeep);   // Would throw an exception if it was deleted.
 578      }
 579  
 580      public function test_create_all_block_instances() {
 581          global $CFG, $PAGE, $DB;
 582  
 583          $this->setAdminUser();
 584          $this->resetAfterTest();
 585          $regionname = 'side-pre';
 586          $context = context_system::instance();
 587  
 588          $PAGE->reset_theme_and_output();
 589          $CFG->theme = 'boost';
 590  
 591          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 592              $context, 'page-type');
 593          $blockmanager->load_blocks();
 594          $blockmanager->create_all_block_instances();
 595          $blocks = $blockmanager->get_blocks_for_region($regionname);
 596          // Assert that we no auto created blocks in boost by default.
 597          $this->assertEmpty($blocks);
 598          // There should be no blocks in the DB.
 599  
 600          $PAGE->reset_theme_and_output();
 601          // Change to a theme with undeletable blocks.
 602          $CFG->theme = 'classic';
 603  
 604          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 605              $context, 'page-type');
 606  
 607          $blockmanager->show_only_fake_blocks(true);
 608          $blockmanager->load_blocks();
 609          $blockmanager->create_all_block_instances();
 610          $blocks = $blockmanager->get_blocks_for_region($regionname);
 611          // Assert that we no auto created blocks when viewing a fake blocks only page.
 612          $this->assertEmpty($blocks);
 613  
 614          $PAGE->reset_theme_and_output();
 615          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 616              $context, 'page-type');
 617  
 618          $blockmanager->show_only_fake_blocks(false);
 619          $blockmanager->load_blocks();
 620          $blockmanager->create_all_block_instances();
 621          $blocks = $blockmanager->get_blocks_for_region($regionname);
 622          // Assert that we get the required block for this theme auto-created.
 623          $this->assertCount(2, $blocks);
 624  
 625          $PAGE->reset_theme_and_output();
 626          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 627              $context, 'page-type');
 628  
 629          $blockmanager->protect_block('html');
 630          $blockmanager->load_blocks();
 631          $blockmanager->create_all_block_instances();
 632          $blocks = $blockmanager->get_blocks_for_region($regionname);
 633          // Assert that protecting a block does not make it auto-created.
 634          $this->assertCount(2, $blocks);
 635  
 636          $requiredbytheme = $blockmanager->get_required_by_theme_block_types();
 637          foreach ($requiredbytheme as $blockname) {
 638              $instance = $DB->get_record('block_instances', array('blockname' => $blockname));
 639              $this->assertEquals(1, $instance->requiredbytheme);
 640          }
 641  
 642          // Switch back and those auto blocks should not be returned.
 643          $PAGE->reset_theme_and_output();
 644          $CFG->theme = 'boost';
 645  
 646          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 647              $context, 'page-type');
 648          $blockmanager->load_blocks();
 649          $blockmanager->create_all_block_instances();
 650          $blocks = $blockmanager->get_blocks_for_region($regionname);
 651          // Assert that we do not return requiredbytheme blocks when they are not required.
 652          $this->assertEmpty($blocks);
 653          // But they should exist in the DB.
 654          foreach ($requiredbytheme as $blockname) {
 655              $count = $DB->count_records('block_instances', array('blockname' => $blockname));
 656              $this->assertEquals(1, $count);
 657          }
 658      }
 659  
 660      /**
 661       * Test the block instance time fields (timecreated, timemodified).
 662       */
 663      public function test_block_instance_times() {
 664          global $DB;
 665  
 666          $this->purge_blocks();
 667  
 668          // Set up fixture.
 669          $regionname = 'a-region';
 670          $blockname = 'html';
 671          $context = context_system::instance();
 672  
 673          list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname),
 674                  $context, 'page-type');
 675  
 676          // Add block to page.
 677          $before = time();
 678          $blockmanager->add_block($blockname, $regionname, 0, false);
 679          $after = time();
 680  
 681          // Check database table to ensure it contains created/modified times.
 682          $blockdata = $DB->get_record('block_instances', ['blockname' => 'html']);
 683          $this->assertTrue($blockdata->timemodified >= $before && $blockdata->timemodified <= $after);
 684          $this->assertTrue($blockdata->timecreated >= $before && $blockdata->timecreated <= $after);
 685  
 686          // Get block from manager.
 687          $blockmanager->load_blocks();
 688          $blocks = $blockmanager->get_blocks_for_region($regionname);
 689          $block = reset($blocks);
 690  
 691          // Wait until at least the next second.
 692          while (time() === $after) {
 693              usleep(100000);
 694          }
 695  
 696          // Update block settings.
 697          $this->setAdminUser();
 698          $data = (object)['text' => ['text' => 'New text', 'itemid' => 0, 'format' => FORMAT_HTML]];
 699          $before = time();
 700          $block->instance_config_save($data);
 701          $after = time();
 702  
 703          // Check time modified updated, but time created didn't.
 704          $newblockdata = $DB->get_record('block_instances', ['blockname' => 'html']);
 705          $this->assertTrue(
 706                  $newblockdata->timemodified >= $before &&
 707                  $newblockdata->timemodified <= $after &&
 708                  $newblockdata->timemodified > $blockdata->timemodified);
 709          $this->assertEquals($blockdata->timecreated, $newblockdata->timecreated);
 710  
 711          // Also try repositioning the block.
 712          while (time() === $after) {
 713              usleep(100000);
 714          }
 715          $before = time();
 716          $blockmanager->reposition_block($blockdata->id, $regionname, 10);
 717          $after = time();
 718          $blockdata = $newblockdata;
 719          $newblockdata = $DB->get_record('block_instances', ['blockname' => 'html']);
 720          $this->assertTrue(
 721                  $newblockdata->timemodified >= $before &&
 722                  $newblockdata->timemodified <= $after &&
 723                  $newblockdata->timemodified > $blockdata->timemodified);
 724          $this->assertEquals($blockdata->timecreated, $newblockdata->timecreated);
 725      }
 726  
 727      /**
 728       * Tests that dashboard pages get their blocks loaded correctly.
 729       */
 730      public function test_default_dashboard() {
 731          global $CFG, $PAGE, $DB;
 732          $storedpage = $PAGE;
 733          require_once($CFG->dirroot . '/my/lib.php');
 734          $this->purge_blocks();
 735          $regionname = 'a-region';
 736          $blockname = $this->get_a_known_block_type();
 737          $user = self::getDataGenerator()->create_user();
 738          $syscontext = context_system::instance();
 739          $usercontext = context_user::instance($user->id);
 740          // Add sitewide 'sticky' blocks. The page is not setup exactly as a site page would be...
 741          // but it does seem to mean that the bloacks are added correctly.
 742          list($sitepage, $sitebm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'site-index');
 743          $sitebm->add_block($blockname, $regionname, 0, true, '*');
 744          $sitestickyblock1 = $this->get_last_created_block();
 745          $sitebm->add_block($blockname, $regionname, 1, true, '*');
 746          $sitestickyblock2 = $this->get_last_created_block();
 747          $sitebm->add_block($blockname, $regionname, 8, true, '*');
 748          $sitestickyblock3 = $this->get_last_created_block();
 749          // Blocks that should not be picked up by any other pages in this unit test.
 750          $sitebm->add_block($blockname, $regionname, -8, true, 'site-index-*');
 751          $sitebm->add_block($blockname, $regionname, -9, true, 'site-index');
 752          $sitebm->load_blocks();
 753          // This repositioning should not be picked up.
 754          $sitebm->reposition_block($sitestickyblock3->id, $regionname, 9);
 755          // Setup the default dashboard page. This adds the blocks with the correct parameters, but seems to not be
 756          // an exact page/blockmanager setup for the default dashboard setup page.
 757          $defaultmy = my_get_page(null, MY_PAGE_PRIVATE);
 758          list($defaultmypage, $defaultmybm) = $this->get_a_page_and_block_manager(array($regionname), null, 'my-index', $defaultmy->id);
 759          $PAGE = $defaultmypage;
 760          $defaultmybm->add_block($blockname, $regionname, -2, false, $defaultmypage->pagetype, $defaultmypage->subpage);
 761          $defaultblock1 = $this->get_last_created_block();
 762          $defaultmybm->add_block($blockname, $regionname, 3, false, $defaultmypage->pagetype, $defaultmypage->subpage);
 763          $defaultblock2 = $this->get_last_created_block();
 764          $defaultmybm->load_blocks();
 765          $defaultmybm->reposition_block($sitestickyblock1->id, $regionname, 4);
 766          // Setup the user's dashboard.
 767          $usermy = my_copy_page($user->id);
 768          list($mypage, $mybm) = $this->get_a_page_and_block_manager(array($regionname), $usercontext, 'my-index', $usermy->id);
 769          $PAGE = $mypage;
 770          $mybm->add_block($blockname, $regionname, 5, false, $mypage->pagetype, $mypage->subpage);
 771          $block1 = $this->get_last_created_block();
 772          $mybm->load_blocks();
 773          $mybm->reposition_block($sitestickyblock2->id, $regionname, -1);
 774          // Reload the blocks in the managers.
 775          context_helper::reset_caches();
 776          $defaultmybm->reset_caches();
 777          $this->assertNull($defaultmybm->get_loaded_blocks());
 778          $defaultmybm->load_blocks();
 779          $this->assertNotNull($defaultmybm->get_loaded_blocks());
 780          $defaultbr = $defaultmybm->get_blocks_for_region($regionname);
 781          $mybm->reset_caches();
 782          $this->assertNull($mybm->get_loaded_blocks());
 783          $mybm->load_blocks();
 784          $this->assertNotNull($mybm->get_loaded_blocks());
 785          $mybr = $mybm->get_blocks_for_region($regionname);
 786          // Test that a user dashboard when forced to use the default finds the correct blocks.
 787          list($forcedmypage, $forcedmybm) = $this->get_a_page_and_block_manager(array($regionname), $usercontext, 'my-index', $defaultmy->id);
 788          $forcedmybm->load_blocks();
 789          $forcedmybr = $forcedmybm->get_blocks_for_region($regionname);
 790          // Check that the default page is in the expected order.
 791          $this->assertCount(5, $defaultbr);
 792          $this->assertEquals($defaultblock1->id, $defaultbr[0]->instance->id);
 793          $this->assertEquals('-2', $defaultbr[0]->instance->weight);
 794          $this->assertEquals($sitestickyblock2->id, $defaultbr[1]->instance->id);
 795          $this->assertEquals('1', $defaultbr[1]->instance->weight);
 796          $this->assertEquals($defaultblock2->id, $defaultbr[2]->instance->id);
 797          $this->assertEquals('3', $defaultbr[2]->instance->weight);
 798          $this->assertEquals($sitestickyblock1->id, $defaultbr[3]->instance->id);
 799          $this->assertEquals('4', $defaultbr[3]->instance->weight);
 800          $this->assertEquals($sitestickyblock3->id, $defaultbr[4]->instance->id);
 801          $this->assertEquals('8', $defaultbr[4]->instance->weight);
 802          // Check that the correct block are present in the expected order for a.
 803          $this->assertCount(5, $forcedmybr);
 804          $this->assertEquals($defaultblock1->id, $forcedmybr[0]->instance->id);
 805          $this->assertEquals('-2', $forcedmybr[0]->instance->weight);
 806          $this->assertEquals($sitestickyblock2->id, $forcedmybr[1]->instance->id);
 807          $this->assertEquals('1', $forcedmybr[1]->instance->weight);
 808          $this->assertEquals($defaultblock2->id, $forcedmybr[2]->instance->id);
 809          $this->assertEquals('3', $forcedmybr[2]->instance->weight);
 810          $this->assertEquals($sitestickyblock1->id, $forcedmybr[3]->instance->id);
 811          $this->assertEquals('4', $forcedmybr[3]->instance->weight);
 812          $this->assertEquals($sitestickyblock3->id, $forcedmybr[4]->instance->id);
 813          $this->assertEquals('8', $forcedmybr[4]->instance->weight);
 814          // Check that the correct blocks are present in the standard my page.
 815          $this->assertCount(6, $mybr);
 816          $this->assertEquals('-2', $mybr[0]->instance->weight);
 817          $this->assertEquals($sitestickyblock2->id, $mybr[1]->instance->id);
 818          $this->assertEquals('-1', $mybr[1]->instance->weight);
 819          $this->assertEquals('3', $mybr[2]->instance->weight);
 820          // Test the override on the first sticky block was copied and picked up.
 821          $this->assertEquals($sitestickyblock1->id, $mybr[3]->instance->id);
 822          $this->assertEquals('4', $mybr[3]->instance->weight);
 823          $this->assertEquals($block1->id, $mybr[4]->instance->id);
 824          $this->assertEquals('5', $mybr[4]->instance->weight);
 825          $this->assertEquals($sitestickyblock3->id, $mybr[5]->instance->id);
 826          $this->assertEquals('8', $mybr[5]->instance->weight);
 827          $PAGE = $storedpage;
 828      }
 829  }
 830  
 831  /**
 832   * Test-specific subclass to make some protected things public.
 833   */
 834  class testable_block_manager extends block_manager {
 835      /**
 836       * Resets the caches in the block manager.
 837       * This allows blocks to be reloaded correctly.
 838       */
 839      public function reset_caches() {
 840          $this->birecordsbyregion = null;
 841          $this->blockinstances = array();
 842          $this->visibleblockcontent = array();
 843      }
 844      public function mark_loaded() {
 845          $this->birecordsbyregion = array();
 846      }
 847      public function get_loaded_blocks() {
 848          return $this->birecordsbyregion;
 849      }
 850  }
 851  
 852  /**
 853   * Test-specific subclass to make some protected things public.
 854   */
 855  class block_ablocktype extends block_base {
 856      public function init() {
 857      }
 858  }