Merge branch 'MDL-73502' of https://github.com/stronk7/moodle
[moodle.git] / lib / blocklib.php
blobdc391583aef5614100f0f73c674b653a05f6a5a0
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
23 * @package core
24 * @subpackage block
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**#@+
32 * Default names for the block regions in the standard theme.
34 define('BLOCK_POS_LEFT', 'side-pre');
35 define('BLOCK_POS_RIGHT', 'side-post');
36 /**#@-*/
38 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
39 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
40 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
42 define('BUI_CONTEXTS_CURRENT', 0);
43 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
45 // Position of "Add block" control, to be used in theme config as a value for $THEME->addblockposition:
46 // - default: as a fake block that is displayed in editing mode
47 // - flatnav: "Add block" item in the flat navigation drawer in editing mode
48 // - custom: none of the above, theme will take care of displaying the control.
49 define('BLOCK_ADDBLOCK_POSITION_DEFAULT', 0);
50 define('BLOCK_ADDBLOCK_POSITION_FLATNAV', 1);
51 define('BLOCK_ADDBLOCK_POSITION_CUSTOM', -1);
53 /**
54 * Exception thrown when someone tried to do something with a block that does
55 * not exist on a page.
57 * @copyright 2009 Tim Hunt
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 * @since Moodle 2.0
61 class block_not_on_page_exception extends moodle_exception {
62 /**
63 * Constructor
64 * @param int $instanceid the block instance id of the block that was looked for.
65 * @param object $page the current page.
67 public function __construct($instanceid, $page) {
68 $a = new stdClass;
69 $a->instanceid = $instanceid;
70 $a->url = $page->url->out();
71 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
75 /**
76 * This class keeps track of the block that should appear on a moodle_page.
78 * The page to work with as passed to the constructor.
80 * @copyright 2009 Tim Hunt
81 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
82 * @since Moodle 2.0
84 class block_manager {
85 /**
86 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
87 * although other weights are valid.
89 const MAX_WEIGHT = 10;
91 /// Field declarations =========================================================
93 /**
94 * the moodle_page we are managing blocks for.
95 * @var moodle_page
97 protected $page;
99 /** @var array region name => 1.*/
100 protected $regions = array();
102 /** @var string the region where new blocks are added.*/
103 protected $defaultregion = null;
105 /** @var array will be $DB->get_records('blocks') */
106 protected $allblocks = null;
109 * @var array blocks that this user can add to this page. Will be a subset
110 * of $allblocks, but with array keys block->name. Access this via the
111 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
113 protected $addableblocks = null;
116 * Will be an array region-name => array(db rows loaded in load_blocks);
117 * @var array
119 protected $birecordsbyregion = null;
122 * array region-name => array(block objects); populated as necessary by
123 * the ensure_instances_exist method.
124 * @var array
126 protected $blockinstances = array();
129 * array region-name => array(block_contents objects) what actually needs to
130 * be displayed in each region.
131 * @var array
133 protected $visibleblockcontent = array();
136 * array region-name => array(block_contents objects) extra block-like things
137 * to be displayed in each region, before the real blocks.
138 * @var array
140 protected $extracontent = array();
143 * Used by the block move id, to track whether a block is currently being moved.
145 * When you click on the move icon of a block, first the page needs to reload with
146 * extra UI for choosing a new position for a particular block. In that situation
147 * this field holds the id of the block being moved.
149 * @var integer|null
151 protected $movingblock = null;
154 * Show only fake blocks
156 protected $fakeblocksonly = false;
158 /// Constructor ================================================================
161 * Constructor.
162 * @param object $page the moodle_page object object we are managing the blocks for,
163 * or a reasonable faxilimily. (See the comment at the top of this class
164 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
166 public function __construct($page) {
167 $this->page = $page;
170 /// Getter methods =============================================================
173 * Get an array of all region names on this page where a block may appear
175 * @return array the internal names of the regions on this page where block may appear.
177 public function get_regions() {
178 if (is_null($this->defaultregion)) {
179 $this->page->initialise_theme_and_output();
181 return array_keys($this->regions);
185 * Get the region name of the region blocks are added to by default
187 * @return string the internal names of the region where new blocks are added
188 * by default, and where any blocks from an unrecognised region are shown.
189 * (Imagine that blocks were added with one theme selected, then you switched
190 * to a theme with different block positions.)
192 public function get_default_region() {
193 $this->page->initialise_theme_and_output();
194 return $this->defaultregion;
198 * The list of block types that may be added to this page.
200 * @return array block name => record from block table.
202 public function get_addable_blocks() {
203 $this->check_is_loaded();
205 if (!is_null($this->addableblocks)) {
206 return $this->addableblocks;
209 // Lazy load.
210 $this->addableblocks = array();
212 $allblocks = blocks_get_record();
213 if (empty($allblocks)) {
214 return $this->addableblocks;
217 $unaddableblocks = self::get_undeletable_block_types();
218 $requiredbythemeblocks = $this->get_required_by_theme_block_types();
219 $pageformat = $this->page->pagetype;
220 foreach($allblocks as $block) {
221 if (!$bi = block_instance($block->name)) {
222 continue;
224 if ($block->visible && !in_array($block->name, $unaddableblocks) &&
225 !in_array($block->name, $requiredbythemeblocks) &&
226 $bi->can_block_be_added($this->page) &&
227 ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
228 blocks_name_allowed_in_format($block->name, $pageformat) &&
229 $bi->user_can_addto($this->page)) {
230 $block->title = $bi->get_title();
231 $this->addableblocks[$block->name] = $block;
235 core_collator::asort_objects_by_property($this->addableblocks, 'title');
236 return $this->addableblocks;
240 * Given a block name, find out of any of them are currently present in the page
242 * @param string $blockname - the basic name of a block (eg "navigation")
243 * @return boolean - is there one of these blocks in the current page?
245 public function is_block_present($blockname) {
246 if (empty($this->blockinstances)) {
247 return false;
250 $requiredbythemeblocks = $this->get_required_by_theme_block_types();
251 foreach ($this->blockinstances as $region) {
252 foreach ($region as $instance) {
253 if (empty($instance->instance->blockname)) {
254 continue;
256 if ($instance->instance->blockname == $blockname) {
257 if ($instance->instance->requiredbytheme) {
258 if (!in_array($blockname, $requiredbythemeblocks)) {
259 continue;
262 return true;
266 return false;
270 * Find out if a block type is known by the system
272 * @param string $blockname the name of the type of block.
273 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
274 * @return boolean true if this block in installed.
276 public function is_known_block_type($blockname, $includeinvisible = false) {
277 $blocks = $this->get_installed_blocks();
278 foreach ($blocks as $block) {
279 if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
280 return true;
283 return false;
287 * Find out if a region exists on a page
289 * @param string $region a region name
290 * @return boolean true if this region exists on this page.
292 public function is_known_region($region) {
293 if (empty($region)) {
294 return false;
296 return array_key_exists($region, $this->regions);
300 * Get an array of all blocks within a given region
302 * @param string $region a block region that exists on this page.
303 * @return array of block instances.
305 public function get_blocks_for_region($region) {
306 $this->check_is_loaded();
307 $this->ensure_instances_exist($region);
308 return $this->blockinstances[$region];
312 * Returns an array of block content objects that exist in a region
314 * @param string $region a block region that exists on this page.
315 * @return array of block block_contents objects for all the blocks in a region.
317 public function get_content_for_region($region, $output) {
318 $this->check_is_loaded();
319 $this->ensure_content_created($region, $output);
320 return $this->visibleblockcontent[$region];
324 * Returns an array of block content objects for all the existings regions
326 * @param renderer_base $output the rendered to use
327 * @return array of block block_contents objects for all the blocks in all regions.
328 * @since Moodle 3.3
330 public function get_content_for_all_regions($output) {
331 $contents = array();
332 $this->check_is_loaded();
334 foreach ($this->regions as $region => $val) {
335 $this->ensure_content_created($region, $output);
336 $contents[$region] = $this->visibleblockcontent[$region];
338 return $contents;
342 * Helper method used by get_content_for_region.
343 * @param string $region region name
344 * @param float $weight weight. May be fractional, since you may want to move a block
345 * between ones with weight 2 and 3, say ($weight would be 2.5).
346 * @return string URL for moving block $this->movingblock to this position.
348 protected function get_move_target_url($region, $weight) {
349 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
350 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
354 * Determine whether a region contains anything. (Either any real blocks, or
355 * the add new block UI.)
357 * (You may wonder why the $output parameter is required. Unfortunately,
358 * because of the way that blocks work, the only reliable way to find out
359 * if a block will be visible is to get the content for output, and to
360 * get the content, you need a renderer. Fortunately, this is not a
361 * performance problem, because we cache the output that is generated, and
362 * in almost every case where we call region_has_content, we are about to
363 * output the blocks anyway, so we are not doing wasted effort.)
365 * @param string $region a block region that exists on this page.
366 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
367 * @return boolean Whether there is anything in this region.
369 public function region_has_content($region, $output) {
371 if (!$this->is_known_region($region)) {
372 return false;
374 $this->check_is_loaded();
375 $this->ensure_content_created($region, $output);
376 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
377 // Mark Nielsen's patch - part 1
378 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
379 // If editing is on, we need all the block regions visible, for the
380 // move blocks UI.
381 return true;
383 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
387 * Determine whether a region contains any fake blocks.
389 * (Fake blocks are typically added to the extracontent array per region)
391 * @param string $region a block region that exists on this page.
392 * @return boolean Whether there are fake blocks in this region.
394 public function region_has_fakeblocks($region): bool {
395 return !empty($this->extracontent[$region]);
399 * Get an array of all of the installed blocks.
401 * @return array contents of the block table.
403 public function get_installed_blocks() {
404 global $DB;
405 if (is_null($this->allblocks)) {
406 $this->allblocks = $DB->get_records('block');
408 return $this->allblocks;
412 * @return array names of block types that must exist on every page with this theme.
414 public function get_required_by_theme_block_types() {
415 $requiredbythemeblocks = false;
416 if (isset($this->page->theme->requiredblocks)) {
417 $requiredbythemeblocks = $this->page->theme->requiredblocks;
420 if ($requiredbythemeblocks === false) {
421 return array('navigation', 'settings');
422 } else if ($requiredbythemeblocks === '') {
423 return array();
424 } else if (is_string($requiredbythemeblocks)) {
425 return explode(',', $requiredbythemeblocks);
426 } else {
427 return $requiredbythemeblocks;
432 * Make this block type undeletable and unaddable.
434 * @param mixed $blockidorname string or int
436 public static function protect_block($blockidorname) {
437 global $DB;
439 $syscontext = context_system::instance();
441 require_capability('moodle/site:config', $syscontext);
443 $block = false;
444 if (is_int($blockidorname)) {
445 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
446 } else {
447 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
449 $undeletableblocktypes = self::get_undeletable_block_types();
450 if (!in_array($block->name, $undeletableblocktypes)) {
451 $undeletableblocktypes[] = $block->name;
452 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
453 add_to_config_log('block_protect', "0", "1", $block->name);
458 * Make this block type deletable and addable.
460 * @param mixed $blockidorname string or int
462 public static function unprotect_block($blockidorname) {
463 global $DB;
465 $syscontext = context_system::instance();
467 require_capability('moodle/site:config', $syscontext);
469 $block = false;
470 if (is_int($blockidorname)) {
471 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
472 } else {
473 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
475 $undeletableblocktypes = self::get_undeletable_block_types();
476 if (in_array($block->name, $undeletableblocktypes)) {
477 $undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name));
478 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
479 add_to_config_log('block_protect', "1", "0", $block->name);
485 * Get the list of "protected" blocks via admin block manager ui.
487 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
489 public static function get_undeletable_block_types() {
490 global $CFG;
491 $undeletableblocks = false;
492 if (isset($CFG->undeletableblocktypes)) {
493 $undeletableblocks = $CFG->undeletableblocktypes;
496 if (empty($undeletableblocks)) {
497 return array();
498 } else if (is_string($undeletableblocks)) {
499 return explode(',', $undeletableblocks);
500 } else {
501 return $undeletableblocks;
505 /// Setter methods =============================================================
508 * Add a region to a page
510 * @param string $region add a named region where blocks may appear on the current page.
511 * This is an internal name, like 'side-pre', not a string to display in the UI.
512 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
514 public function add_region($region, $custom = true) {
515 global $SESSION;
516 $this->check_not_yet_loaded();
517 if ($custom) {
518 if (array_key_exists($region, $this->regions)) {
519 // This here is EXACTLY why we should not be adding block regions into a page. It should
520 // ALWAYS be done in a theme layout.
521 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
523 // We need to register this custom region against the page type being used.
524 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
525 $type = $this->page->pagetype;
526 if (!isset($SESSION->custom_block_regions)) {
527 $SESSION->custom_block_regions = array($type => array($region));
528 } else if (!isset($SESSION->custom_block_regions[$type])) {
529 $SESSION->custom_block_regions[$type] = array($region);
530 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
531 $SESSION->custom_block_regions[$type][] = $region;
534 $this->regions[$region] = 1;
536 // Checking the actual property instead of calling get_default_region as it ends up in a recursive call.
537 if (empty($this->defaultregion)) {
538 $this->set_default_region($region);
543 * Add an array of regions
544 * @see add_region()
546 * @param array $regions this utility method calls add_region for each array element.
548 public function add_regions($regions, $custom = true) {
549 foreach ($regions as $region) {
550 $this->add_region($region, $custom);
555 * Finds custom block regions associated with a page type and registers them with this block manager.
557 * @param string $pagetype
559 public function add_custom_regions_for_pagetype($pagetype) {
560 global $SESSION;
561 if (isset($SESSION->custom_block_regions[$pagetype])) {
562 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
563 $this->add_region($customregion, false);
569 * Set the default region for new blocks on the page
571 * @param string $defaultregion the internal names of the region where new
572 * blocks should be added by default, and where any blocks from an
573 * unrecognised region are shown.
575 public function set_default_region($defaultregion) {
576 $this->check_not_yet_loaded();
577 if ($defaultregion) {
578 $this->check_region_is_known($defaultregion);
580 $this->defaultregion = $defaultregion;
584 * Add something that looks like a block, but which isn't an actual block_instance,
585 * to this page.
587 * @param block_contents $bc the content of the block-like thing.
588 * @param string $region a block region that exists on this page.
590 public function add_fake_block($bc, $region) {
591 $this->page->initialise_theme_and_output();
592 if (!$this->is_known_region($region)) {
593 $region = $this->get_default_region();
595 if (array_key_exists($region, $this->visibleblockcontent)) {
596 throw new coding_exception('block_manager has already prepared the blocks in region ' .
597 $region . 'for output. It is too late to add a fake block.');
599 if (!isset($bc->attributes['data-block'])) {
600 $bc->attributes['data-block'] = '_fake';
602 $bc->attributes['class'] .= ' block_fake';
603 $this->extracontent[$region][] = $bc;
607 * Checks to see whether all of the blocks within the given region are docked
609 * @see region_uses_dock
610 * @param string $region
611 * @return bool True if all of the blocks within that region are docked
613 * Return false as from MDL-64506
615 public function region_completely_docked($region, $output) {
616 return false;
620 * Checks to see whether any of the blocks within the given regions are docked
622 * @see region_completely_docked
623 * @param array|string $regions array of regions (or single region)
624 * @return bool True if any of the blocks within that region are docked
626 * Return false as from MDL-64506
628 public function region_uses_dock($regions, $output) {
629 return false;
632 /// Actions ====================================================================
635 * This method actually loads the blocks for our page from the database.
637 * @param boolean|null $includeinvisible
638 * null (default) - load hidden blocks if $this->page->user_is_editing();
639 * true - load hidden blocks.
640 * false - don't load hidden blocks.
642 public function load_blocks($includeinvisible = null) {
643 global $DB, $CFG;
645 if (!is_null($this->birecordsbyregion)) {
646 // Already done.
647 return;
650 if ($CFG->version < 2009050619) {
651 // Upgrade/install not complete. Don't try too show any blocks.
652 $this->birecordsbyregion = array();
653 return;
656 // Ensure we have been initialised.
657 if (is_null($this->defaultregion)) {
658 $this->page->initialise_theme_and_output();
659 // If there are still no block regions, then there are no blocks on this page.
660 if (empty($this->regions)) {
661 $this->birecordsbyregion = array();
662 return;
666 // Check if we need to load normal blocks
667 if ($this->fakeblocksonly) {
668 $this->birecordsbyregion = $this->prepare_per_region_arrays();
669 return;
672 // Exclude auto created blocks if they are not undeletable in this theme.
673 $requiredbytheme = $this->get_required_by_theme_block_types();
674 $requiredbythemecheck = '';
675 $requiredbythemeparams = array();
676 $requiredbythemenotparams = array();
677 if (!empty($requiredbytheme)) {
678 list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED, 'requiredbytheme');
679 list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED,
680 'notrequiredbytheme', false);
681 $requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
682 ' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
683 } else {
684 $requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
687 if (is_null($includeinvisible)) {
688 $includeinvisible = $this->page->user_is_editing();
690 if ($includeinvisible) {
691 $visiblecheck = '';
692 } else {
693 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL) AND (bs.visible = 1 OR bs.visible IS NULL)';
696 $context = $this->page->context;
697 $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
698 $parentcontextparams = array();
699 $parentcontextids = $context->get_parent_context_ids();
700 if ($parentcontextids) {
701 list($parentcontexttest, $parentcontextparams) =
702 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
703 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
706 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
707 list($pagetypepatterntest, $pagetypepatternparams) =
708 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
710 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
711 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
713 $systemcontext = context_system::instance();
714 $params = array(
715 'contextlevel' => CONTEXT_BLOCK,
716 'subpage1' => $this->page->subpage,
717 'subpage2' => $this->page->subpage,
718 'subpage3' => $this->page->subpage,
719 'contextid1' => $context->id,
720 'contextid2' => $context->id,
721 'contextid3' => $systemcontext->id,
722 'contextid4' => $systemcontext->id,
723 'pagetype' => $this->page->pagetype,
724 'pagetype2' => $this->page->pagetype,
726 if ($this->page->subpage === '') {
727 $params['subpage1'] = '';
728 $params['subpage2'] = '';
729 $params['subpage3'] = '';
731 $sql = "SELECT
732 bi.id,
733 COALESCE(bp.id, bs.id) AS blockpositionid,
734 bi.blockname,
735 bi.parentcontextid,
736 bi.showinsubcontexts,
737 bi.pagetypepattern,
738 bi.requiredbytheme,
739 bi.subpagepattern,
740 bi.defaultregion,
741 bi.defaultweight,
742 COALESCE(bp.visible, bs.visible, 1) AS visible,
743 COALESCE(bp.region, bs.region, bi.defaultregion) AS region,
744 COALESCE(bp.weight, bs.weight, bi.defaultweight) AS weight,
745 bi.configdata
746 $ccselect
748 FROM {block_instances} bi
749 JOIN {block} b ON bi.blockname = b.name
750 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
751 AND bp.contextid = :contextid1
752 AND bp.pagetype = :pagetype
753 AND bp.subpage = :subpage1
754 LEFT JOIN {block_positions} bs ON bs.blockinstanceid = bi.id
755 AND bs.contextid = :contextid4
756 AND bs.pagetype = :pagetype2
757 AND bs.subpage = :subpage3
758 $ccjoin
760 WHERE
761 $contexttest
762 AND bi.pagetypepattern $pagetypepatterntest
763 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
764 $visiblecheck
765 AND b.visible = 1
766 $requiredbythemecheck
768 ORDER BY
769 COALESCE(bp.region, bs.region, bi.defaultregion),
770 COALESCE(bp.weight, bs.weight, bi.defaultweight),
771 bi.id";
773 $allparams = $params + $parentcontextparams + $pagetypepatternparams + $requiredbythemeparams + $requiredbythemenotparams;
774 $blockinstances = $DB->get_recordset_sql($sql, $allparams);
776 $this->birecordsbyregion = $this->prepare_per_region_arrays();
777 $unknown = array();
778 foreach ($blockinstances as $bi) {
779 context_helper::preload_from_record($bi);
780 if ($this->is_known_region($bi->region)) {
781 $this->birecordsbyregion[$bi->region][] = $bi;
782 } else {
783 $unknown[] = $bi;
786 $blockinstances->close();
788 // Pages don't necessarily have a defaultregion. The one time this can
789 // happen is when there are no theme block regions, but the script itself
790 // has a block region in the main content area.
791 if (!empty($this->defaultregion)) {
792 $this->birecordsbyregion[$this->defaultregion] =
793 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
798 * Add a block to the current page, or related pages. The block is added to
799 * context $this->page->contextid. If $pagetypepattern $subpagepattern
801 * @param string $blockname The type of block to add.
802 * @param string $region the block region on this page to add the block to.
803 * @param integer $weight determines the order where this block appears in the region.
804 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
805 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
806 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
808 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
809 global $DB;
810 // Allow invisible blocks because this is used when adding default page blocks, which
811 // might include invisible ones if the user makes some default blocks invisible
812 $this->check_known_block_type($blockname, true);
813 $this->check_region_is_known($region);
815 if (empty($pagetypepattern)) {
816 $pagetypepattern = $this->page->pagetype;
819 $blockinstance = new stdClass;
820 $blockinstance->blockname = $blockname;
821 $blockinstance->parentcontextid = $this->page->context->id;
822 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
823 $blockinstance->pagetypepattern = $pagetypepattern;
824 $blockinstance->subpagepattern = $subpagepattern;
825 $blockinstance->defaultregion = $region;
826 $blockinstance->defaultweight = $weight;
827 $blockinstance->configdata = '';
828 $blockinstance->timecreated = time();
829 $blockinstance->timemodified = $blockinstance->timecreated;
830 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
832 // Ensure the block context is created.
833 context_block::instance($blockinstance->id);
835 // If the new instance was created, allow it to do additional setup
836 if ($block = block_instance($blockname, $blockinstance)) {
837 $block->instance_create();
842 * When passed a block name create a new instance of the block in the specified region.
844 * @param string $blockname Name of the block to add.
845 * @param null|string $blockregion If defined add the new block to the specified region.
847 public function add_block_at_end_of_default_region($blockname, $blockregion = null) {
848 if (empty($this->birecordsbyregion)) {
849 // No blocks or block regions exist yet.
850 return;
853 if ($blockregion === null) {
854 $defaulregion = $this->get_default_region();
855 } else {
856 $defaulregion = $blockregion;
859 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
860 if ($lastcurrentblock) {
861 $weight = $lastcurrentblock->weight + 1;
862 } else {
863 $weight = 0;
866 if ($this->page->subpage) {
867 $subpage = $this->page->subpage;
868 } else {
869 $subpage = null;
872 // Special case. Course view page type include the course format, but we
873 // want to add the block non-format-specifically.
874 $pagetypepattern = $this->page->pagetype;
875 if (strpos($pagetypepattern, 'course-view') === 0) {
876 $pagetypepattern = 'course-view-*';
879 // We should end using this for ALL the blocks, making always the 1st option
880 // the default one to be used. Until then, this is one hack to avoid the
881 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
882 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
883 // (the FIRST $pagetypepattern will be set)
885 // We are applying it to all blocks created in mod pages for now and only if the
886 // default pagetype is not one of the available options
887 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
888 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
889 // Only go for the first if the pagetype is not a valid option
890 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
891 $pagetypepattern = key($pagetypelist);
894 // Surely other pages like course-report will need this too, they just are not important
895 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
897 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
901 * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
902 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
903 * and incremented by the position of the block in the $blocks array
905 * @param array $blocks array with array keys the region names, and values an array of block names.
906 * @param string $pagetypepattern optional. Passed to {@link add_block()}
907 * @param string $subpagepattern optional. Passed to {@link add_block()}
908 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
909 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
911 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
912 $initialweight = $weight;
913 $this->add_regions(array_keys($blocks), false);
914 foreach ($blocks as $region => $regionblocks) {
915 foreach ($regionblocks as $offset => $blockname) {
916 $weight = $initialweight + $offset;
917 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
923 * Move a block to a new position on this page.
925 * If this block cannot appear on any other pages, then we change defaultposition/weight
926 * in the block_instances table. Otherwise we just set the position on this page.
928 * @param $blockinstanceid the block instance id.
929 * @param $newregion the new region name.
930 * @param $newweight the new weight.
932 public function reposition_block($blockinstanceid, $newregion, $newweight) {
933 global $DB;
935 $this->check_region_is_known($newregion);
936 $inst = $this->find_instance($blockinstanceid);
938 $bi = $inst->instance;
939 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
940 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
941 (!$this->page->subpage || $bi->subpagepattern)) {
943 // Set default position
944 $newbi = new stdClass;
945 $newbi->id = $bi->id;
946 $newbi->defaultregion = $newregion;
947 $newbi->defaultweight = $newweight;
948 $newbi->timemodified = time();
949 $DB->update_record('block_instances', $newbi);
951 if ($bi->blockpositionid) {
952 $bp = new stdClass;
953 $bp->id = $bi->blockpositionid;
954 $bp->region = $newregion;
955 $bp->weight = $newweight;
956 $DB->update_record('block_positions', $bp);
959 } else {
960 // Just set position on this page.
961 $bp = new stdClass;
962 $bp->region = $newregion;
963 $bp->weight = $newweight;
965 if ($bi->blockpositionid) {
966 $bp->id = $bi->blockpositionid;
967 $DB->update_record('block_positions', $bp);
969 } else {
970 $bp->blockinstanceid = $bi->id;
971 $bp->contextid = $this->page->context->id;
972 $bp->pagetype = $this->page->pagetype;
973 if ($this->page->subpage) {
974 $bp->subpage = $this->page->subpage;
975 } else {
976 $bp->subpage = '';
978 $bp->visible = $bi->visible;
979 $DB->insert_record('block_positions', $bp);
985 * Find a given block by its instance id
987 * @param integer $instanceid
988 * @return block_base
990 public function find_instance($instanceid) {
991 foreach ($this->regions as $region => $notused) {
992 $this->ensure_instances_exist($region);
993 foreach($this->blockinstances[$region] as $instance) {
994 if ($instance->instance->id == $instanceid) {
995 return $instance;
999 throw new block_not_on_page_exception($instanceid, $this->page);
1002 /// Inner workings =============================================================
1005 * Check whether the page blocks have been loaded yet
1007 * @return void Throws coding exception if already loaded
1009 protected function check_not_yet_loaded() {
1010 if (!is_null($this->birecordsbyregion)) {
1011 throw new coding_exception('block_manager has already loaded the blocks, to it is too late to change things that might affect which blocks are visible.');
1016 * Check whether the page blocks have been loaded yet
1018 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
1020 * @return void Throws coding exception if already loaded
1022 protected function check_is_loaded() {
1023 if (is_null($this->birecordsbyregion)) {
1024 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
1029 * Check if a block type is known and usable
1031 * @param string $blockname The block type name to search for
1032 * @param bool $includeinvisible Include disabled block types in the initial pass
1033 * @return void Coding Exception thrown if unknown or not enabled
1035 protected function check_known_block_type($blockname, $includeinvisible = false) {
1036 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
1037 if ($this->is_known_block_type($blockname, true)) {
1038 throw new coding_exception('Unknown block type ' . $blockname);
1039 } else {
1040 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
1046 * Check if a region is known by its name
1048 * @param string $region
1049 * @return void Coding Exception thrown if the region is not known
1051 protected function check_region_is_known($region) {
1052 if (!$this->is_known_region($region)) {
1053 throw new coding_exception('Trying to reference an unknown block region ' . $region);
1058 * Returns an array of region names as keys and nested arrays for values
1060 * @return array an array where the array keys are the region names, and the array
1061 * values are empty arrays.
1063 protected function prepare_per_region_arrays() {
1064 $result = array();
1065 foreach ($this->regions as $region => $notused) {
1066 $result[$region] = array();
1068 return $result;
1072 * Create a set of new block instance from a record array
1074 * @param array $birecords An array of block instance records
1075 * @return array An array of instantiated block_instance objects
1077 protected function create_block_instances($birecords) {
1078 $results = array();
1079 foreach ($birecords as $record) {
1080 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
1081 $results[] = $blockobject;
1084 return $results;
1088 * Create all the block instances for all the blocks that were loaded by
1089 * load_blocks. This is used, for example, to ensure that all blocks get a
1090 * chance to initialise themselves via the {@link block_base::specialize()}
1091 * method, before any output is done.
1093 * It is also used to create any blocks that are "requiredbytheme" by the current theme.
1094 * These blocks that are auto-created have requiredbytheme set on the block instance
1095 * so they are only visible on themes that require them.
1097 public function create_all_block_instances() {
1098 $missing = false;
1100 // If there are any un-removable blocks that were not created - force them.
1101 $requiredbytheme = $this->get_required_by_theme_block_types();
1102 if (!$this->fakeblocksonly) {
1103 foreach ($requiredbytheme as $forced) {
1104 if (empty($forced)) {
1105 continue;
1107 $found = false;
1108 foreach ($this->get_regions() as $region) {
1109 foreach($this->birecordsbyregion[$region] as $instance) {
1110 if ($instance->blockname == $forced) {
1111 $found = true;
1115 if (!$found) {
1116 $this->add_block_required_by_theme($forced);
1117 $missing = true;
1122 if ($missing) {
1123 // Some blocks were missing. Lets do it again.
1124 $this->birecordsbyregion = null;
1125 $this->load_blocks();
1127 foreach ($this->get_regions() as $region) {
1128 $this->ensure_instances_exist($region);
1134 * Add a block that is required by the current theme but has not been
1135 * created yet. This is a special type of block that only shows in themes that
1136 * require it (by listing it in undeletable_block_types).
1138 * @param string $blockname the name of the block type.
1140 protected function add_block_required_by_theme($blockname) {
1141 global $DB;
1143 if (empty($this->birecordsbyregion)) {
1144 // No blocks or block regions exist yet.
1145 return;
1148 // Never auto create blocks when we are showing fake blocks only.
1149 if ($this->fakeblocksonly) {
1150 return;
1153 // Never add a duplicate block required by theme.
1154 if ($DB->record_exists('block_instances', array('blockname' => $blockname, 'requiredbytheme' => 1))) {
1155 return;
1158 $systemcontext = context_system::instance();
1159 $defaultregion = $this->get_default_region();
1160 // Add a special system wide block instance only for themes that require it.
1161 $blockinstance = new stdClass;
1162 $blockinstance->blockname = $blockname;
1163 $blockinstance->parentcontextid = $systemcontext->id;
1164 $blockinstance->showinsubcontexts = true;
1165 $blockinstance->requiredbytheme = true;
1166 $blockinstance->pagetypepattern = '*';
1167 $blockinstance->subpagepattern = null;
1168 $blockinstance->defaultregion = $defaultregion;
1169 $blockinstance->defaultweight = 0;
1170 $blockinstance->configdata = '';
1171 $blockinstance->timecreated = time();
1172 $blockinstance->timemodified = $blockinstance->timecreated;
1173 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
1175 // Ensure the block context is created.
1176 context_block::instance($blockinstance->id);
1178 // If the new instance was created, allow it to do additional setup.
1179 if ($block = block_instance($blockname, $blockinstance)) {
1180 $block->instance_create();
1185 * Return an array of content objects from a set of block instances
1187 * @param array $instances An array of block instances
1188 * @param renderer_base The renderer to use.
1189 * @param string $region the region name.
1190 * @return array An array of block_content (and possibly block_move_target) objects.
1192 protected function create_block_contents($instances, $output, $region) {
1193 $results = array();
1195 $lastweight = 0;
1196 $lastblock = 0;
1197 if ($this->movingblock) {
1198 $first = reset($instances);
1199 if ($first) {
1200 $lastweight = $first->instance->weight - 2;
1204 foreach ($instances as $instance) {
1205 $content = $instance->get_content_for_output($output);
1206 if (empty($content)) {
1207 continue;
1210 if ($this->movingblock && $lastweight != $instance->instance->weight &&
1211 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
1212 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
1215 if ($content->blockinstanceid == $this->movingblock) {
1216 $content->add_class('beingmoved');
1217 $content->annotation .= get_string('movingthisblockcancel', 'block',
1218 html_writer::link($this->page->url, get_string('cancel')));
1221 $results[] = $content;
1222 $lastweight = $instance->instance->weight;
1223 $lastblock = $instance->instance->id;
1226 if ($this->movingblock && $lastblock != $this->movingblock) {
1227 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
1229 return $results;
1233 * Ensure block instances exist for a given region
1235 * @param string $region Check for bi's with the instance with this name
1237 protected function ensure_instances_exist($region) {
1238 $this->check_region_is_known($region);
1239 if (!array_key_exists($region, $this->blockinstances)) {
1240 $this->blockinstances[$region] =
1241 $this->create_block_instances($this->birecordsbyregion[$region]);
1246 * Ensure that there is some content within the given region
1248 * @param string $region The name of the region to check
1250 public function ensure_content_created($region, $output) {
1251 $this->ensure_instances_exist($region);
1253 if (!has_capability('moodle/block:view', $this->page->context) ) {
1254 $this->visibleblockcontent[$region] = [];
1255 return;
1258 if (!array_key_exists($region, $this->visibleblockcontent)) {
1259 $contents = array();
1260 if (array_key_exists($region, $this->extracontent)) {
1261 $contents = $this->extracontent[$region];
1263 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1264 if (($region == $this->defaultregion) && (!isset($this->page->theme->addblockposition) ||
1265 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_DEFAULT)) {
1266 $addblockui = block_add_block_ui($this->page, $output);
1267 if ($addblockui) {
1268 $contents[] = $addblockui;
1271 $this->visibleblockcontent[$region] = $contents;
1275 /// Process actions from the URL ===============================================
1278 * Get the appropriate list of editing icons for a block. This is used
1279 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1281 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1282 * @return an array in the format for {@link block_contents::$controls}
1284 public function edit_controls($block) {
1285 global $CFG;
1287 $controls = array();
1288 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1289 $blocktitle = $block->title;
1290 if (empty($blocktitle)) {
1291 $blocktitle = $block->arialabel;
1294 if ($this->page->user_can_edit_blocks()) {
1295 // Move icon.
1296 $str = new lang_string('moveblock', 'block', $blocktitle);
1297 $controls[] = new action_menu_link_primary(
1298 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1299 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1300 $str,
1301 array('class' => 'editing_move')
1306 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1307 // Edit config icon - always show - needed for positioning UI.
1308 $str = new lang_string('configureblock', 'block', $blocktitle);
1309 $editactionurl = new moodle_url($actionurl, ['bui_editid' => $block->instance->id]);
1310 $editactionurl->remove_params(['sesskey']);
1312 // Handle editing block on admin index page, prevent the page redirecting before block action can begin.
1313 if ($editactionurl->compare(new moodle_url('/admin/index.php'), URL_MATCH_BASE)) {
1314 $editactionurl->param('cache', 1);
1317 $controls[] = new action_menu_link_secondary(
1318 $editactionurl,
1319 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1320 $str,
1321 array('class' => 'editing_edit')
1326 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1327 // Show/hide icon.
1328 if ($block->instance->visible) {
1329 $str = new lang_string('hideblock', 'block', $blocktitle);
1330 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1331 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1332 $attributes = array('class' => 'editing_hide');
1333 } else {
1334 $str = new lang_string('showblock', 'block', $blocktitle);
1335 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1336 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1337 $attributes = array('class' => 'editing_show');
1339 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1342 // Assign roles.
1343 if (get_assignable_roles($block->context, ROLENAME_SHORT)) {
1344 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id,
1345 'returnurl' => $this->page->url->out_as_local_url()));
1346 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1347 $controls[] = new action_menu_link_secondary(
1348 $rolesurl,
1349 new pix_icon('i/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1350 $str, array('class' => 'editing_assignroles')
1354 // Permissions.
1355 if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) {
1356 $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id,
1357 'returnurl' => $this->page->url->out_as_local_url()));
1358 $str = get_string('permissions', 'role');
1359 $controls[] = new action_menu_link_secondary(
1360 $rolesurl,
1361 new pix_icon('i/permissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1362 $str, array('class' => 'editing_permissions')
1366 // Change permissions.
1367 if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) {
1368 $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id,
1369 'returnurl' => $this->page->url->out_as_local_url()));
1370 $str = get_string('checkpermissions', 'role');
1371 $controls[] = new action_menu_link_secondary(
1372 $rolesurl,
1373 new pix_icon('i/checkpermissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1374 $str, array('class' => 'editing_checkroles')
1378 if ($this->user_can_delete_block($block)) {
1379 // Delete icon.
1380 $str = new lang_string('deleteblock', 'block', $blocktitle);
1381 $deleteactionurl = new moodle_url($actionurl, ['bui_deleteid' => $block->instance->id]);
1382 $deleteactionurl->remove_params(['sesskey']);
1384 // Handle deleting block on admin index page, prevent the page redirecting before block action can begin.
1385 if ($deleteactionurl->compare(new moodle_url('/admin/index.php'), URL_MATCH_BASE)) {
1386 $deleteactionurl->param('cache', 1);
1389 $deleteconfirmationurl = new moodle_url($actionurl, [
1390 'bui_deleteid' => $block->instance->id,
1391 'bui_confirm' => 1,
1392 'sesskey' => sesskey(),
1394 $blocktitle = $block->get_title();
1396 $controls[] = new action_menu_link_secondary(
1397 $deleteactionurl,
1398 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1399 $str,
1401 'class' => 'editing_delete',
1402 'data-confirmation' => 'modal',
1403 'data-confirmation-title-str' => json_encode(['deletecheck_modal', 'block']),
1404 'data-confirmation-question-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),
1405 'data-confirmation-yes-button-str' => json_encode(['delete', 'core']),
1406 'data-confirmation-toast' => 'true',
1407 'data-confirmation-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),
1408 'data-confirmation-destination' => $deleteconfirmationurl->out(false),
1413 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $block->context)) {
1414 $parentcontext = $block->context->get_parent_context();
1415 if (empty($parentcontext) || empty($parentcontext->locked)) {
1416 if ($block->context->locked) {
1417 $lockicon = 'i/unlock';
1418 $lockstring = get_string('managecontextunlock', 'admin');
1419 } else {
1420 $lockicon = 'i/lock';
1421 $lockstring = get_string('managecontextlock', 'admin');
1423 $controls[] = new action_menu_link_secondary(
1424 new moodle_url(
1425 '/admin/lock.php',
1427 'id' => $block->context->id,
1430 new pix_icon($lockicon, $lockstring, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1431 $lockstring,
1432 ['class' => 'editing_lock']
1437 return $controls;
1441 * @param block_base $block a block that appears on this page.
1442 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1444 protected function user_can_delete_block($block) {
1445 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1446 $block->user_can_addto($this->page) &&
1447 !in_array($block->instance->blockname, self::get_undeletable_block_types()) &&
1448 !in_array($block->instance->blockname, $this->get_required_by_theme_block_types());
1452 * Process any block actions that were specified in the URL.
1454 * @return boolean true if anything was done. False if not.
1456 public function process_url_actions() {
1457 if (!$this->page->user_is_editing()) {
1458 return false;
1460 return $this->process_url_add() || $this->process_url_delete() ||
1461 $this->process_url_show_hide() || $this->process_url_edit() ||
1462 $this->process_url_move();
1466 * Handle adding a block.
1467 * @return boolean true if anything was done. False if not.
1469 public function process_url_add() {
1470 global $CFG, $PAGE, $OUTPUT;
1472 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1473 $blockregion = optional_param('bui_blockregion', null, PARAM_TEXT);
1475 if ($blocktype === null) {
1476 return false;
1479 require_sesskey();
1481 if (!$this->page->user_can_edit_blocks()) {
1482 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1485 $addableblocks = $this->get_addable_blocks();
1487 if ($blocktype === '') {
1488 // Display add block selection.
1489 $addpage = new moodle_page();
1490 $addpage->set_pagelayout('admin');
1491 $addpage->blocks->show_only_fake_blocks(true);
1492 $addpage->set_course($this->page->course);
1493 $addpage->set_context($this->page->context);
1494 if ($this->page->cm) {
1495 $addpage->set_cm($this->page->cm);
1498 $addpagebase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1499 $addpageparams = $this->page->url->params();
1500 $addpage->set_url($addpagebase, $addpageparams);
1501 $addpage->set_block_actions_done();
1502 // At this point we are going to display the block selector, overwrite global $PAGE ready for this.
1503 $PAGE = $addpage;
1504 // Some functions use $OUTPUT so we need to replace that too.
1505 $OUTPUT = $addpage->get_renderer('core');
1507 $site = get_site();
1508 $straddblock = get_string('addblock');
1510 $PAGE->navbar->add($straddblock);
1511 $PAGE->set_title($straddblock);
1512 $PAGE->set_heading($site->fullname);
1513 echo $OUTPUT->header();
1514 echo $OUTPUT->heading($straddblock);
1516 if (!$addableblocks) {
1517 echo $OUTPUT->box(get_string('noblockstoaddhere'));
1518 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('back')), 'mx-3 mb-1');
1519 } else {
1520 $url = new moodle_url($addpage->url, array('sesskey' => sesskey()));
1521 echo $OUTPUT->render_from_template('core/add_block_body',
1522 ['blocks' => array_values($addableblocks),
1523 'url' => '?' . $url->get_query_string(false)]);
1524 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('cancel')), 'mx-3 mb-1');
1527 echo $OUTPUT->footer();
1528 // Make sure that nothing else happens after we have displayed this form.
1529 exit;
1532 if (!array_key_exists($blocktype, $addableblocks)) {
1533 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1536 $this->add_block_at_end_of_default_region($blocktype, $blockregion);
1538 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1539 $this->page->ensure_param_not_in_url('bui_addblock');
1541 return true;
1545 * Handle deleting a block.
1546 * @return boolean true if anything was done. False if not.
1548 public function process_url_delete() {
1549 global $CFG, $PAGE, $OUTPUT;
1551 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1552 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1554 if (!$blockid) {
1555 return false;
1558 $block = $this->page->blocks->find_instance($blockid);
1559 if (!$this->user_can_delete_block($block)) {
1560 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1563 if (!$confirmdelete) {
1564 $deletepage = new moodle_page();
1565 $deletepage->set_pagelayout('admin');
1566 $deletepage->blocks->show_only_fake_blocks(true);
1567 $deletepage->set_course($this->page->course);
1568 $deletepage->set_context($this->page->context);
1569 if ($this->page->cm) {
1570 $deletepage->set_cm($this->page->cm);
1573 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1574 $deleteurlparams = $this->page->url->params();
1575 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1576 $deletepage->set_block_actions_done();
1577 $deletepage->set_secondarynav($this->get_secondarynav($block));
1578 // At this point we are either going to redirect, or display the form, so
1579 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1580 $PAGE = $deletepage;
1581 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1582 $output = $deletepage->get_renderer('core');
1583 $OUTPUT = $output;
1585 $site = get_site();
1586 $blocktitle = $block->get_title();
1587 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1588 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1590 // If the block is being shown in sub contexts display a warning.
1591 if ($block->instance->showinsubcontexts == 1) {
1592 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1593 $systemcontext = context_system::instance();
1594 $messagestring = new stdClass();
1595 $messagestring->location = $parentcontext->get_context_name();
1597 // Checking for blocks that may have visibility on the front page and pages added on that.
1598 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1599 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1600 } else {
1601 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1602 $messagestring->pagetype = $block->instance->pagetypepattern;
1603 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1604 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1608 $message = get_string('deleteblockwarning', 'block', $messagestring);
1611 $PAGE->navbar->add($strdeletecheck);
1612 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1613 $PAGE->set_heading($site->fullname);
1614 echo $OUTPUT->header();
1615 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1616 $cancelurl = new moodle_url($deletepage->url);
1617 $yesbutton = new single_button($confirmurl, get_string('yes'));
1618 $nobutton = new single_button($cancelurl, get_string('no'));
1619 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1620 echo $OUTPUT->footer();
1621 // Make sure that nothing else happens after we have displayed this form.
1622 exit;
1623 } else {
1624 require_sesskey();
1626 blocks_delete_instance($block->instance);
1627 // bui_deleteid and bui_confirm should not be in the PAGE url.
1628 $this->page->ensure_param_not_in_url('bui_deleteid');
1629 $this->page->ensure_param_not_in_url('bui_confirm');
1630 return true;
1635 * Handle showing or hiding a block.
1636 * @return boolean true if anything was done. False if not.
1638 public function process_url_show_hide() {
1639 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1640 $newvisibility = 0;
1641 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1642 $newvisibility = 1;
1643 } else {
1644 return false;
1647 require_sesskey();
1649 $block = $this->page->blocks->find_instance($blockid);
1651 if (!$this->page->user_can_edit_blocks()) {
1652 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1653 } else if (!$block->instance_can_be_hidden()) {
1654 return false;
1657 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1659 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1660 $this->page->ensure_param_not_in_url('bui_hideid');
1661 $this->page->ensure_param_not_in_url('bui_showid');
1663 return true;
1667 * Convenience function to check whether a block is implementing a secondary nav class and return it
1668 * initialised to the calling function
1670 * @param block_base $block
1671 * @return \core\navigation\views\secondary
1673 protected function get_secondarynav(block_base $block): \core\navigation\views\secondary {
1674 $class = "core_block\\local\\views\\secondary";
1675 if (class_exists("block_{$block->name()}\\local\\views\\secondary")) {
1676 $class = "block_{$block->name()}\\local\\views\\secondary";
1678 $secondarynav = new $class($this->page);
1679 $secondarynav->initialise();
1680 return $secondarynav;
1684 * Handle showing/processing the submission from the block editing form.
1685 * @return boolean true if the form was submitted and the new config saved. Does not
1686 * return if the editing form was displayed. False otherwise.
1688 public function process_url_edit() {
1689 global $CFG, $DB, $PAGE, $OUTPUT;
1691 $blockid = optional_param('bui_editid', null, PARAM_INT);
1692 if (!$blockid) {
1693 return false;
1696 require_once($CFG->dirroot . '/blocks/edit_form.php');
1698 $block = $this->find_instance($blockid);
1700 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1701 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1704 $editpage = new moodle_page();
1705 $editpage->set_pagelayout('admin');
1706 $editpage->blocks->show_only_fake_blocks(true);
1707 $editpage->set_course($this->page->course);
1708 //$editpage->set_context($block->context);
1709 $editpage->set_context($this->page->context);
1710 $editpage->set_secondarynav($this->get_secondarynav($block));
1712 if ($this->page->cm) {
1713 $editpage->set_cm($this->page->cm);
1715 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1716 $editurlparams = $this->page->url->params();
1717 $editurlparams['bui_editid'] = $blockid;
1718 $editpage->set_url($editurlbase, $editurlparams);
1719 $editpage->set_block_actions_done();
1720 // At this point we are either going to redirect, or display the form, so
1721 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1722 $PAGE = $editpage;
1723 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1724 $output = $editpage->get_renderer('core');
1725 $OUTPUT = $output;
1727 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1728 if (is_readable($formfile)) {
1729 require_once($formfile);
1730 $classname = 'block_' . $block->name() . '_edit_form';
1731 if (!class_exists($classname)) {
1732 $classname = 'block_edit_form';
1734 } else {
1735 $classname = 'block_edit_form';
1738 $mform = new $classname($editpage->url, $block, $this->page);
1739 $mform->set_data($block->instance);
1741 if ($mform->is_cancelled()) {
1742 redirect($this->page->url);
1744 } else if ($data = $mform->get_data()) {
1745 $bi = new stdClass;
1746 $bi->id = $block->instance->id;
1748 // This may get overwritten by the special case handling below.
1749 $bi->pagetypepattern = $data->bui_pagetypepattern;
1750 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1751 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1752 $bi->subpagepattern = null;
1753 } else {
1754 $bi->subpagepattern = $data->bui_subpagepattern;
1757 $systemcontext = context_system::instance();
1758 $frontpagecontext = context_course::instance(SITEID);
1759 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1761 // Updating stickiness and contexts. See MDL-21375 for details.
1762 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1764 // Explicitly set the default context
1765 $bi->parentcontextid = $parentcontext->id;
1767 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1769 // The interface here is a special case because the pagetype pattern is
1770 // totally derived from the context menu. Here are the excpetions. MDL-30340
1772 switch ($data->bui_contexts) {
1773 case BUI_CONTEXTS_ENTIRE_SITE:
1774 // The user wants to show the block across the entire site
1775 $bi->parentcontextid = $systemcontext->id;
1776 $bi->showinsubcontexts = true;
1777 $bi->pagetypepattern = '*';
1778 break;
1779 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1780 // The user wants the block shown on the front page and all subcontexts
1781 $bi->parentcontextid = $frontpagecontext->id;
1782 $bi->showinsubcontexts = true;
1783 $bi->pagetypepattern = '*';
1784 break;
1785 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1786 // The user want to show the front page on the frontpage only
1787 $bi->parentcontextid = $frontpagecontext->id;
1788 $bi->showinsubcontexts = false;
1789 $bi->pagetypepattern = 'site-index';
1790 // This is the only relevant page type anyway but we'll set it explicitly just
1791 // in case the front page grows site-index-* subpages of its own later
1792 break;
1797 $bits = explode('-', $bi->pagetypepattern);
1798 // hacks for some contexts
1799 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1800 // For course context
1801 // is page type pattern is mod-*, change showinsubcontext to 1
1802 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1803 $bi->showinsubcontexts = 1;
1804 } else {
1805 $bi->showinsubcontexts = 0;
1807 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1808 // for user context
1809 // subpagepattern should be null
1810 if ($bits[0] == 'user' or $bits[0] == 'my') {
1811 // we don't need subpagepattern in usercontext
1812 $bi->subpagepattern = null;
1816 $bi->defaultregion = $data->bui_defaultregion;
1817 $bi->defaultweight = $data->bui_defaultweight;
1818 $bi->timemodified = time();
1819 $DB->update_record('block_instances', $bi);
1821 if (!empty($block->config)) {
1822 $config = clone($block->config);
1823 } else {
1824 $config = new stdClass;
1826 foreach ($data as $configfield => $value) {
1827 if (strpos($configfield, 'config_') !== 0) {
1828 continue;
1830 $field = substr($configfield, 7);
1831 $config->$field = $value;
1833 $block->instance_config_save($config);
1835 $bp = new stdClass;
1836 $bp->visible = $data->bui_visible;
1837 $bp->region = $data->bui_region;
1838 $bp->weight = $data->bui_weight;
1839 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1840 $data->bui_weight != $data->bui_defaultweight;
1842 if ($block->instance->blockpositionid && !$needbprecord) {
1843 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1845 } else if ($block->instance->blockpositionid && $needbprecord) {
1846 $bp->id = $block->instance->blockpositionid;
1847 $DB->update_record('block_positions', $bp);
1849 } else if ($needbprecord) {
1850 $bp->blockinstanceid = $block->instance->id;
1851 $bp->contextid = $this->page->context->id;
1852 $bp->pagetype = $this->page->pagetype;
1853 if ($this->page->subpage) {
1854 $bp->subpage = $this->page->subpage;
1855 } else {
1856 $bp->subpage = '';
1858 $DB->insert_record('block_positions', $bp);
1861 redirect($this->page->url);
1863 } else {
1864 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1865 $editpage->set_title($strheading);
1866 $editpage->set_heading($strheading);
1867 $bits = explode('-', $this->page->pagetype);
1868 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1869 // better navbar for tag pages
1870 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1871 $tag = core_tag_tag::get($this->page->subpage);
1872 // tag search page doesn't have subpageid
1873 if ($tag) {
1874 $editpage->navbar->add($tag->get_display_name(), $tag->get_view_url());
1877 $editpage->navbar->add($block->get_title());
1878 $editpage->navbar->add(get_string('configuration'));
1879 echo $output->header();
1880 echo $output->heading($strheading, 2);
1881 $mform->display();
1882 echo $output->footer();
1883 exit;
1888 * Handle showing/processing the submission from the block editing form.
1889 * @return boolean true if the form was submitted and the new config saved. Does not
1890 * return if the editing form was displayed. False otherwise.
1892 public function process_url_move() {
1893 global $CFG, $DB, $PAGE;
1895 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1896 if (!$blockid) {
1897 return false;
1900 require_sesskey();
1902 $block = $this->find_instance($blockid);
1904 if (!$this->page->user_can_edit_blocks()) {
1905 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1908 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1909 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1910 if (!$newregion || is_null($newweight)) {
1911 // Don't have a valid target position yet, must be just starting the move.
1912 $this->movingblock = $blockid;
1913 $this->page->ensure_param_not_in_url('bui_moveid');
1914 return false;
1917 if (!$this->is_known_region($newregion)) {
1918 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1921 // Move this block. This may involve moving other nearby blocks.
1922 $blocks = $this->birecordsbyregion[$newregion];
1924 $maxweight = self::MAX_WEIGHT;
1925 $minweight = -self::MAX_WEIGHT;
1927 // Initialise the used weights and spareweights array with the default values
1928 $spareweights = array();
1929 $usedweights = array();
1930 for ($i = $minweight; $i <= $maxweight; $i++) {
1931 $spareweights[$i] = $i;
1932 $usedweights[$i] = array();
1935 // Check each block and sort out where we have used weights
1936 foreach ($blocks as $bi) {
1937 if ($bi->weight > $maxweight) {
1938 // If this statement is true then the blocks weight is more than the
1939 // current maximum. To ensure that we can get the best block position
1940 // we will initialise elements within the usedweights and spareweights
1941 // arrays between the blocks weight (which will then be the new max) and
1942 // the current max
1943 $parseweight = $bi->weight;
1944 while (!array_key_exists($parseweight, $usedweights)) {
1945 $usedweights[$parseweight] = array();
1946 $spareweights[$parseweight] = $parseweight;
1947 $parseweight--;
1949 $maxweight = $bi->weight;
1950 } else if ($bi->weight < $minweight) {
1951 // As above except this time the blocks weight is LESS than the
1952 // the current minimum, so we will initialise the array from the
1953 // blocks weight (new minimum) to the current minimum
1954 $parseweight = $bi->weight;
1955 while (!array_key_exists($parseweight, $usedweights)) {
1956 $usedweights[$parseweight] = array();
1957 $spareweights[$parseweight] = $parseweight;
1958 $parseweight++;
1960 $minweight = $bi->weight;
1962 if ($bi->id != $block->instance->id) {
1963 unset($spareweights[$bi->weight]);
1964 $usedweights[$bi->weight][] = $bi->id;
1968 // First we find the nearest gap in the list of weights.
1969 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1970 $bestgap = null;
1971 foreach ($spareweights as $spareweight) {
1972 if (abs($newweight - $spareweight) < $bestdistance) {
1973 $bestdistance = abs($newweight - $spareweight);
1974 $bestgap = $spareweight;
1978 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1979 if (is_null($bestgap)) {
1980 $bestgap = self::MAX_WEIGHT + 1;
1981 while (!empty($usedweights[$bestgap])) {
1982 $bestgap++;
1986 // Now we know the gap we are aiming for, so move all the blocks along.
1987 if ($bestgap < $newweight) {
1988 $newweight = floor($newweight);
1989 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1990 if (array_key_exists($weight, $usedweights)) {
1991 foreach ($usedweights[$weight] as $biid) {
1992 $this->reposition_block($biid, $newregion, $weight - 1);
1996 $this->reposition_block($block->instance->id, $newregion, $newweight);
1997 } else {
1998 $newweight = ceil($newweight);
1999 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
2000 if (array_key_exists($weight, $usedweights)) {
2001 foreach ($usedweights[$weight] as $biid) {
2002 $this->reposition_block($biid, $newregion, $weight + 1);
2006 $this->reposition_block($block->instance->id, $newregion, $newweight);
2009 $this->page->ensure_param_not_in_url('bui_moveid');
2010 $this->page->ensure_param_not_in_url('bui_newregion');
2011 $this->page->ensure_param_not_in_url('bui_newweight');
2012 return true;
2016 * Turns the display of normal blocks either on or off.
2018 * @param bool $setting
2020 public function show_only_fake_blocks($setting = true) {
2021 $this->fakeblocksonly = $setting;
2025 /// Helper functions for working with block classes ============================
2028 * Call a class method (one that does not require a block instance) on a block class.
2030 * @param string $blockname the name of the block.
2031 * @param string $method the method name.
2032 * @param array $param parameters to pass to the method.
2033 * @return mixed whatever the method returns.
2035 function block_method_result($blockname, $method, $param = NULL) {
2036 if(!block_load_class($blockname)) {
2037 return NULL;
2039 return call_user_func(array('block_'.$blockname, $method), $param);
2043 * Returns a new instance of the specified block instance id.
2045 * @param int $blockinstanceid
2046 * @return block_base the requested block instance.
2048 function block_instance_by_id($blockinstanceid) {
2049 global $DB;
2051 $blockinstance = $DB->get_record('block_instances', ['id' => $blockinstanceid]);
2052 $instance = block_instance($blockinstance->blockname, $blockinstance);
2053 return $instance;
2057 * Creates a new instance of the specified block class.
2059 * @param string $blockname the name of the block.
2060 * @param $instance block_instances DB table row (optional).
2061 * @param moodle_page $page the page this block is appearing on.
2062 * @return block_base the requested block instance.
2064 function block_instance($blockname, $instance = NULL, $page = NULL) {
2065 if(!block_load_class($blockname)) {
2066 return false;
2068 $classname = 'block_'.$blockname;
2069 $retval = new $classname;
2070 if($instance !== NULL) {
2071 if (is_null($page)) {
2072 global $PAGE;
2073 $page = $PAGE;
2075 $retval->_load_instance($instance, $page);
2077 return $retval;
2081 * Load the block class for a particular type of block.
2083 * @param string $blockname the name of the block.
2084 * @return boolean success or failure.
2086 function block_load_class($blockname) {
2087 global $CFG;
2089 if(empty($blockname)) {
2090 return false;
2093 $classname = 'block_'.$blockname;
2095 if(class_exists($classname)) {
2096 return true;
2099 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
2101 if (file_exists($blockpath)) {
2102 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
2103 include_once($blockpath);
2104 }else{
2105 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
2106 return false;
2109 return class_exists($classname);
2113 * Given a specific page type, return all the page type patterns that might
2114 * match it.
2116 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2117 * @return array an array of all the page type patterns that might match this page type.
2119 function matching_page_type_patterns($pagetype) {
2120 $patterns = array($pagetype);
2121 $bits = explode('-', $pagetype);
2122 if (count($bits) == 3 && $bits[0] == 'mod') {
2123 if ($bits[2] == 'view') {
2124 $patterns[] = 'mod-*-view';
2125 } else if ($bits[2] == 'index') {
2126 $patterns[] = 'mod-*-index';
2129 while (count($bits) > 0) {
2130 $patterns[] = implode('-', $bits) . '-*';
2131 array_pop($bits);
2133 $patterns[] = '*';
2134 return $patterns;
2138 * Give an specific pattern, return all the page type patterns that would also match it.
2140 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
2141 * @return array of all the page type patterns matching.
2143 function matching_page_type_patterns_from_pattern($pattern) {
2144 $patterns = array($pattern);
2145 if ($pattern === '*') {
2146 return $patterns;
2149 // Only keep the part before the star because we will append -* to all the bits.
2150 $star = strpos($pattern, '-*');
2151 if ($star !== false) {
2152 $pattern = substr($pattern, 0, $star);
2155 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
2156 $patterns = array_unique($patterns);
2158 return $patterns;
2162 * Given a specific page type, parent context and currect context, return all the page type patterns
2163 * that might be used by this block.
2165 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2166 * @param stdClass $parentcontext Block's parent context
2167 * @param stdClass $currentcontext Current context of block
2168 * @return array an array of all the page type patterns that might match this page type.
2170 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
2171 global $CFG; // Required for includes bellow.
2173 $bits = explode('-', $pagetype);
2175 $core = core_component::get_core_subsystems();
2176 $plugins = core_component::get_plugin_types();
2178 //progressively strip pieces off the page type looking for a match
2179 $componentarray = null;
2180 for ($i = count($bits); $i > 0; $i--) {
2181 $possiblecomponentarray = array_slice($bits, 0, $i);
2182 $possiblecomponent = implode('', $possiblecomponentarray);
2184 // Check to see if the component is a core component
2185 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
2186 $libfile = $core[$possiblecomponent].'/lib.php';
2187 if (file_exists($libfile)) {
2188 require_once($libfile);
2189 $function = $possiblecomponent.'_page_type_list';
2190 if (function_exists($function)) {
2191 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2192 break;
2198 //check the plugin directory and look for a callback
2199 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
2201 //We've found a plugin type. Look for a plugin name by getting the next section of page type
2202 if (count($bits) > $i) {
2203 $pluginname = $bits[$i];
2204 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
2205 if (!empty($directory)){
2206 $libfile = $directory.'/lib.php';
2207 if (file_exists($libfile)) {
2208 require_once($libfile);
2209 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
2210 if (!function_exists($function)) {
2211 $function = $pluginname.'_page_type_list';
2213 if (function_exists($function)) {
2214 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2215 break;
2222 //we'll only get to here if we still don't have any patterns
2223 //the plugin type may have a callback
2224 $directory = $plugins[$possiblecomponent];
2225 $libfile = $directory.'/lib.php';
2226 if (file_exists($libfile)) {
2227 require_once($libfile);
2228 $function = $possiblecomponent.'_page_type_list';
2229 if (function_exists($function)) {
2230 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2231 break;
2238 if (empty($patterns)) {
2239 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
2242 // Ensure that the * pattern is always available if editing block 'at distance', so
2243 // we always can 'bring back' it to the original context. MDL-30340
2244 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
2245 // TODO: We could change the string here, showing its 'bring back' meaning
2246 $patterns['*'] = get_string('page-x', 'pagetype');
2249 return $patterns;
2253 * Generates a default page type list when a more appropriate callback cannot be decided upon.
2255 * @param string $pagetype
2256 * @param stdClass $parentcontext
2257 * @param stdClass $currentcontext
2258 * @return array
2260 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2261 // Generate page type patterns based on current page type if
2262 // callbacks haven't been defined
2263 $patterns = array($pagetype => $pagetype);
2264 $bits = explode('-', $pagetype);
2265 while (count($bits) > 0) {
2266 $pattern = implode('-', $bits) . '-*';
2267 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
2268 // guessing page type description
2269 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
2270 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
2271 } else {
2272 $patterns[$pattern] = $pattern;
2274 array_pop($bits);
2276 $patterns['*'] = get_string('page-x', 'pagetype');
2277 return $patterns;
2281 * Generates the page type list for the my moodle page
2283 * @param string $pagetype
2284 * @param stdClass $parentcontext
2285 * @param stdClass $currentcontext
2286 * @return array
2288 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2289 return array('my-index' => get_string('page-my-index', 'pagetype'));
2293 * Generates the page type list for a module by either locating and using the modules callback
2294 * or by generating a default list.
2296 * @param string $pagetype
2297 * @param stdClass $parentcontext
2298 * @param stdClass $currentcontext
2299 * @return array
2301 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2302 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
2303 if (empty($patterns)) {
2304 // if modules don't have callbacks
2305 // generate two default page type patterns for modules only
2306 $bits = explode('-', $pagetype);
2307 $patterns = array($pagetype => $pagetype);
2308 if ($bits[2] == 'view') {
2309 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
2310 } else if ($bits[2] == 'index') {
2311 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
2314 return $patterns;
2316 /// Functions update the blocks if required by the request parameters ==========
2319 * Return a {@link block_contents} representing the add a new block UI, if
2320 * this user is allowed to see it.
2322 * @return block_contents an appropriate block_contents, or null if the user
2323 * cannot add any blocks here.
2325 function block_add_block_ui($page, $output) {
2326 global $CFG, $OUTPUT;
2327 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
2328 return null;
2331 $bc = new block_contents();
2332 $bc->title = get_string('addblock');
2333 $bc->add_class('block_adminblock');
2334 $bc->attributes['data-block'] = 'adminblock';
2336 $missingblocks = $page->blocks->get_addable_blocks();
2337 if (empty($missingblocks)) {
2338 $bc->content = get_string('noblockstoaddhere');
2339 return $bc;
2342 $menu = array();
2343 foreach ($missingblocks as $block) {
2344 $menu[$block->name] = $block->title;
2347 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
2348 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
2349 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
2350 $bc->content = $OUTPUT->render($select);
2351 return $bc;
2355 * Actually delete from the database any blocks that are currently on this page,
2356 * but which should not be there according to blocks_name_allowed_in_format.
2358 * @todo Write/Fix this function. Currently returns immediately
2359 * @param $course
2361 function blocks_remove_inappropriate($course) {
2362 // TODO
2363 return;
2365 $blockmanager = blocks_get_by_page($page);
2367 if (empty($blockmanager)) {
2368 return;
2371 if (($pageformat = $page->pagetype) == NULL) {
2372 return;
2375 foreach($blockmanager as $region) {
2376 foreach($region as $instance) {
2377 $block = blocks_get_record($instance->blockid);
2378 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
2379 blocks_delete_instance($instance->instance);
2386 * Check that a given name is in a permittable format
2388 * @param string $name
2389 * @param string $pageformat
2390 * @return bool
2392 function blocks_name_allowed_in_format($name, $pageformat) {
2393 $accept = NULL;
2394 $maxdepth = -1;
2395 if (!$bi = block_instance($name)) {
2396 return false;
2399 $formats = $bi->applicable_formats();
2400 if (!$formats) {
2401 $formats = array();
2403 foreach ($formats as $format => $allowed) {
2404 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2405 $depth = substr_count($format, '-');
2406 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2407 $maxdepth = $depth;
2408 $accept = $allowed;
2411 if ($accept === NULL) {
2412 $accept = !empty($formats['all']);
2414 return $accept;
2418 * Delete a block, and associated data.
2420 * @param object $instance a row from the block_instances table
2421 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2422 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2424 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2425 global $DB;
2427 // Allow plugins to use this block before we completely delete it.
2428 if ($pluginsfunction = get_plugins_with_function('pre_block_delete')) {
2429 foreach ($pluginsfunction as $plugintype => $plugins) {
2430 foreach ($plugins as $pluginfunction) {
2431 $pluginfunction($instance);
2436 if ($block = block_instance($instance->blockname, $instance)) {
2437 $block->instance_delete();
2439 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2441 if (!$skipblockstables) {
2442 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2443 $DB->delete_records('block_instances', array('id' => $instance->id));
2444 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2449 * Delete multiple blocks at once.
2451 * @param array $instanceids A list of block instance ID.
2453 function blocks_delete_instances($instanceids) {
2454 global $DB;
2456 $limit = 1000;
2457 $count = count($instanceids);
2458 $chunks = [$instanceids];
2459 if ($count > $limit) {
2460 $chunks = array_chunk($instanceids, $limit);
2463 // Perform deletion for each chunk.
2464 foreach ($chunks as $chunk) {
2465 $instances = $DB->get_recordset_list('block_instances', 'id', $chunk);
2466 foreach ($instances as $instance) {
2467 blocks_delete_instance($instance, false, true);
2469 $instances->close();
2471 $DB->delete_records_list('block_positions', 'blockinstanceid', $chunk);
2472 $DB->delete_records_list('block_instances', 'id', $chunk);
2474 $preferences = array();
2475 foreach ($chunk as $instanceid) {
2476 $preferences[] = 'block' . $instanceid . 'hidden';
2477 $preferences[] = 'docked_block_instance_' . $instanceid;
2479 $DB->delete_records_list('user_preferences', 'name', $preferences);
2484 * Delete all the blocks that belong to a particular context.
2486 * @param int $contextid the context id.
2488 function blocks_delete_all_for_context($contextid) {
2489 global $DB;
2490 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2491 foreach ($instances as $instance) {
2492 blocks_delete_instance($instance, true);
2494 $instances->close();
2495 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2496 $DB->delete_records('block_positions', array('contextid' => $contextid));
2500 * Set a block to be visible or hidden on a particular page.
2502 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2503 * block_positions table as return by block_manager.
2504 * @param moodle_page $page the back to set the visibility with respect to.
2505 * @param integer $newvisibility 1 for visible, 0 for hidden.
2507 function blocks_set_visibility($instance, $page, $newvisibility) {
2508 global $DB;
2509 if (!empty($instance->blockpositionid)) {
2510 // Already have local information on this page.
2511 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2512 return;
2515 // Create a new block_positions record.
2516 $bp = new stdClass;
2517 $bp->blockinstanceid = $instance->id;
2518 $bp->contextid = $page->context->id;
2519 $bp->pagetype = $page->pagetype;
2520 if ($page->subpage) {
2521 $bp->subpage = $page->subpage;
2523 $bp->visible = $newvisibility;
2524 $bp->region = $instance->defaultregion;
2525 $bp->weight = $instance->defaultweight;
2526 $DB->insert_record('block_positions', $bp);
2530 * Get the block record for a particular blockid - that is, a particular type os block.
2532 * @param $int blockid block type id. If null, an array of all block types is returned.
2533 * @param bool $notusedanymore No longer used.
2534 * @return array|object row from block table, or all rows.
2536 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2537 global $PAGE;
2538 $blocks = $PAGE->blocks->get_installed_blocks();
2539 if ($blockid === NULL) {
2540 return $blocks;
2541 } else if (isset($blocks[$blockid])) {
2542 return $blocks[$blockid];
2543 } else {
2544 return false;
2549 * Find a given block by its blockid within a provide array
2551 * @param int $blockid
2552 * @param array $blocksarray
2553 * @return bool|object Instance if found else false
2555 function blocks_find_block($blockid, $blocksarray) {
2556 if (empty($blocksarray)) {
2557 return false;
2559 foreach($blocksarray as $blockgroup) {
2560 if (empty($blockgroup)) {
2561 continue;
2563 foreach($blockgroup as $instance) {
2564 if($instance->blockid == $blockid) {
2565 return $instance;
2569 return false;
2572 // Functions for programatically adding default blocks to pages ================
2575 * Parse a list of default blocks. See config-dist for a description of the format.
2577 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2578 * @return array the parsed list of default blocks
2580 function blocks_parse_default_blocks_list($blocksstr) {
2581 $blocks = array();
2582 $bits = explode(':', $blocksstr);
2583 if (!empty($bits)) {
2584 $leftbits = trim(array_shift($bits));
2585 if ($leftbits != '') {
2586 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2589 if (!empty($bits)) {
2590 $rightbits = trim(array_shift($bits));
2591 if ($rightbits != '') {
2592 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2595 return $blocks;
2599 * @return array the blocks that should be added to the site course by default.
2601 function blocks_get_default_site_course_blocks() {
2602 global $CFG;
2604 if (isset($CFG->defaultblocks_site)) {
2605 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2606 } else {
2607 return array(
2608 BLOCK_POS_LEFT => array(),
2609 BLOCK_POS_RIGHT => array()
2615 * Add the default blocks to a course.
2617 * @param object $course a course object.
2619 function blocks_add_default_course_blocks($course) {
2620 global $CFG;
2622 if (isset($CFG->defaultblocks_override)) {
2623 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2625 } else if ($course->id == SITEID) {
2626 $blocknames = blocks_get_default_site_course_blocks();
2628 } else if (isset($CFG->{'defaultblocks_' . $course->format})) {
2629 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2631 } else {
2632 require_once($CFG->dirroot. '/course/lib.php');
2633 $blocknames = course_get_format($course)->get_default_blocks();
2637 if ($course->id == SITEID) {
2638 $pagetypepattern = 'site-index';
2639 } else {
2640 $pagetypepattern = 'course-view-*';
2642 $page = new moodle_page();
2643 $page->set_course($course);
2644 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2648 * Add the default system-context blocks. E.g. the admin tree.
2650 function blocks_add_default_system_blocks() {
2651 global $DB;
2653 $page = new moodle_page();
2654 $page->set_context(context_system::instance());
2655 // We don't add blocks required by the theme, they will be auto-created.
2656 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2658 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2659 $subpagepattern = $defaultmypage->id;
2660 } else {
2661 $subpagepattern = null;
2664 if ($defaultmycoursespage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__courses', 'private' => 0))) {
2665 $mycoursesubpagepattern = $defaultmycoursespage->id;
2666 } else {
2667 $mycoursesubpagepattern = null;
2670 $page->blocks->add_blocks([
2671 BLOCK_POS_RIGHT => [
2672 'private_files',
2673 'badges',
2675 'content' => [
2676 'timeline',
2677 'calendar_month',
2679 'my-index',
2680 $subpagepattern
2683 $page->blocks->add_blocks([
2684 'content' => [
2685 'myoverview'
2687 'my-index',
2688 $mycoursesubpagepattern