Merge branch 'MDL-60302-master' of git://github.com/jleyva/moodle
[moodle.git] / lib / blocklib.php
blob62b8bf5ec346859a587508db2b35488bc40ba29a
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->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
227 blocks_name_allowed_in_format($block->name, $pageformat) &&
228 $bi->user_can_addto($this->page)) {
229 $block->title = $bi->get_title();
230 $this->addableblocks[$block->name] = $block;
234 core_collator::asort_objects_by_property($this->addableblocks, 'title');
235 return $this->addableblocks;
239 * Given a block name, find out of any of them are currently present in the page
241 * @param string $blockname - the basic name of a block (eg "navigation")
242 * @return boolean - is there one of these blocks in the current page?
244 public function is_block_present($blockname) {
245 if (empty($this->blockinstances)) {
246 return false;
249 $requiredbythemeblocks = $this->get_required_by_theme_block_types();
250 foreach ($this->blockinstances as $region) {
251 foreach ($region as $instance) {
252 if (empty($instance->instance->blockname)) {
253 continue;
255 if ($instance->instance->blockname == $blockname) {
256 if ($instance->instance->requiredbytheme) {
257 if (!in_array($blockname, $requiredbythemeblocks)) {
258 continue;
261 return true;
265 return false;
269 * Find out if a block type is known by the system
271 * @param string $blockname the name of the type of block.
272 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
273 * @return boolean true if this block in installed.
275 public function is_known_block_type($blockname, $includeinvisible = false) {
276 $blocks = $this->get_installed_blocks();
277 foreach ($blocks as $block) {
278 if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
279 return true;
282 return false;
286 * Find out if a region exists on a page
288 * @param string $region a region name
289 * @return boolean true if this region exists on this page.
291 public function is_known_region($region) {
292 if (empty($region)) {
293 return false;
295 return array_key_exists($region, $this->regions);
299 * Get an array of all blocks within a given region
301 * @param string $region a block region that exists on this page.
302 * @return array of block instances.
304 public function get_blocks_for_region($region) {
305 $this->check_is_loaded();
306 $this->ensure_instances_exist($region);
307 return $this->blockinstances[$region];
311 * Returns an array of block content objects that exist in a region
313 * @param string $region a block region that exists on this page.
314 * @return array of block block_contents objects for all the blocks in a region.
316 public function get_content_for_region($region, $output) {
317 $this->check_is_loaded();
318 $this->ensure_content_created($region, $output);
319 return $this->visibleblockcontent[$region];
323 * Returns an array of block content objects for all the existings regions
325 * @param renderer_base $output the rendered to use
326 * @return array of block block_contents objects for all the blocks in all regions.
327 * @since Moodle 3.3
329 public function get_content_for_all_regions($output) {
330 $contents = array();
331 $this->check_is_loaded();
333 foreach ($this->regions as $region => $val) {
334 $this->ensure_content_created($region, $output);
335 $contents[$region] = $this->visibleblockcontent[$region];
337 return $contents;
341 * Helper method used by get_content_for_region.
342 * @param string $region region name
343 * @param float $weight weight. May be fractional, since you may want to move a block
344 * between ones with weight 2 and 3, say ($weight would be 2.5).
345 * @return string URL for moving block $this->movingblock to this position.
347 protected function get_move_target_url($region, $weight) {
348 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
349 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
353 * Determine whether a region contains anything. (Either any real blocks, or
354 * the add new block UI.)
356 * (You may wonder why the $output parameter is required. Unfortunately,
357 * because of the way that blocks work, the only reliable way to find out
358 * if a block will be visible is to get the content for output, and to
359 * get the content, you need a renderer. Fortunately, this is not a
360 * performance problem, because we cache the output that is generated, and
361 * in almost every case where we call region_has_content, we are about to
362 * output the blocks anyway, so we are not doing wasted effort.)
364 * @param string $region a block region that exists on this page.
365 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
366 * @return boolean Whether there is anything in this region.
368 public function region_has_content($region, $output) {
370 if (!$this->is_known_region($region)) {
371 return false;
373 $this->check_is_loaded();
374 $this->ensure_content_created($region, $output);
375 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
376 // Mark Nielsen's patch - part 1
377 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
378 // If editing is on, we need all the block regions visible, for the
379 // move blocks UI.
380 return true;
382 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
386 * Get an array of all of the installed blocks.
388 * @return array contents of the block table.
390 public function get_installed_blocks() {
391 global $DB;
392 if (is_null($this->allblocks)) {
393 $this->allblocks = $DB->get_records('block');
395 return $this->allblocks;
399 * @return array names of block types that must exist on every page with this theme.
401 public function get_required_by_theme_block_types() {
402 $requiredbythemeblocks = false;
403 if (isset($this->page->theme->requiredblocks)) {
404 $requiredbythemeblocks = $this->page->theme->requiredblocks;
407 if ($requiredbythemeblocks === false) {
408 return array('navigation', 'settings');
409 } else if ($requiredbythemeblocks === '') {
410 return array();
411 } else if (is_string($requiredbythemeblocks)) {
412 return explode(',', $requiredbythemeblocks);
413 } else {
414 return $requiredbythemeblocks;
419 * Make this block type undeletable and unaddable.
421 * @param mixed $blockidorname string or int
423 public static function protect_block($blockidorname) {
424 global $DB;
426 $syscontext = context_system::instance();
428 require_capability('moodle/site:config', $syscontext);
430 $block = false;
431 if (is_int($blockidorname)) {
432 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
433 } else {
434 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
436 $undeletableblocktypes = self::get_undeletable_block_types();
437 if (!in_array($block->name, $undeletableblocktypes)) {
438 $undeletableblocktypes[] = $block->name;
439 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
440 add_to_config_log('block_protect', "0", "1", $block->name);
445 * Make this block type deletable and addable.
447 * @param mixed $blockidorname string or int
449 public static function unprotect_block($blockidorname) {
450 global $DB;
452 $syscontext = context_system::instance();
454 require_capability('moodle/site:config', $syscontext);
456 $block = false;
457 if (is_int($blockidorname)) {
458 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
459 } else {
460 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
462 $undeletableblocktypes = self::get_undeletable_block_types();
463 if (in_array($block->name, $undeletableblocktypes)) {
464 $undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name));
465 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
466 add_to_config_log('block_protect', "1", "0", $block->name);
472 * Get the list of "protected" blocks via admin block manager ui.
474 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
476 public static function get_undeletable_block_types() {
477 global $CFG;
478 $undeletableblocks = false;
479 if (isset($CFG->undeletableblocktypes)) {
480 $undeletableblocks = $CFG->undeletableblocktypes;
483 if (empty($undeletableblocks)) {
484 return array();
485 } else if (is_string($undeletableblocks)) {
486 return explode(',', $undeletableblocks);
487 } else {
488 return $undeletableblocks;
492 /// Setter methods =============================================================
495 * Add a region to a page
497 * @param string $region add a named region where blocks may appear on the current page.
498 * This is an internal name, like 'side-pre', not a string to display in the UI.
499 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
501 public function add_region($region, $custom = true) {
502 global $SESSION;
503 $this->check_not_yet_loaded();
504 if ($custom) {
505 if (array_key_exists($region, $this->regions)) {
506 // This here is EXACTLY why we should not be adding block regions into a page. It should
507 // ALWAYS be done in a theme layout.
508 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
510 // We need to register this custom region against the page type being used.
511 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
512 $type = $this->page->pagetype;
513 if (!isset($SESSION->custom_block_regions)) {
514 $SESSION->custom_block_regions = array($type => array($region));
515 } else if (!isset($SESSION->custom_block_regions[$type])) {
516 $SESSION->custom_block_regions[$type] = array($region);
517 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
518 $SESSION->custom_block_regions[$type][] = $region;
521 $this->regions[$region] = 1;
525 * Add an array of regions
526 * @see add_region()
528 * @param array $regions this utility method calls add_region for each array element.
530 public function add_regions($regions, $custom = true) {
531 foreach ($regions as $region) {
532 $this->add_region($region, $custom);
537 * Finds custom block regions associated with a page type and registers them with this block manager.
539 * @param string $pagetype
541 public function add_custom_regions_for_pagetype($pagetype) {
542 global $SESSION;
543 if (isset($SESSION->custom_block_regions[$pagetype])) {
544 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
545 $this->add_region($customregion, false);
551 * Set the default region for new blocks on the page
553 * @param string $defaultregion the internal names of the region where new
554 * blocks should be added by default, and where any blocks from an
555 * unrecognised region are shown.
557 public function set_default_region($defaultregion) {
558 $this->check_not_yet_loaded();
559 if ($defaultregion) {
560 $this->check_region_is_known($defaultregion);
562 $this->defaultregion = $defaultregion;
566 * Add something that looks like a block, but which isn't an actual block_instance,
567 * to this page.
569 * @param block_contents $bc the content of the block-like thing.
570 * @param string $region a block region that exists on this page.
572 public function add_fake_block($bc, $region) {
573 $this->page->initialise_theme_and_output();
574 if (!$this->is_known_region($region)) {
575 $region = $this->get_default_region();
577 if (array_key_exists($region, $this->visibleblockcontent)) {
578 throw new coding_exception('block_manager has already prepared the blocks in region ' .
579 $region . 'for output. It is too late to add a fake block.');
581 if (!isset($bc->attributes['data-block'])) {
582 $bc->attributes['data-block'] = '_fake';
584 $bc->attributes['class'] .= ' block_fake';
585 $this->extracontent[$region][] = $bc;
589 * Checks to see whether all of the blocks within the given region are docked
591 * @see region_uses_dock
592 * @param string $region
593 * @return bool True if all of the blocks within that region are docked
595 public function region_completely_docked($region, $output) {
596 global $CFG;
597 // If theme doesn't allow docking or allowblockstodock is not set, then return.
598 if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
599 return false;
602 // Do not dock the region when the user attemps to move a block.
603 if ($this->movingblock) {
604 return false;
607 // Block regions should not be docked during editing when all the blocks are hidden.
608 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
609 return false;
612 $this->check_is_loaded();
613 $this->ensure_content_created($region, $output);
614 if (!$this->region_has_content($region, $output)) {
615 // If the region has no content then nothing is docked at all of course.
616 return false;
618 foreach ($this->visibleblockcontent[$region] as $instance) {
619 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
620 return false;
623 return true;
627 * Checks to see whether any of the blocks within the given regions are docked
629 * @see region_completely_docked
630 * @param array|string $regions array of regions (or single region)
631 * @return bool True if any of the blocks within that region are docked
633 public function region_uses_dock($regions, $output) {
634 if (!$this->page->theme->enable_dock) {
635 return false;
637 $this->check_is_loaded();
638 foreach((array)$regions as $region) {
639 $this->ensure_content_created($region, $output);
640 foreach($this->visibleblockcontent[$region] as $instance) {
641 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
642 return true;
646 return false;
649 /// Actions ====================================================================
652 * This method actually loads the blocks for our page from the database.
654 * @param boolean|null $includeinvisible
655 * null (default) - load hidden blocks if $this->page->user_is_editing();
656 * true - load hidden blocks.
657 * false - don't load hidden blocks.
659 public function load_blocks($includeinvisible = null) {
660 global $DB, $CFG;
662 if (!is_null($this->birecordsbyregion)) {
663 // Already done.
664 return;
667 if ($CFG->version < 2009050619) {
668 // Upgrade/install not complete. Don't try too show any blocks.
669 $this->birecordsbyregion = array();
670 return;
673 // Ensure we have been initialised.
674 if (is_null($this->defaultregion)) {
675 $this->page->initialise_theme_and_output();
676 // If there are still no block regions, then there are no blocks on this page.
677 if (empty($this->regions)) {
678 $this->birecordsbyregion = array();
679 return;
683 // Check if we need to load normal blocks
684 if ($this->fakeblocksonly) {
685 $this->birecordsbyregion = $this->prepare_per_region_arrays();
686 return;
689 // Exclude auto created blocks if they are not undeletable in this theme.
690 $requiredbytheme = $this->get_required_by_theme_block_types();
691 $requiredbythemecheck = '';
692 $requiredbythemeparams = array();
693 $requiredbythemenotparams = array();
694 if (!empty($requiredbytheme)) {
695 list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED, 'requiredbytheme');
696 list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED,
697 'notrequiredbytheme', false);
698 $requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
699 ' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
700 } else {
701 $requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
704 if (is_null($includeinvisible)) {
705 $includeinvisible = $this->page->user_is_editing();
707 if ($includeinvisible) {
708 $visiblecheck = '';
709 } else {
710 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
713 $context = $this->page->context;
714 $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
715 $parentcontextparams = array();
716 $parentcontextids = $context->get_parent_context_ids();
717 if ($parentcontextids) {
718 list($parentcontexttest, $parentcontextparams) =
719 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
720 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
723 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
724 list($pagetypepatterntest, $pagetypepatternparams) =
725 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
727 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
728 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
730 $systemcontext = context_system::instance();
731 list($bpcontext, $bpcontextidparams) = $DB->get_in_or_equal(array($context->id, $systemcontext->id),
732 SQL_PARAMS_NAMED, 'bpcontextid');
733 $params = array(
734 'contextlevel' => CONTEXT_BLOCK,
735 'subpage1' => $this->page->subpage,
736 'subpage2' => $this->page->subpage,
737 'contextid1' => $context->id,
738 'contextid2' => $context->id,
739 'contextid3' => $systemcontext->id,
740 'pagetype' => $this->page->pagetype,
742 if ($this->page->subpage === '') {
743 $params['subpage1'] = '';
744 $params['subpage2'] = '';
746 $sql = "SELECT
747 bi.id,
748 bp.id AS blockpositionid,
749 bi.blockname,
750 bi.parentcontextid,
751 bi.showinsubcontexts,
752 bi.pagetypepattern,
753 bi.requiredbytheme,
754 bi.subpagepattern,
755 bi.defaultregion,
756 bi.defaultweight,
757 COALESCE(bp.visible, 1) AS visible,
758 COALESCE(bp.region, bi.defaultregion) AS region,
759 COALESCE(bp.weight, bi.defaultweight) AS weight,
760 bi.configdata
761 $ccselect
763 FROM {block_instances} bi
764 JOIN {block} b ON bi.blockname = b.name
765 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
766 AND bp.contextid $bpcontext
767 AND bp.pagetype = :pagetype
768 AND bp.subpage = :subpage1
769 $ccjoin
771 WHERE
772 $contexttest
773 AND bi.pagetypepattern $pagetypepatterntest
774 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
775 $visiblecheck
776 AND b.visible = 1
777 $requiredbythemecheck
779 ORDER BY
780 COALESCE(bp.region, bi.defaultregion),
781 COALESCE(bp.weight, bi.defaultweight),
782 bi.id";
784 $allparams = $params + $parentcontextparams + $pagetypepatternparams + $requiredbythemeparams;
785 $allparams = $allparams + $requiredbythemenotparams + $bpcontextidparams;
786 $blockinstances = $DB->get_recordset_sql($sql, $allparams);
788 $this->birecordsbyregion = $this->prepare_per_region_arrays();
789 $unknown = array();
790 foreach ($blockinstances as $bi) {
791 context_helper::preload_from_record($bi);
792 if ($this->is_known_region($bi->region)) {
793 $this->birecordsbyregion[$bi->region][] = $bi;
794 } else {
795 $unknown[] = $bi;
799 // Pages don't necessarily have a defaultregion. The one time this can
800 // happen is when there are no theme block regions, but the script itself
801 // has a block region in the main content area.
802 if (!empty($this->defaultregion)) {
803 $this->birecordsbyregion[$this->defaultregion] =
804 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
809 * Add a block to the current page, or related pages. The block is added to
810 * context $this->page->contextid. If $pagetypepattern $subpagepattern
812 * @param string $blockname The type of block to add.
813 * @param string $region the block region on this page to add the block to.
814 * @param integer $weight determines the order where this block appears in the region.
815 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
816 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
817 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
819 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
820 global $DB;
821 // Allow invisible blocks because this is used when adding default page blocks, which
822 // might include invisible ones if the user makes some default blocks invisible
823 $this->check_known_block_type($blockname, true);
824 $this->check_region_is_known($region);
826 if (empty($pagetypepattern)) {
827 $pagetypepattern = $this->page->pagetype;
830 $blockinstance = new stdClass;
831 $blockinstance->blockname = $blockname;
832 $blockinstance->parentcontextid = $this->page->context->id;
833 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
834 $blockinstance->pagetypepattern = $pagetypepattern;
835 $blockinstance->subpagepattern = $subpagepattern;
836 $blockinstance->defaultregion = $region;
837 $blockinstance->defaultweight = $weight;
838 $blockinstance->configdata = '';
839 $blockinstance->timecreated = time();
840 $blockinstance->timemodified = $blockinstance->timecreated;
841 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
843 // Ensure the block context is created.
844 context_block::instance($blockinstance->id);
846 // If the new instance was created, allow it to do additional setup
847 if ($block = block_instance($blockname, $blockinstance)) {
848 $block->instance_create();
852 public function add_block_at_end_of_default_region($blockname) {
853 if (empty($this->birecordsbyregion)) {
854 // No blocks or block regions exist yet.
855 return;
857 $defaulregion = $this->get_default_region();
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);
1252 if (!array_key_exists($region, $this->visibleblockcontent)) {
1253 $contents = array();
1254 if (array_key_exists($region, $this->extracontent)) {
1255 $contents = $this->extracontent[$region];
1257 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1258 if (($region == $this->defaultregion) && (!isset($this->page->theme->addblockposition) ||
1259 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_DEFAULT)) {
1260 $addblockui = block_add_block_ui($this->page, $output);
1261 if ($addblockui) {
1262 $contents[] = $addblockui;
1265 $this->visibleblockcontent[$region] = $contents;
1269 /// Process actions from the URL ===============================================
1272 * Get the appropriate list of editing icons for a block. This is used
1273 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1275 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1276 * @return an array in the format for {@link block_contents::$controls}
1278 public function edit_controls($block) {
1279 global $CFG;
1281 $controls = array();
1282 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1283 $blocktitle = $block->title;
1284 if (empty($blocktitle)) {
1285 $blocktitle = $block->arialabel;
1288 if ($this->page->user_can_edit_blocks()) {
1289 // Move icon.
1290 $str = new lang_string('moveblock', 'block', $blocktitle);
1291 $controls[] = new action_menu_link_primary(
1292 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1293 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1294 $str,
1295 array('class' => 'editing_move')
1300 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1301 // Edit config icon - always show - needed for positioning UI.
1302 $str = new lang_string('configureblock', 'block', $blocktitle);
1303 $controls[] = new action_menu_link_secondary(
1304 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1305 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1306 $str,
1307 array('class' => 'editing_edit')
1312 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1313 // Show/hide icon.
1314 if ($block->instance->visible) {
1315 $str = new lang_string('hideblock', 'block', $blocktitle);
1316 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1317 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1318 $attributes = array('class' => 'editing_hide');
1319 } else {
1320 $str = new lang_string('showblock', 'block', $blocktitle);
1321 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1322 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1323 $attributes = array('class' => 'editing_show');
1325 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1328 // Assign roles.
1329 if (get_assignable_roles($block->context, ROLENAME_SHORT)) {
1330 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id,
1331 'returnurl' => $this->page->url->out_as_local_url()));
1332 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1333 $controls[] = new action_menu_link_secondary(
1334 $rolesurl,
1335 new pix_icon('i/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1336 $str, array('class' => 'editing_assignroles')
1340 // Permissions.
1341 if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) {
1342 $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id,
1343 'returnurl' => $this->page->url->out_as_local_url()));
1344 $str = get_string('permissions', 'role');
1345 $controls[] = new action_menu_link_secondary(
1346 $rolesurl,
1347 new pix_icon('i/permissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1348 $str, array('class' => 'editing_permissions')
1352 // Change permissions.
1353 if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) {
1354 $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id,
1355 'returnurl' => $this->page->url->out_as_local_url()));
1356 $str = get_string('checkpermissions', 'role');
1357 $controls[] = new action_menu_link_secondary(
1358 $rolesurl,
1359 new pix_icon('i/checkpermissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1360 $str, array('class' => 'editing_checkroles')
1364 if ($this->user_can_delete_block($block)) {
1365 // Delete icon.
1366 $str = new lang_string('deleteblock', 'block', $blocktitle);
1367 $controls[] = new action_menu_link_secondary(
1368 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1369 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1370 $str,
1371 array('class' => 'editing_delete')
1375 return $controls;
1379 * @param block_base $block a block that appears on this page.
1380 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1382 protected function user_can_delete_block($block) {
1383 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1384 $block->user_can_addto($this->page) &&
1385 !in_array($block->instance->blockname, self::get_undeletable_block_types()) &&
1386 !in_array($block->instance->blockname, $this->get_required_by_theme_block_types());
1390 * Process any block actions that were specified in the URL.
1392 * @return boolean true if anything was done. False if not.
1394 public function process_url_actions() {
1395 if (!$this->page->user_is_editing()) {
1396 return false;
1398 return $this->process_url_add() || $this->process_url_delete() ||
1399 $this->process_url_show_hide() || $this->process_url_edit() ||
1400 $this->process_url_move();
1404 * Handle adding a block.
1405 * @return boolean true if anything was done. False if not.
1407 public function process_url_add() {
1408 global $CFG, $PAGE, $OUTPUT;
1410 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1411 if ($blocktype === null) {
1412 return false;
1415 require_sesskey();
1417 if (!$this->page->user_can_edit_blocks()) {
1418 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1421 $addableblocks = $this->get_addable_blocks();
1423 if ($blocktype === '') {
1424 // Display add block selection.
1425 $addpage = new moodle_page();
1426 $addpage->set_pagelayout('admin');
1427 $addpage->blocks->show_only_fake_blocks(true);
1428 $addpage->set_course($this->page->course);
1429 $addpage->set_context($this->page->context);
1430 if ($this->page->cm) {
1431 $addpage->set_cm($this->page->cm);
1434 $addpagebase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1435 $addpageparams = $this->page->url->params();
1436 $addpage->set_url($addpagebase, $addpageparams);
1437 $addpage->set_block_actions_done();
1438 // At this point we are going to display the block selector, overwrite global $PAGE ready for this.
1439 $PAGE = $addpage;
1440 // Some functions use $OUTPUT so we need to replace that too.
1441 $OUTPUT = $addpage->get_renderer('core');
1443 $site = get_site();
1444 $straddblock = get_string('addblock');
1446 $PAGE->navbar->add($straddblock);
1447 $PAGE->set_title($straddblock);
1448 $PAGE->set_heading($site->fullname);
1449 echo $OUTPUT->header();
1450 echo $OUTPUT->heading($straddblock);
1452 if (!$addableblocks) {
1453 echo $OUTPUT->box(get_string('noblockstoaddhere'));
1454 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('back')), 'm-x-3 m-b-1');
1455 } else {
1456 $url = new moodle_url($addpage->url, array('sesskey' => sesskey()));
1457 echo $OUTPUT->render_from_template('core/add_block_body',
1458 ['blocks' => array_values($addableblocks),
1459 'url' => '?' . $url->get_query_string(false)]);
1460 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('cancel')), 'm-x-3 m-b-1');
1463 echo $OUTPUT->footer();
1464 // Make sure that nothing else happens after we have displayed this form.
1465 exit;
1468 if (!array_key_exists($blocktype, $addableblocks)) {
1469 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1472 $this->add_block_at_end_of_default_region($blocktype);
1474 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1475 $this->page->ensure_param_not_in_url('bui_addblock');
1477 return true;
1481 * Handle deleting a block.
1482 * @return boolean true if anything was done. False if not.
1484 public function process_url_delete() {
1485 global $CFG, $PAGE, $OUTPUT;
1487 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1488 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1490 if (!$blockid) {
1491 return false;
1494 require_sesskey();
1495 $block = $this->page->blocks->find_instance($blockid);
1496 if (!$this->user_can_delete_block($block)) {
1497 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1500 if (!$confirmdelete) {
1501 $deletepage = new moodle_page();
1502 $deletepage->set_pagelayout('admin');
1503 $deletepage->blocks->show_only_fake_blocks(true);
1504 $deletepage->set_course($this->page->course);
1505 $deletepage->set_context($this->page->context);
1506 if ($this->page->cm) {
1507 $deletepage->set_cm($this->page->cm);
1510 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1511 $deleteurlparams = $this->page->url->params();
1512 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1513 $deletepage->set_block_actions_done();
1514 // At this point we are either going to redirect, or display the form, so
1515 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1516 $PAGE = $deletepage;
1517 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1518 $output = $deletepage->get_renderer('core');
1519 $OUTPUT = $output;
1521 $site = get_site();
1522 $blocktitle = $block->get_title();
1523 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1524 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1526 // If the block is being shown in sub contexts display a warning.
1527 if ($block->instance->showinsubcontexts == 1) {
1528 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1529 $systemcontext = context_system::instance();
1530 $messagestring = new stdClass();
1531 $messagestring->location = $parentcontext->get_context_name();
1533 // Checking for blocks that may have visibility on the front page and pages added on that.
1534 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1535 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1536 } else {
1537 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1538 $messagestring->pagetype = $block->instance->pagetypepattern;
1539 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1540 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1544 $message = get_string('deleteblockwarning', 'block', $messagestring);
1547 $PAGE->navbar->add($strdeletecheck);
1548 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1549 $PAGE->set_heading($site->fullname);
1550 echo $OUTPUT->header();
1551 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1552 $cancelurl = new moodle_url($deletepage->url);
1553 $yesbutton = new single_button($confirmurl, get_string('yes'));
1554 $nobutton = new single_button($cancelurl, get_string('no'));
1555 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1556 echo $OUTPUT->footer();
1557 // Make sure that nothing else happens after we have displayed this form.
1558 exit;
1559 } else {
1560 blocks_delete_instance($block->instance);
1561 // bui_deleteid and bui_confirm should not be in the PAGE url.
1562 $this->page->ensure_param_not_in_url('bui_deleteid');
1563 $this->page->ensure_param_not_in_url('bui_confirm');
1564 return true;
1569 * Handle showing or hiding a block.
1570 * @return boolean true if anything was done. False if not.
1572 public function process_url_show_hide() {
1573 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1574 $newvisibility = 0;
1575 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1576 $newvisibility = 1;
1577 } else {
1578 return false;
1581 require_sesskey();
1583 $block = $this->page->blocks->find_instance($blockid);
1585 if (!$this->page->user_can_edit_blocks()) {
1586 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1587 } else if (!$block->instance_can_be_hidden()) {
1588 return false;
1591 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1593 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1594 $this->page->ensure_param_not_in_url('bui_hideid');
1595 $this->page->ensure_param_not_in_url('bui_showid');
1597 return true;
1601 * Handle showing/processing the submission from the block editing form.
1602 * @return boolean true if the form was submitted and the new config saved. Does not
1603 * return if the editing form was displayed. False otherwise.
1605 public function process_url_edit() {
1606 global $CFG, $DB, $PAGE, $OUTPUT;
1608 $blockid = optional_param('bui_editid', null, PARAM_INT);
1609 if (!$blockid) {
1610 return false;
1613 require_sesskey();
1614 require_once($CFG->dirroot . '/blocks/edit_form.php');
1616 $block = $this->find_instance($blockid);
1618 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1619 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1622 $editpage = new moodle_page();
1623 $editpage->set_pagelayout('admin');
1624 $editpage->blocks->show_only_fake_blocks(true);
1625 $editpage->set_course($this->page->course);
1626 //$editpage->set_context($block->context);
1627 $editpage->set_context($this->page->context);
1628 if ($this->page->cm) {
1629 $editpage->set_cm($this->page->cm);
1631 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1632 $editurlparams = $this->page->url->params();
1633 $editurlparams['bui_editid'] = $blockid;
1634 $editpage->set_url($editurlbase, $editurlparams);
1635 $editpage->set_block_actions_done();
1636 // At this point we are either going to redirect, or display the form, so
1637 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1638 $PAGE = $editpage;
1639 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1640 $output = $editpage->get_renderer('core');
1641 $OUTPUT = $output;
1643 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1644 if (is_readable($formfile)) {
1645 require_once($formfile);
1646 $classname = 'block_' . $block->name() . '_edit_form';
1647 if (!class_exists($classname)) {
1648 $classname = 'block_edit_form';
1650 } else {
1651 $classname = 'block_edit_form';
1654 $mform = new $classname($editpage->url, $block, $this->page);
1655 $mform->set_data($block->instance);
1657 if ($mform->is_cancelled()) {
1658 redirect($this->page->url);
1660 } else if ($data = $mform->get_data()) {
1661 $bi = new stdClass;
1662 $bi->id = $block->instance->id;
1664 // This may get overwritten by the special case handling below.
1665 $bi->pagetypepattern = $data->bui_pagetypepattern;
1666 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1667 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1668 $bi->subpagepattern = null;
1669 } else {
1670 $bi->subpagepattern = $data->bui_subpagepattern;
1673 $systemcontext = context_system::instance();
1674 $frontpagecontext = context_course::instance(SITEID);
1675 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1677 // Updating stickiness and contexts. See MDL-21375 for details.
1678 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1680 // Explicitly set the default context
1681 $bi->parentcontextid = $parentcontext->id;
1683 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1685 // The interface here is a special case because the pagetype pattern is
1686 // totally derived from the context menu. Here are the excpetions. MDL-30340
1688 switch ($data->bui_contexts) {
1689 case BUI_CONTEXTS_ENTIRE_SITE:
1690 // The user wants to show the block across the entire site
1691 $bi->parentcontextid = $systemcontext->id;
1692 $bi->showinsubcontexts = true;
1693 $bi->pagetypepattern = '*';
1694 break;
1695 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1696 // The user wants the block shown on the front page and all subcontexts
1697 $bi->parentcontextid = $frontpagecontext->id;
1698 $bi->showinsubcontexts = true;
1699 $bi->pagetypepattern = '*';
1700 break;
1701 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1702 // The user want to show the front page on the frontpage only
1703 $bi->parentcontextid = $frontpagecontext->id;
1704 $bi->showinsubcontexts = false;
1705 $bi->pagetypepattern = 'site-index';
1706 // This is the only relevant page type anyway but we'll set it explicitly just
1707 // in case the front page grows site-index-* subpages of its own later
1708 break;
1713 $bits = explode('-', $bi->pagetypepattern);
1714 // hacks for some contexts
1715 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1716 // For course context
1717 // is page type pattern is mod-*, change showinsubcontext to 1
1718 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1719 $bi->showinsubcontexts = 1;
1720 } else {
1721 $bi->showinsubcontexts = 0;
1723 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1724 // for user context
1725 // subpagepattern should be null
1726 if ($bits[0] == 'user' or $bits[0] == 'my') {
1727 // we don't need subpagepattern in usercontext
1728 $bi->subpagepattern = null;
1732 $bi->defaultregion = $data->bui_defaultregion;
1733 $bi->defaultweight = $data->bui_defaultweight;
1734 $bi->timemodified = time();
1735 $DB->update_record('block_instances', $bi);
1737 if (!empty($block->config)) {
1738 $config = clone($block->config);
1739 } else {
1740 $config = new stdClass;
1742 foreach ($data as $configfield => $value) {
1743 if (strpos($configfield, 'config_') !== 0) {
1744 continue;
1746 $field = substr($configfield, 7);
1747 $config->$field = $value;
1749 $block->instance_config_save($config);
1751 $bp = new stdClass;
1752 $bp->visible = $data->bui_visible;
1753 $bp->region = $data->bui_region;
1754 $bp->weight = $data->bui_weight;
1755 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1756 $data->bui_weight != $data->bui_defaultweight;
1758 if ($block->instance->blockpositionid && !$needbprecord) {
1759 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1761 } else if ($block->instance->blockpositionid && $needbprecord) {
1762 $bp->id = $block->instance->blockpositionid;
1763 $DB->update_record('block_positions', $bp);
1765 } else if ($needbprecord) {
1766 $bp->blockinstanceid = $block->instance->id;
1767 $bp->contextid = $this->page->context->id;
1768 $bp->pagetype = $this->page->pagetype;
1769 if ($this->page->subpage) {
1770 $bp->subpage = $this->page->subpage;
1771 } else {
1772 $bp->subpage = '';
1774 $DB->insert_record('block_positions', $bp);
1777 redirect($this->page->url);
1779 } else {
1780 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1781 $editpage->set_title($strheading);
1782 $editpage->set_heading($strheading);
1783 $bits = explode('-', $this->page->pagetype);
1784 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1785 // better navbar for tag pages
1786 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1787 $tag = core_tag_tag::get($this->page->subpage);
1788 // tag search page doesn't have subpageid
1789 if ($tag) {
1790 $editpage->navbar->add($tag->get_display_name(), $tag->get_view_url());
1793 $editpage->navbar->add($block->get_title());
1794 $editpage->navbar->add(get_string('configuration'));
1795 echo $output->header();
1796 echo $output->heading($strheading, 2);
1797 $mform->display();
1798 echo $output->footer();
1799 exit;
1804 * Handle showing/processing the submission from the block editing form.
1805 * @return boolean true if the form was submitted and the new config saved. Does not
1806 * return if the editing form was displayed. False otherwise.
1808 public function process_url_move() {
1809 global $CFG, $DB, $PAGE;
1811 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1812 if (!$blockid) {
1813 return false;
1816 require_sesskey();
1818 $block = $this->find_instance($blockid);
1820 if (!$this->page->user_can_edit_blocks()) {
1821 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1824 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1825 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1826 if (!$newregion || is_null($newweight)) {
1827 // Don't have a valid target position yet, must be just starting the move.
1828 $this->movingblock = $blockid;
1829 $this->page->ensure_param_not_in_url('bui_moveid');
1830 return false;
1833 if (!$this->is_known_region($newregion)) {
1834 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1837 // Move this block. This may involve moving other nearby blocks.
1838 $blocks = $this->birecordsbyregion[$newregion];
1840 $maxweight = self::MAX_WEIGHT;
1841 $minweight = -self::MAX_WEIGHT;
1843 // Initialise the used weights and spareweights array with the default values
1844 $spareweights = array();
1845 $usedweights = array();
1846 for ($i = $minweight; $i <= $maxweight; $i++) {
1847 $spareweights[$i] = $i;
1848 $usedweights[$i] = array();
1851 // Check each block and sort out where we have used weights
1852 foreach ($blocks as $bi) {
1853 if ($bi->weight > $maxweight) {
1854 // If this statement is true then the blocks weight is more than the
1855 // current maximum. To ensure that we can get the best block position
1856 // we will initialise elements within the usedweights and spareweights
1857 // arrays between the blocks weight (which will then be the new max) and
1858 // the current max
1859 $parseweight = $bi->weight;
1860 while (!array_key_exists($parseweight, $usedweights)) {
1861 $usedweights[$parseweight] = array();
1862 $spareweights[$parseweight] = $parseweight;
1863 $parseweight--;
1865 $maxweight = $bi->weight;
1866 } else if ($bi->weight < $minweight) {
1867 // As above except this time the blocks weight is LESS than the
1868 // the current minimum, so we will initialise the array from the
1869 // blocks weight (new minimum) to the current minimum
1870 $parseweight = $bi->weight;
1871 while (!array_key_exists($parseweight, $usedweights)) {
1872 $usedweights[$parseweight] = array();
1873 $spareweights[$parseweight] = $parseweight;
1874 $parseweight++;
1876 $minweight = $bi->weight;
1878 if ($bi->id != $block->instance->id) {
1879 unset($spareweights[$bi->weight]);
1880 $usedweights[$bi->weight][] = $bi->id;
1884 // First we find the nearest gap in the list of weights.
1885 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1886 $bestgap = null;
1887 foreach ($spareweights as $spareweight) {
1888 if (abs($newweight - $spareweight) < $bestdistance) {
1889 $bestdistance = abs($newweight - $spareweight);
1890 $bestgap = $spareweight;
1894 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1895 if (is_null($bestgap)) {
1896 $bestgap = self::MAX_WEIGHT + 1;
1897 while (!empty($usedweights[$bestgap])) {
1898 $bestgap++;
1902 // Now we know the gap we are aiming for, so move all the blocks along.
1903 if ($bestgap < $newweight) {
1904 $newweight = floor($newweight);
1905 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1906 if (array_key_exists($weight, $usedweights)) {
1907 foreach ($usedweights[$weight] as $biid) {
1908 $this->reposition_block($biid, $newregion, $weight - 1);
1912 $this->reposition_block($block->instance->id, $newregion, $newweight);
1913 } else {
1914 $newweight = ceil($newweight);
1915 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1916 if (array_key_exists($weight, $usedweights)) {
1917 foreach ($usedweights[$weight] as $biid) {
1918 $this->reposition_block($biid, $newregion, $weight + 1);
1922 $this->reposition_block($block->instance->id, $newregion, $newweight);
1925 $this->page->ensure_param_not_in_url('bui_moveid');
1926 $this->page->ensure_param_not_in_url('bui_newregion');
1927 $this->page->ensure_param_not_in_url('bui_newweight');
1928 return true;
1932 * Turns the display of normal blocks either on or off.
1934 * @param bool $setting
1936 public function show_only_fake_blocks($setting = true) {
1937 $this->fakeblocksonly = $setting;
1941 /// Helper functions for working with block classes ============================
1944 * Call a class method (one that does not require a block instance) on a block class.
1946 * @param string $blockname the name of the block.
1947 * @param string $method the method name.
1948 * @param array $param parameters to pass to the method.
1949 * @return mixed whatever the method returns.
1951 function block_method_result($blockname, $method, $param = NULL) {
1952 if(!block_load_class($blockname)) {
1953 return NULL;
1955 return call_user_func(array('block_'.$blockname, $method), $param);
1959 * Creates a new instance of the specified block class.
1961 * @param string $blockname the name of the block.
1962 * @param $instance block_instances DB table row (optional).
1963 * @param moodle_page $page the page this block is appearing on.
1964 * @return block_base the requested block instance.
1966 function block_instance($blockname, $instance = NULL, $page = NULL) {
1967 if(!block_load_class($blockname)) {
1968 return false;
1970 $classname = 'block_'.$blockname;
1971 $retval = new $classname;
1972 if($instance !== NULL) {
1973 if (is_null($page)) {
1974 global $PAGE;
1975 $page = $PAGE;
1977 $retval->_load_instance($instance, $page);
1979 return $retval;
1983 * Load the block class for a particular type of block.
1985 * @param string $blockname the name of the block.
1986 * @return boolean success or failure.
1988 function block_load_class($blockname) {
1989 global $CFG;
1991 if(empty($blockname)) {
1992 return false;
1995 $classname = 'block_'.$blockname;
1997 if(class_exists($classname)) {
1998 return true;
2001 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
2003 if (file_exists($blockpath)) {
2004 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
2005 include_once($blockpath);
2006 }else{
2007 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
2008 return false;
2011 return class_exists($classname);
2015 * Given a specific page type, return all the page type patterns that might
2016 * match it.
2018 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2019 * @return array an array of all the page type patterns that might match this page type.
2021 function matching_page_type_patterns($pagetype) {
2022 $patterns = array($pagetype);
2023 $bits = explode('-', $pagetype);
2024 if (count($bits) == 3 && $bits[0] == 'mod') {
2025 if ($bits[2] == 'view') {
2026 $patterns[] = 'mod-*-view';
2027 } else if ($bits[2] == 'index') {
2028 $patterns[] = 'mod-*-index';
2031 while (count($bits) > 0) {
2032 $patterns[] = implode('-', $bits) . '-*';
2033 array_pop($bits);
2035 $patterns[] = '*';
2036 return $patterns;
2040 * Give an specific pattern, return all the page type patterns that would also match it.
2042 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
2043 * @return array of all the page type patterns matching.
2045 function matching_page_type_patterns_from_pattern($pattern) {
2046 $patterns = array($pattern);
2047 if ($pattern === '*') {
2048 return $patterns;
2051 // Only keep the part before the star because we will append -* to all the bits.
2052 $star = strpos($pattern, '-*');
2053 if ($star !== false) {
2054 $pattern = substr($pattern, 0, $star);
2057 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
2058 $patterns = array_unique($patterns);
2060 return $patterns;
2064 * Given a specific page type, parent context and currect context, return all the page type patterns
2065 * that might be used by this block.
2067 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2068 * @param stdClass $parentcontext Block's parent context
2069 * @param stdClass $currentcontext Current context of block
2070 * @return array an array of all the page type patterns that might match this page type.
2072 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
2073 global $CFG; // Required for includes bellow.
2075 $bits = explode('-', $pagetype);
2077 $core = core_component::get_core_subsystems();
2078 $plugins = core_component::get_plugin_types();
2080 //progressively strip pieces off the page type looking for a match
2081 $componentarray = null;
2082 for ($i = count($bits); $i > 0; $i--) {
2083 $possiblecomponentarray = array_slice($bits, 0, $i);
2084 $possiblecomponent = implode('', $possiblecomponentarray);
2086 // Check to see if the component is a core component
2087 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
2088 $libfile = $core[$possiblecomponent].'/lib.php';
2089 if (file_exists($libfile)) {
2090 require_once($libfile);
2091 $function = $possiblecomponent.'_page_type_list';
2092 if (function_exists($function)) {
2093 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2094 break;
2100 //check the plugin directory and look for a callback
2101 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
2103 //We've found a plugin type. Look for a plugin name by getting the next section of page type
2104 if (count($bits) > $i) {
2105 $pluginname = $bits[$i];
2106 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
2107 if (!empty($directory)){
2108 $libfile = $directory.'/lib.php';
2109 if (file_exists($libfile)) {
2110 require_once($libfile);
2111 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
2112 if (!function_exists($function)) {
2113 $function = $pluginname.'_page_type_list';
2115 if (function_exists($function)) {
2116 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2117 break;
2124 //we'll only get to here if we still don't have any patterns
2125 //the plugin type may have a callback
2126 $directory = $plugins[$possiblecomponent];
2127 $libfile = $directory.'/lib.php';
2128 if (file_exists($libfile)) {
2129 require_once($libfile);
2130 $function = $possiblecomponent.'_page_type_list';
2131 if (function_exists($function)) {
2132 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2133 break;
2140 if (empty($patterns)) {
2141 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
2144 // Ensure that the * pattern is always available if editing block 'at distance', so
2145 // we always can 'bring back' it to the original context. MDL-30340
2146 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
2147 // TODO: We could change the string here, showing its 'bring back' meaning
2148 $patterns['*'] = get_string('page-x', 'pagetype');
2151 return $patterns;
2155 * Generates a default page type list when a more appropriate callback cannot be decided upon.
2157 * @param string $pagetype
2158 * @param stdClass $parentcontext
2159 * @param stdClass $currentcontext
2160 * @return array
2162 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2163 // Generate page type patterns based on current page type if
2164 // callbacks haven't been defined
2165 $patterns = array($pagetype => $pagetype);
2166 $bits = explode('-', $pagetype);
2167 while (count($bits) > 0) {
2168 $pattern = implode('-', $bits) . '-*';
2169 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
2170 // guessing page type description
2171 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
2172 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
2173 } else {
2174 $patterns[$pattern] = $pattern;
2176 array_pop($bits);
2178 $patterns['*'] = get_string('page-x', 'pagetype');
2179 return $patterns;
2183 * Generates the page type list for the my moodle page
2185 * @param string $pagetype
2186 * @param stdClass $parentcontext
2187 * @param stdClass $currentcontext
2188 * @return array
2190 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2191 return array('my-index' => get_string('page-my-index', 'pagetype'));
2195 * Generates the page type list for a module by either locating and using the modules callback
2196 * or by generating a default list.
2198 * @param string $pagetype
2199 * @param stdClass $parentcontext
2200 * @param stdClass $currentcontext
2201 * @return array
2203 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2204 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
2205 if (empty($patterns)) {
2206 // if modules don't have callbacks
2207 // generate two default page type patterns for modules only
2208 $bits = explode('-', $pagetype);
2209 $patterns = array($pagetype => $pagetype);
2210 if ($bits[2] == 'view') {
2211 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
2212 } else if ($bits[2] == 'index') {
2213 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
2216 return $patterns;
2218 /// Functions update the blocks if required by the request parameters ==========
2221 * Return a {@link block_contents} representing the add a new block UI, if
2222 * this user is allowed to see it.
2224 * @return block_contents an appropriate block_contents, or null if the user
2225 * cannot add any blocks here.
2227 function block_add_block_ui($page, $output) {
2228 global $CFG, $OUTPUT;
2229 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
2230 return null;
2233 $bc = new block_contents();
2234 $bc->title = get_string('addblock');
2235 $bc->add_class('block_adminblock');
2236 $bc->attributes['data-block'] = 'adminblock';
2238 $missingblocks = $page->blocks->get_addable_blocks();
2239 if (empty($missingblocks)) {
2240 $bc->content = get_string('noblockstoaddhere');
2241 return $bc;
2244 $menu = array();
2245 foreach ($missingblocks as $block) {
2246 $menu[$block->name] = $block->title;
2249 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
2250 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
2251 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
2252 $bc->content = $OUTPUT->render($select);
2253 return $bc;
2257 * Actually delete from the database any blocks that are currently on this page,
2258 * but which should not be there according to blocks_name_allowed_in_format.
2260 * @todo Write/Fix this function. Currently returns immediately
2261 * @param $course
2263 function blocks_remove_inappropriate($course) {
2264 // TODO
2265 return;
2267 $blockmanager = blocks_get_by_page($page);
2269 if (empty($blockmanager)) {
2270 return;
2273 if (($pageformat = $page->pagetype) == NULL) {
2274 return;
2277 foreach($blockmanager as $region) {
2278 foreach($region as $instance) {
2279 $block = blocks_get_record($instance->blockid);
2280 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
2281 blocks_delete_instance($instance->instance);
2288 * Check that a given name is in a permittable format
2290 * @param string $name
2291 * @param string $pageformat
2292 * @return bool
2294 function blocks_name_allowed_in_format($name, $pageformat) {
2295 $accept = NULL;
2296 $maxdepth = -1;
2297 if (!$bi = block_instance($name)) {
2298 return false;
2301 $formats = $bi->applicable_formats();
2302 if (!$formats) {
2303 $formats = array();
2305 foreach ($formats as $format => $allowed) {
2306 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2307 $depth = substr_count($format, '-');
2308 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2309 $maxdepth = $depth;
2310 $accept = $allowed;
2313 if ($accept === NULL) {
2314 $accept = !empty($formats['all']);
2316 return $accept;
2320 * Delete a block, and associated data.
2322 * @param object $instance a row from the block_instances table
2323 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2324 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2326 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2327 global $DB;
2329 // Allow plugins to use this block before we completely delete it.
2330 if ($pluginsfunction = get_plugins_with_function('pre_block_delete')) {
2331 foreach ($pluginsfunction as $plugintype => $plugins) {
2332 foreach ($plugins as $pluginfunction) {
2333 $pluginfunction($instance);
2338 if ($block = block_instance($instance->blockname, $instance)) {
2339 $block->instance_delete();
2341 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2343 if (!$skipblockstables) {
2344 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2345 $DB->delete_records('block_instances', array('id' => $instance->id));
2346 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2351 * Delete multiple blocks at once.
2353 * @param array $instanceids A list of block instance ID.
2355 function blocks_delete_instances($instanceids) {
2356 global $DB;
2358 $limit = 1000;
2359 $count = count($instanceids);
2360 $chunks = [$instanceids];
2361 if ($count > $limit) {
2362 $chunks = array_chunk($instanceids, $limit);
2365 // Perform deletion for each chunk.
2366 foreach ($chunks as $chunk) {
2367 $instances = $DB->get_recordset_list('block_instances', 'id', $chunk);
2368 foreach ($instances as $instance) {
2369 blocks_delete_instance($instance, false, true);
2371 $instances->close();
2373 $DB->delete_records_list('block_positions', 'blockinstanceid', $chunk);
2374 $DB->delete_records_list('block_instances', 'id', $chunk);
2376 $preferences = array();
2377 foreach ($chunk as $instanceid) {
2378 $preferences[] = 'block' . $instanceid . 'hidden';
2379 $preferences[] = 'docked_block_instance_' . $instanceid;
2381 $DB->delete_records_list('user_preferences', 'name', $preferences);
2386 * Delete all the blocks that belong to a particular context.
2388 * @param int $contextid the context id.
2390 function blocks_delete_all_for_context($contextid) {
2391 global $DB;
2392 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2393 foreach ($instances as $instance) {
2394 blocks_delete_instance($instance, true);
2396 $instances->close();
2397 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2398 $DB->delete_records('block_positions', array('contextid' => $contextid));
2402 * Set a block to be visible or hidden on a particular page.
2404 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2405 * block_positions table as return by block_manager.
2406 * @param moodle_page $page the back to set the visibility with respect to.
2407 * @param integer $newvisibility 1 for visible, 0 for hidden.
2409 function blocks_set_visibility($instance, $page, $newvisibility) {
2410 global $DB;
2411 if (!empty($instance->blockpositionid)) {
2412 // Already have local information on this page.
2413 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2414 return;
2417 // Create a new block_positions record.
2418 $bp = new stdClass;
2419 $bp->blockinstanceid = $instance->id;
2420 $bp->contextid = $page->context->id;
2421 $bp->pagetype = $page->pagetype;
2422 if ($page->subpage) {
2423 $bp->subpage = $page->subpage;
2425 $bp->visible = $newvisibility;
2426 $bp->region = $instance->defaultregion;
2427 $bp->weight = $instance->defaultweight;
2428 $DB->insert_record('block_positions', $bp);
2432 * Get the block record for a particular blockid - that is, a particular type os block.
2434 * @param $int blockid block type id. If null, an array of all block types is returned.
2435 * @param bool $notusedanymore No longer used.
2436 * @return array|object row from block table, or all rows.
2438 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2439 global $PAGE;
2440 $blocks = $PAGE->blocks->get_installed_blocks();
2441 if ($blockid === NULL) {
2442 return $blocks;
2443 } else if (isset($blocks[$blockid])) {
2444 return $blocks[$blockid];
2445 } else {
2446 return false;
2451 * Find a given block by its blockid within a provide array
2453 * @param int $blockid
2454 * @param array $blocksarray
2455 * @return bool|object Instance if found else false
2457 function blocks_find_block($blockid, $blocksarray) {
2458 if (empty($blocksarray)) {
2459 return false;
2461 foreach($blocksarray as $blockgroup) {
2462 if (empty($blockgroup)) {
2463 continue;
2465 foreach($blockgroup as $instance) {
2466 if($instance->blockid == $blockid) {
2467 return $instance;
2471 return false;
2474 // Functions for programatically adding default blocks to pages ================
2477 * Parse a list of default blocks. See config-dist for a description of the format.
2479 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2480 * @return array the parsed list of default blocks
2482 function blocks_parse_default_blocks_list($blocksstr) {
2483 $blocks = array();
2484 $bits = explode(':', $blocksstr);
2485 if (!empty($bits)) {
2486 $leftbits = trim(array_shift($bits));
2487 if ($leftbits != '') {
2488 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2491 if (!empty($bits)) {
2492 $rightbits = trim(array_shift($bits));
2493 if ($rightbits != '') {
2494 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2497 return $blocks;
2501 * @return array the blocks that should be added to the site course by default.
2503 function blocks_get_default_site_course_blocks() {
2504 global $CFG;
2506 if (isset($CFG->defaultblocks_site)) {
2507 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2508 } else {
2509 return array(
2510 BLOCK_POS_LEFT => array(),
2511 BLOCK_POS_RIGHT => array()
2517 * Add the default blocks to a course.
2519 * @param object $course a course object.
2521 function blocks_add_default_course_blocks($course) {
2522 global $CFG;
2524 if (isset($CFG->defaultblocks_override)) {
2525 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2527 } else if ($course->id == SITEID) {
2528 $blocknames = blocks_get_default_site_course_blocks();
2530 } else if (isset($CFG->{'defaultblocks_' . $course->format})) {
2531 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2533 } else {
2534 require_once($CFG->dirroot. '/course/lib.php');
2535 $blocknames = course_get_format($course)->get_default_blocks();
2539 if ($course->id == SITEID) {
2540 $pagetypepattern = 'site-index';
2541 } else {
2542 $pagetypepattern = 'course-view-*';
2544 $page = new moodle_page();
2545 $page->set_course($course);
2546 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2550 * Add the default system-context blocks. E.g. the admin tree.
2552 function blocks_add_default_system_blocks() {
2553 global $DB;
2555 $page = new moodle_page();
2556 $page->set_context(context_system::instance());
2557 // We don't add blocks required by the theme, they will be auto-created.
2558 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2560 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2561 $subpagepattern = $defaultmypage->id;
2562 } else {
2563 $subpagepattern = null;
2566 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2567 $newcontent = array('lp', 'myoverview');
2568 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);