MDL-49144 blocks: Add behat test to ensury sanity of block title
[moodle.git] / lib / blocklib.php
blob630d59224e10bd8084d8a5fe56724446a52b61e2
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 /**
46 * Exception thrown when someone tried to do something with a block that does
47 * not exist on a page.
49 * @copyright 2009 Tim Hunt
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 * @since Moodle 2.0
53 class block_not_on_page_exception extends moodle_exception {
54 /**
55 * Constructor
56 * @param int $instanceid the block instance id of the block that was looked for.
57 * @param object $page the current page.
59 public function __construct($instanceid, $page) {
60 $a = new stdClass;
61 $a->instanceid = $instanceid;
62 $a->url = $page->url->out();
63 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
67 /**
68 * This class keeps track of the block that should appear on a moodle_page.
70 * The page to work with as passed to the constructor.
72 * @copyright 2009 Tim Hunt
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
74 * @since Moodle 2.0
76 class block_manager {
77 /**
78 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
79 * although other weights are valid.
81 const MAX_WEIGHT = 10;
83 /// Field declarations =========================================================
85 /**
86 * the moodle_page we are managing blocks for.
87 * @var moodle_page
89 protected $page;
91 /** @var array region name => 1.*/
92 protected $regions = array();
94 /** @var string the region where new blocks are added.*/
95 protected $defaultregion = null;
97 /** @var array will be $DB->get_records('blocks') */
98 protected $allblocks = null;
101 * @var array blocks that this user can add to this page. Will be a subset
102 * of $allblocks, but with array keys block->name. Access this via the
103 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
105 protected $addableblocks = null;
108 * Will be an array region-name => array(db rows loaded in load_blocks);
109 * @var array
111 protected $birecordsbyregion = null;
114 * array region-name => array(block objects); populated as necessary by
115 * the ensure_instances_exist method.
116 * @var array
118 protected $blockinstances = array();
121 * array region-name => array(block_contents objects) what actually needs to
122 * be displayed in each region.
123 * @var array
125 protected $visibleblockcontent = array();
128 * array region-name => array(block_contents objects) extra block-like things
129 * to be displayed in each region, before the real blocks.
130 * @var array
132 protected $extracontent = array();
135 * Used by the block move id, to track whether a block is currently being moved.
137 * When you click on the move icon of a block, first the page needs to reload with
138 * extra UI for choosing a new position for a particular block. In that situation
139 * this field holds the id of the block being moved.
141 * @var integer|null
143 protected $movingblock = null;
146 * Show only fake blocks
148 protected $fakeblocksonly = false;
150 /// Constructor ================================================================
153 * Constructor.
154 * @param object $page the moodle_page object object we are managing the blocks for,
155 * or a reasonable faxilimily. (See the comment at the top of this class
156 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
158 public function __construct($page) {
159 $this->page = $page;
162 /// Getter methods =============================================================
165 * Get an array of all region names on this page where a block may appear
167 * @return array the internal names of the regions on this page where block may appear.
169 public function get_regions() {
170 if (is_null($this->defaultregion)) {
171 $this->page->initialise_theme_and_output();
173 return array_keys($this->regions);
177 * Get the region name of the region blocks are added to by default
179 * @return string the internal names of the region where new blocks are added
180 * by default, and where any blocks from an unrecognised region are shown.
181 * (Imagine that blocks were added with one theme selected, then you switched
182 * to a theme with different block positions.)
184 public function get_default_region() {
185 $this->page->initialise_theme_and_output();
186 return $this->defaultregion;
190 * The list of block types that may be added to this page.
192 * @return array block name => record from block table.
194 public function get_addable_blocks() {
195 $this->check_is_loaded();
197 if (!is_null($this->addableblocks)) {
198 return $this->addableblocks;
201 // Lazy load.
202 $this->addableblocks = array();
204 $allblocks = blocks_get_record();
205 if (empty($allblocks)) {
206 return $this->addableblocks;
209 $unaddableblocks = self::get_undeletable_block_types();
210 $pageformat = $this->page->pagetype;
211 foreach($allblocks as $block) {
212 if (!$bi = block_instance($block->name)) {
213 continue;
215 if ($block->visible && !in_array($block->name, $unaddableblocks) &&
216 ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
217 blocks_name_allowed_in_format($block->name, $pageformat) &&
218 $bi->user_can_addto($this->page)) {
219 $this->addableblocks[$block->name] = $block;
223 return $this->addableblocks;
227 * Given a block name, find out of any of them are currently present in the page
229 * @param string $blockname - the basic name of a block (eg "navigation")
230 * @return boolean - is there one of these blocks in the current page?
232 public function is_block_present($blockname) {
233 if (empty($this->blockinstances)) {
234 return false;
237 foreach ($this->blockinstances as $region) {
238 foreach ($region as $instance) {
239 if (empty($instance->instance->blockname)) {
240 continue;
242 if ($instance->instance->blockname == $blockname) {
243 return true;
247 return false;
251 * Find out if a block type is known by the system
253 * @param string $blockname the name of the type of block.
254 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
255 * @return boolean true if this block in installed.
257 public function is_known_block_type($blockname, $includeinvisible = false) {
258 $blocks = $this->get_installed_blocks();
259 foreach ($blocks as $block) {
260 if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
261 return true;
264 return false;
268 * Find out if a region exists on a page
270 * @param string $region a region name
271 * @return boolean true if this region exists on this page.
273 public function is_known_region($region) {
274 return array_key_exists($region, $this->regions);
278 * Get an array of all blocks within a given region
280 * @param string $region a block region that exists on this page.
281 * @return array of block instances.
283 public function get_blocks_for_region($region) {
284 $this->check_is_loaded();
285 $this->ensure_instances_exist($region);
286 return $this->blockinstances[$region];
290 * Returns an array of block content objects that exist in a region
292 * @param string $region a block region that exists on this page.
293 * @return array of block block_contents objects for all the blocks in a region.
295 public function get_content_for_region($region, $output) {
296 $this->check_is_loaded();
297 $this->ensure_content_created($region, $output);
298 return $this->visibleblockcontent[$region];
302 * Helper method used by get_content_for_region.
303 * @param string $region region name
304 * @param float $weight weight. May be fractional, since you may want to move a block
305 * between ones with weight 2 and 3, say ($weight would be 2.5).
306 * @return string URL for moving block $this->movingblock to this position.
308 protected function get_move_target_url($region, $weight) {
309 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
310 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
314 * Determine whether a region contains anything. (Either any real blocks, or
315 * the add new block UI.)
317 * (You may wonder why the $output parameter is required. Unfortunately,
318 * because of the way that blocks work, the only reliable way to find out
319 * if a block will be visible is to get the content for output, and to
320 * get the content, you need a renderer. Fortunately, this is not a
321 * performance problem, because we cache the output that is generated, and
322 * in almost every case where we call region_has_content, we are about to
323 * output the blocks anyway, so we are not doing wasted effort.)
325 * @param string $region a block region that exists on this page.
326 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
327 * @return boolean Whether there is anything in this region.
329 public function region_has_content($region, $output) {
331 if (!$this->is_known_region($region)) {
332 return false;
334 $this->check_is_loaded();
335 $this->ensure_content_created($region, $output);
336 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
337 // Mark Nielsen's patch - part 1
338 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
339 // If editing is on, we need all the block regions visible, for the
340 // move blocks UI.
341 return true;
343 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
347 * Get an array of all of the installed blocks.
349 * @return array contents of the block table.
351 public function get_installed_blocks() {
352 global $DB;
353 if (is_null($this->allblocks)) {
354 $this->allblocks = $DB->get_records('block');
356 return $this->allblocks;
360 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
362 public static function get_undeletable_block_types() {
363 global $CFG;
365 if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
366 return array('navigation','settings');
367 } else if (is_string($CFG->undeletableblocktypes)) {
368 return explode(',', $CFG->undeletableblocktypes);
369 } else {
370 return $CFG->undeletableblocktypes;
374 /// Setter methods =============================================================
377 * Add a region to a page
379 * @param string $region add a named region where blocks may appear on the current page.
380 * This is an internal name, like 'side-pre', not a string to display in the UI.
381 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
383 public function add_region($region, $custom = true) {
384 global $SESSION;
385 $this->check_not_yet_loaded();
386 if ($custom) {
387 if (array_key_exists($region, $this->regions)) {
388 // This here is EXACTLY why we should not be adding block regions into a page. It should
389 // ALWAYS be done in a theme layout.
390 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
392 // We need to register this custom region against the page type being used.
393 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
394 $type = $this->page->pagetype;
395 if (!isset($SESSION->custom_block_regions)) {
396 $SESSION->custom_block_regions = array($type => array($region));
397 } else if (!isset($SESSION->custom_block_regions[$type])) {
398 $SESSION->custom_block_regions[$type] = array($region);
399 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
400 $SESSION->custom_block_regions[$type][] = $region;
403 $this->regions[$region] = 1;
407 * Add an array of regions
408 * @see add_region()
410 * @param array $regions this utility method calls add_region for each array element.
412 public function add_regions($regions, $custom = true) {
413 foreach ($regions as $region) {
414 $this->add_region($region, $custom);
419 * Finds custom block regions associated with a page type and registers them with this block manager.
421 * @param string $pagetype
423 public function add_custom_regions_for_pagetype($pagetype) {
424 global $SESSION;
425 if (isset($SESSION->custom_block_regions[$pagetype])) {
426 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
427 $this->add_region($customregion, false);
433 * Set the default region for new blocks on the page
435 * @param string $defaultregion the internal names of the region where new
436 * blocks should be added by default, and where any blocks from an
437 * unrecognised region are shown.
439 public function set_default_region($defaultregion) {
440 $this->check_not_yet_loaded();
441 if ($defaultregion) {
442 $this->check_region_is_known($defaultregion);
444 $this->defaultregion = $defaultregion;
448 * Add something that looks like a block, but which isn't an actual block_instance,
449 * to this page.
451 * @param block_contents $bc the content of the block-like thing.
452 * @param string $region a block region that exists on this page.
454 public function add_fake_block($bc, $region) {
455 $this->page->initialise_theme_and_output();
456 if (!$this->is_known_region($region)) {
457 $region = $this->get_default_region();
459 if (array_key_exists($region, $this->visibleblockcontent)) {
460 throw new coding_exception('block_manager has already prepared the blocks in region ' .
461 $region . 'for output. It is too late to add a fake block.');
463 if (!isset($bc->attributes['data-block'])) {
464 $bc->attributes['data-block'] = '_fake';
466 $bc->attributes['class'] .= ' block_fake';
467 $this->extracontent[$region][] = $bc;
471 * Checks to see whether all of the blocks within the given region are docked
473 * @see region_uses_dock
474 * @param string $region
475 * @return bool True if all of the blocks within that region are docked
477 public function region_completely_docked($region, $output) {
478 global $CFG;
479 // If theme doesn't allow docking or allowblockstodock is not set, then return.
480 if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
481 return false;
484 // Do not dock the region when the user attemps to move a block.
485 if ($this->movingblock) {
486 return false;
489 // Block regions should not be docked during editing when all the blocks are hidden.
490 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
491 return false;
494 $this->check_is_loaded();
495 $this->ensure_content_created($region, $output);
496 if (!$this->region_has_content($region, $output)) {
497 // If the region has no content then nothing is docked at all of course.
498 return false;
500 foreach ($this->visibleblockcontent[$region] as $instance) {
501 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
502 return false;
505 return true;
509 * Checks to see whether any of the blocks within the given regions are docked
511 * @see region_completely_docked
512 * @param array|string $regions array of regions (or single region)
513 * @return bool True if any of the blocks within that region are docked
515 public function region_uses_dock($regions, $output) {
516 if (!$this->page->theme->enable_dock) {
517 return false;
519 $this->check_is_loaded();
520 foreach((array)$regions as $region) {
521 $this->ensure_content_created($region, $output);
522 foreach($this->visibleblockcontent[$region] as $instance) {
523 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
524 return true;
528 return false;
531 /// Actions ====================================================================
534 * This method actually loads the blocks for our page from the database.
536 * @param boolean|null $includeinvisible
537 * null (default) - load hidden blocks if $this->page->user_is_editing();
538 * true - load hidden blocks.
539 * false - don't load hidden blocks.
541 public function load_blocks($includeinvisible = null) {
542 global $DB, $CFG;
544 if (!is_null($this->birecordsbyregion)) {
545 // Already done.
546 return;
549 if ($CFG->version < 2009050619) {
550 // Upgrade/install not complete. Don't try too show any blocks.
551 $this->birecordsbyregion = array();
552 return;
555 // Ensure we have been initialised.
556 if (is_null($this->defaultregion)) {
557 $this->page->initialise_theme_and_output();
558 // If there are still no block regions, then there are no blocks on this page.
559 if (empty($this->regions)) {
560 $this->birecordsbyregion = array();
561 return;
565 // Check if we need to load normal blocks
566 if ($this->fakeblocksonly) {
567 $this->birecordsbyregion = $this->prepare_per_region_arrays();
568 return;
571 if (is_null($includeinvisible)) {
572 $includeinvisible = $this->page->user_is_editing();
574 if ($includeinvisible) {
575 $visiblecheck = '';
576 } else {
577 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
580 $context = $this->page->context;
581 $contexttest = 'bi.parentcontextid = :contextid2';
582 $parentcontextparams = array();
583 $parentcontextids = $context->get_parent_context_ids();
584 if ($parentcontextids) {
585 list($parentcontexttest, $parentcontextparams) =
586 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
587 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
590 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
591 list($pagetypepatterntest, $pagetypepatternparams) =
592 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
594 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
595 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
597 $params = array(
598 'contextlevel' => CONTEXT_BLOCK,
599 'subpage1' => $this->page->subpage,
600 'subpage2' => $this->page->subpage,
601 'contextid1' => $context->id,
602 'contextid2' => $context->id,
603 'pagetype' => $this->page->pagetype,
605 if ($this->page->subpage === '') {
606 $params['subpage1'] = '';
607 $params['subpage2'] = '';
609 $sql = "SELECT
610 bi.id,
611 bp.id AS blockpositionid,
612 bi.blockname,
613 bi.parentcontextid,
614 bi.showinsubcontexts,
615 bi.pagetypepattern,
616 bi.subpagepattern,
617 bi.defaultregion,
618 bi.defaultweight,
619 COALESCE(bp.visible, 1) AS visible,
620 COALESCE(bp.region, bi.defaultregion) AS region,
621 COALESCE(bp.weight, bi.defaultweight) AS weight,
622 bi.configdata
623 $ccselect
625 FROM {block_instances} bi
626 JOIN {block} b ON bi.blockname = b.name
627 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
628 AND bp.contextid = :contextid1
629 AND bp.pagetype = :pagetype
630 AND bp.subpage = :subpage1
631 $ccjoin
633 WHERE
634 $contexttest
635 AND bi.pagetypepattern $pagetypepatterntest
636 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
637 $visiblecheck
638 AND b.visible = 1
640 ORDER BY
641 COALESCE(bp.region, bi.defaultregion),
642 COALESCE(bp.weight, bi.defaultweight),
643 bi.id";
644 $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
646 $this->birecordsbyregion = $this->prepare_per_region_arrays();
647 $unknown = array();
648 foreach ($blockinstances as $bi) {
649 context_helper::preload_from_record($bi);
650 if ($this->is_known_region($bi->region)) {
651 $this->birecordsbyregion[$bi->region][] = $bi;
652 } else {
653 $unknown[] = $bi;
657 // Pages don't necessarily have a defaultregion. The one time this can
658 // happen is when there are no theme block regions, but the script itself
659 // has a block region in the main content area.
660 if (!empty($this->defaultregion)) {
661 $this->birecordsbyregion[$this->defaultregion] =
662 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
667 * Add a block to the current page, or related pages. The block is added to
668 * context $this->page->contextid. If $pagetypepattern $subpagepattern
670 * @param string $blockname The type of block to add.
671 * @param string $region the block region on this page to add the block to.
672 * @param integer $weight determines the order where this block appears in the region.
673 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
674 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
675 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
677 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
678 global $DB;
679 // Allow invisible blocks because this is used when adding default page blocks, which
680 // might include invisible ones if the user makes some default blocks invisible
681 $this->check_known_block_type($blockname, true);
682 $this->check_region_is_known($region);
684 if (empty($pagetypepattern)) {
685 $pagetypepattern = $this->page->pagetype;
688 $blockinstance = new stdClass;
689 $blockinstance->blockname = $blockname;
690 $blockinstance->parentcontextid = $this->page->context->id;
691 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
692 $blockinstance->pagetypepattern = $pagetypepattern;
693 $blockinstance->subpagepattern = $subpagepattern;
694 $blockinstance->defaultregion = $region;
695 $blockinstance->defaultweight = $weight;
696 $blockinstance->configdata = '';
697 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
699 // Ensure the block context is created.
700 context_block::instance($blockinstance->id);
702 // If the new instance was created, allow it to do additional setup
703 if ($block = block_instance($blockname, $blockinstance)) {
704 $block->instance_create();
708 public function add_block_at_end_of_default_region($blockname) {
709 $defaulregion = $this->get_default_region();
711 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
712 if ($lastcurrentblock) {
713 $weight = $lastcurrentblock->weight + 1;
714 } else {
715 $weight = 0;
718 if ($this->page->subpage) {
719 $subpage = $this->page->subpage;
720 } else {
721 $subpage = null;
724 // Special case. Course view page type include the course format, but we
725 // want to add the block non-format-specifically.
726 $pagetypepattern = $this->page->pagetype;
727 if (strpos($pagetypepattern, 'course-view') === 0) {
728 $pagetypepattern = 'course-view-*';
731 // We should end using this for ALL the blocks, making always the 1st option
732 // the default one to be used. Until then, this is one hack to avoid the
733 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
734 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
735 // (the FIRST $pagetypepattern will be set)
737 // We are applying it to all blocks created in mod pages for now and only if the
738 // default pagetype is not one of the available options
739 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
740 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
741 // Only go for the first if the pagetype is not a valid option
742 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
743 $pagetypepattern = key($pagetypelist);
746 // Surely other pages like course-report will need this too, they just are not important
747 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
749 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
753 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
755 * @param array $blocks array with array keys the region names, and values an array of block names.
756 * @param string $pagetypepattern optional. Passed to @see add_block()
757 * @param string $subpagepattern optional. Passed to @see add_block()
759 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
760 $this->add_regions(array_keys($blocks), false);
761 foreach ($blocks as $region => $regionblocks) {
762 $weight = 0;
763 foreach ($regionblocks as $blockname) {
764 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
765 $weight += 1;
771 * Move a block to a new position on this page.
773 * If this block cannot appear on any other pages, then we change defaultposition/weight
774 * in the block_instances table. Otherwise we just set the position on this page.
776 * @param $blockinstanceid the block instance id.
777 * @param $newregion the new region name.
778 * @param $newweight the new weight.
780 public function reposition_block($blockinstanceid, $newregion, $newweight) {
781 global $DB;
783 $this->check_region_is_known($newregion);
784 $inst = $this->find_instance($blockinstanceid);
786 $bi = $inst->instance;
787 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
788 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
789 (!$this->page->subpage || $bi->subpagepattern)) {
791 // Set default position
792 $newbi = new stdClass;
793 $newbi->id = $bi->id;
794 $newbi->defaultregion = $newregion;
795 $newbi->defaultweight = $newweight;
796 $DB->update_record('block_instances', $newbi);
798 if ($bi->blockpositionid) {
799 $bp = new stdClass;
800 $bp->id = $bi->blockpositionid;
801 $bp->region = $newregion;
802 $bp->weight = $newweight;
803 $DB->update_record('block_positions', $bp);
806 } else {
807 // Just set position on this page.
808 $bp = new stdClass;
809 $bp->region = $newregion;
810 $bp->weight = $newweight;
812 if ($bi->blockpositionid) {
813 $bp->id = $bi->blockpositionid;
814 $DB->update_record('block_positions', $bp);
816 } else {
817 $bp->blockinstanceid = $bi->id;
818 $bp->contextid = $this->page->context->id;
819 $bp->pagetype = $this->page->pagetype;
820 if ($this->page->subpage) {
821 $bp->subpage = $this->page->subpage;
822 } else {
823 $bp->subpage = '';
825 $bp->visible = $bi->visible;
826 $DB->insert_record('block_positions', $bp);
832 * Find a given block by its instance id
834 * @param integer $instanceid
835 * @return block_base
837 public function find_instance($instanceid) {
838 foreach ($this->regions as $region => $notused) {
839 $this->ensure_instances_exist($region);
840 foreach($this->blockinstances[$region] as $instance) {
841 if ($instance->instance->id == $instanceid) {
842 return $instance;
846 throw new block_not_on_page_exception($instanceid, $this->page);
849 /// Inner workings =============================================================
852 * Check whether the page blocks have been loaded yet
854 * @return void Throws coding exception if already loaded
856 protected function check_not_yet_loaded() {
857 if (!is_null($this->birecordsbyregion)) {
858 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.');
863 * Check whether the page blocks have been loaded yet
865 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
867 * @return void Throws coding exception if already loaded
869 protected function check_is_loaded() {
870 if (is_null($this->birecordsbyregion)) {
871 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
876 * Check if a block type is known and usable
878 * @param string $blockname The block type name to search for
879 * @param bool $includeinvisible Include disabled block types in the initial pass
880 * @return void Coding Exception thrown if unknown or not enabled
882 protected function check_known_block_type($blockname, $includeinvisible = false) {
883 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
884 if ($this->is_known_block_type($blockname, true)) {
885 throw new coding_exception('Unknown block type ' . $blockname);
886 } else {
887 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
893 * Check if a region is known by its name
895 * @param string $region
896 * @return void Coding Exception thrown if the region is not known
898 protected function check_region_is_known($region) {
899 if (!$this->is_known_region($region)) {
900 throw new coding_exception('Trying to reference an unknown block region ' . $region);
905 * Returns an array of region names as keys and nested arrays for values
907 * @return array an array where the array keys are the region names, and the array
908 * values are empty arrays.
910 protected function prepare_per_region_arrays() {
911 $result = array();
912 foreach ($this->regions as $region => $notused) {
913 $result[$region] = array();
915 return $result;
919 * Create a set of new block instance from a record array
921 * @param array $birecords An array of block instance records
922 * @return array An array of instantiated block_instance objects
924 protected function create_block_instances($birecords) {
925 $results = array();
926 foreach ($birecords as $record) {
927 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
928 $results[] = $blockobject;
931 return $results;
935 * Create all the block instances for all the blocks that were loaded by
936 * load_blocks. This is used, for example, to ensure that all blocks get a
937 * chance to initialise themselves via the {@link block_base::specialize()}
938 * method, before any output is done.
940 public function create_all_block_instances() {
941 foreach ($this->get_regions() as $region) {
942 $this->ensure_instances_exist($region);
947 * Return an array of content objects from a set of block instances
949 * @param array $instances An array of block instances
950 * @param renderer_base The renderer to use.
951 * @param string $region the region name.
952 * @return array An array of block_content (and possibly block_move_target) objects.
954 protected function create_block_contents($instances, $output, $region) {
955 $results = array();
957 $lastweight = 0;
958 $lastblock = 0;
959 if ($this->movingblock) {
960 $first = reset($instances);
961 if ($first) {
962 $lastweight = $first->instance->weight - 2;
966 foreach ($instances as $instance) {
967 $content = $instance->get_content_for_output($output);
968 if (empty($content)) {
969 continue;
972 if ($this->movingblock && $lastweight != $instance->instance->weight &&
973 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
974 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
977 if ($content->blockinstanceid == $this->movingblock) {
978 $content->add_class('beingmoved');
979 $content->annotation .= get_string('movingthisblockcancel', 'block',
980 html_writer::link($this->page->url, get_string('cancel')));
983 $results[] = $content;
984 $lastweight = $instance->instance->weight;
985 $lastblock = $instance->instance->id;
988 if ($this->movingblock && $lastblock != $this->movingblock) {
989 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
991 return $results;
995 * Ensure block instances exist for a given region
997 * @param string $region Check for bi's with the instance with this name
999 protected function ensure_instances_exist($region) {
1000 $this->check_region_is_known($region);
1001 if (!array_key_exists($region, $this->blockinstances)) {
1002 $this->blockinstances[$region] =
1003 $this->create_block_instances($this->birecordsbyregion[$region]);
1008 * Ensure that there is some content within the given region
1010 * @param string $region The name of the region to check
1012 public function ensure_content_created($region, $output) {
1013 $this->ensure_instances_exist($region);
1014 if (!array_key_exists($region, $this->visibleblockcontent)) {
1015 $contents = array();
1016 if (array_key_exists($region, $this->extracontent)) {
1017 $contents = $this->extracontent[$region];
1019 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1020 if ($region == $this->defaultregion) {
1021 $addblockui = block_add_block_ui($this->page, $output);
1022 if ($addblockui) {
1023 $contents[] = $addblockui;
1026 $this->visibleblockcontent[$region] = $contents;
1030 /// Process actions from the URL ===============================================
1033 * Get the appropriate list of editing icons for a block. This is used
1034 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1036 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1037 * @return an array in the format for {@link block_contents::$controls}
1039 public function edit_controls($block) {
1040 global $CFG;
1042 $controls = array();
1043 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1044 $blocktitle = $block->title;
1045 if (empty($blocktitle)) {
1046 $blocktitle = $block->arialabel;
1049 if ($this->page->user_can_edit_blocks()) {
1050 // Move icon.
1051 $str = new lang_string('moveblock', 'block', $blocktitle);
1052 $controls[] = new action_menu_link_primary(
1053 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1054 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1055 $str,
1056 array('class' => 'editing_move')
1061 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1062 // Edit config icon - always show - needed for positioning UI.
1063 $str = new lang_string('configureblock', 'block', $blocktitle);
1064 $controls[] = new action_menu_link_secondary(
1065 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1066 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1067 $str,
1068 array('class' => 'editing_edit')
1073 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1074 // Show/hide icon.
1075 if ($block->instance->visible) {
1076 $str = new lang_string('hideblock', 'block', $blocktitle);
1077 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1078 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1079 $attributes = array('class' => 'editing_hide');
1080 } else {
1081 $str = new lang_string('showblock', 'block', $blocktitle);
1082 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1083 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1084 $attributes = array('class' => 'editing_show');
1086 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1089 // Assign roles icon.
1090 if ($this->page->pagetype != 'my-index' && has_capability('moodle/role:assign', $block->context)) {
1091 //TODO: please note it is sloppy to pass urls through page parameters!!
1092 // it is shortened because some web servers (e.g. IIS by default) give
1093 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1094 $return = $this->page->url->out(false);
1095 $return = str_replace($CFG->wwwroot . '/', '', $return);
1097 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context->id,
1098 'returnurl'=>$return));
1099 // Delete icon.
1100 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1101 $controls[] = new action_menu_link_secondary(
1102 $rolesurl,
1103 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1104 $str,
1105 array('class' => 'editing_roles')
1109 if ($this->user_can_delete_block($block)) {
1110 // Delete icon.
1111 $str = new lang_string('deleteblock', 'block', $blocktitle);
1112 $controls[] = new action_menu_link_secondary(
1113 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1114 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1115 $str,
1116 array('class' => 'editing_delete')
1120 return $controls;
1124 * @param block_base $block a block that appears on this page.
1125 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1127 protected function user_can_delete_block($block) {
1128 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1129 $block->user_can_addto($this->page) &&
1130 !in_array($block->instance->blockname, self::get_undeletable_block_types());
1134 * Process any block actions that were specified in the URL.
1136 * @return boolean true if anything was done. False if not.
1138 public function process_url_actions() {
1139 if (!$this->page->user_is_editing()) {
1140 return false;
1142 return $this->process_url_add() || $this->process_url_delete() ||
1143 $this->process_url_show_hide() || $this->process_url_edit() ||
1144 $this->process_url_move();
1148 * Handle adding a block.
1149 * @return boolean true if anything was done. False if not.
1151 public function process_url_add() {
1152 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1153 if (!$blocktype) {
1154 return false;
1157 require_sesskey();
1159 if (!$this->page->user_can_edit_blocks()) {
1160 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1163 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1164 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1167 $this->add_block_at_end_of_default_region($blocktype);
1169 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1170 $this->page->ensure_param_not_in_url('bui_addblock');
1172 return true;
1176 * Handle deleting a block.
1177 * @return boolean true if anything was done. False if not.
1179 public function process_url_delete() {
1180 global $CFG, $PAGE, $OUTPUT;
1182 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1183 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1185 if (!$blockid) {
1186 return false;
1189 require_sesskey();
1190 $block = $this->page->blocks->find_instance($blockid);
1191 if (!$this->user_can_delete_block($block)) {
1192 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1195 if (!$confirmdelete) {
1196 $deletepage = new moodle_page();
1197 $deletepage->set_pagelayout('admin');
1198 $deletepage->set_course($this->page->course);
1199 $deletepage->set_context($this->page->context);
1200 if ($this->page->cm) {
1201 $deletepage->set_cm($this->page->cm);
1204 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1205 $deleteurlparams = $this->page->url->params();
1206 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1207 $deletepage->set_block_actions_done();
1208 // At this point we are either going to redirect, or display the form, so
1209 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1210 $PAGE = $deletepage;
1211 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1212 $output = $deletepage->get_renderer('core');
1213 $OUTPUT = $output;
1215 $site = get_site();
1216 $blocktitle = $block->get_title();
1217 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1218 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1220 // If the block is being shown in sub contexts display a warning.
1221 if ($block->instance->showinsubcontexts == 1) {
1222 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1223 $systemcontext = context_system::instance();
1224 $messagestring = new stdClass();
1225 $messagestring->location = $parentcontext->get_context_name();
1227 // Checking for blocks that may have visibility on the front page and pages added on that.
1228 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1229 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1230 } else {
1231 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1232 $messagestring->pagetype = $block->instance->pagetypepattern;
1233 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1234 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1238 $message = get_string('deleteblockwarning', 'block', $messagestring);
1241 $PAGE->navbar->add($strdeletecheck);
1242 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1243 $PAGE->set_heading($site->fullname);
1244 echo $OUTPUT->header();
1245 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1246 $cancelurl = new moodle_url($deletepage->url);
1247 $yesbutton = new single_button($confirmurl, get_string('yes'));
1248 $nobutton = new single_button($cancelurl, get_string('no'));
1249 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1250 echo $OUTPUT->footer();
1251 // Make sure that nothing else happens after we have displayed this form.
1252 exit;
1253 } else {
1254 blocks_delete_instance($block->instance);
1255 // bui_deleteid and bui_confirm should not be in the PAGE url.
1256 $this->page->ensure_param_not_in_url('bui_deleteid');
1257 $this->page->ensure_param_not_in_url('bui_confirm');
1258 return true;
1263 * Handle showing or hiding a block.
1264 * @return boolean true if anything was done. False if not.
1266 public function process_url_show_hide() {
1267 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1268 $newvisibility = 0;
1269 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1270 $newvisibility = 1;
1271 } else {
1272 return false;
1275 require_sesskey();
1277 $block = $this->page->blocks->find_instance($blockid);
1279 if (!$this->page->user_can_edit_blocks()) {
1280 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1281 } else if (!$block->instance_can_be_hidden()) {
1282 return false;
1285 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1287 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1288 $this->page->ensure_param_not_in_url('bui_hideid');
1289 $this->page->ensure_param_not_in_url('bui_showid');
1291 return true;
1295 * Handle showing/processing the submission from the block editing form.
1296 * @return boolean true if the form was submitted and the new config saved. Does not
1297 * return if the editing form was displayed. False otherwise.
1299 public function process_url_edit() {
1300 global $CFG, $DB, $PAGE, $OUTPUT;
1302 $blockid = optional_param('bui_editid', null, PARAM_INT);
1303 if (!$blockid) {
1304 return false;
1307 require_sesskey();
1308 require_once($CFG->dirroot . '/blocks/edit_form.php');
1310 $block = $this->find_instance($blockid);
1312 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1313 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1316 $editpage = new moodle_page();
1317 $editpage->set_pagelayout('admin');
1318 $editpage->set_course($this->page->course);
1319 //$editpage->set_context($block->context);
1320 $editpage->set_context($this->page->context);
1321 if ($this->page->cm) {
1322 $editpage->set_cm($this->page->cm);
1324 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1325 $editurlparams = $this->page->url->params();
1326 $editurlparams['bui_editid'] = $blockid;
1327 $editpage->set_url($editurlbase, $editurlparams);
1328 $editpage->set_block_actions_done();
1329 // At this point we are either going to redirect, or display the form, so
1330 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1331 $PAGE = $editpage;
1332 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1333 $output = $editpage->get_renderer('core');
1334 $OUTPUT = $output;
1336 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1337 if (is_readable($formfile)) {
1338 require_once($formfile);
1339 $classname = 'block_' . $block->name() . '_edit_form';
1340 if (!class_exists($classname)) {
1341 $classname = 'block_edit_form';
1343 } else {
1344 $classname = 'block_edit_form';
1347 $mform = new $classname($editpage->url, $block, $this->page);
1348 $mform->set_data($block->instance);
1350 if ($mform->is_cancelled()) {
1351 redirect($this->page->url);
1353 } else if ($data = $mform->get_data()) {
1354 $bi = new stdClass;
1355 $bi->id = $block->instance->id;
1357 // This may get overwritten by the special case handling below.
1358 $bi->pagetypepattern = $data->bui_pagetypepattern;
1359 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1360 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1361 $bi->subpagepattern = null;
1362 } else {
1363 $bi->subpagepattern = $data->bui_subpagepattern;
1366 $systemcontext = context_system::instance();
1367 $frontpagecontext = context_course::instance(SITEID);
1368 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1370 // Updating stickiness and contexts. See MDL-21375 for details.
1371 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1373 // Explicitly set the default context
1374 $bi->parentcontextid = $parentcontext->id;
1376 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1378 // The interface here is a special case because the pagetype pattern is
1379 // totally derived from the context menu. Here are the excpetions. MDL-30340
1381 switch ($data->bui_contexts) {
1382 case BUI_CONTEXTS_ENTIRE_SITE:
1383 // The user wants to show the block across the entire site
1384 $bi->parentcontextid = $systemcontext->id;
1385 $bi->showinsubcontexts = true;
1386 $bi->pagetypepattern = '*';
1387 break;
1388 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1389 // The user wants the block shown on the front page and all subcontexts
1390 $bi->parentcontextid = $frontpagecontext->id;
1391 $bi->showinsubcontexts = true;
1392 $bi->pagetypepattern = '*';
1393 break;
1394 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1395 // The user want to show the front page on the frontpage only
1396 $bi->parentcontextid = $frontpagecontext->id;
1397 $bi->showinsubcontexts = false;
1398 $bi->pagetypepattern = 'site-index';
1399 // This is the only relevant page type anyway but we'll set it explicitly just
1400 // in case the front page grows site-index-* subpages of its own later
1401 break;
1406 $bits = explode('-', $bi->pagetypepattern);
1407 // hacks for some contexts
1408 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1409 // For course context
1410 // is page type pattern is mod-*, change showinsubcontext to 1
1411 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1412 $bi->showinsubcontexts = 1;
1413 } else {
1414 $bi->showinsubcontexts = 0;
1416 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1417 // for user context
1418 // subpagepattern should be null
1419 if ($bits[0] == 'user' or $bits[0] == 'my') {
1420 // we don't need subpagepattern in usercontext
1421 $bi->subpagepattern = null;
1425 $bi->defaultregion = $data->bui_defaultregion;
1426 $bi->defaultweight = $data->bui_defaultweight;
1427 $DB->update_record('block_instances', $bi);
1429 if (!empty($block->config)) {
1430 $config = clone($block->config);
1431 } else {
1432 $config = new stdClass;
1434 foreach ($data as $configfield => $value) {
1435 if (strpos($configfield, 'config_') !== 0) {
1436 continue;
1438 $field = substr($configfield, 7);
1439 $config->$field = $value;
1441 $block->instance_config_save($config);
1443 $bp = new stdClass;
1444 $bp->visible = $data->bui_visible;
1445 $bp->region = $data->bui_region;
1446 $bp->weight = $data->bui_weight;
1447 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1448 $data->bui_weight != $data->bui_defaultweight;
1450 if ($block->instance->blockpositionid && !$needbprecord) {
1451 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1453 } else if ($block->instance->blockpositionid && $needbprecord) {
1454 $bp->id = $block->instance->blockpositionid;
1455 $DB->update_record('block_positions', $bp);
1457 } else if ($needbprecord) {
1458 $bp->blockinstanceid = $block->instance->id;
1459 $bp->contextid = $this->page->context->id;
1460 $bp->pagetype = $this->page->pagetype;
1461 if ($this->page->subpage) {
1462 $bp->subpage = $this->page->subpage;
1463 } else {
1464 $bp->subpage = '';
1466 $DB->insert_record('block_positions', $bp);
1469 redirect($this->page->url);
1471 } else {
1472 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1473 $editpage->set_title($strheading);
1474 $editpage->set_heading($strheading);
1475 $bits = explode('-', $this->page->pagetype);
1476 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1477 // better navbar for tag pages
1478 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1479 $tag = tag_get('id', $this->page->subpage, '*');
1480 // tag search page doesn't have subpageid
1481 if ($tag) {
1482 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1485 $editpage->navbar->add($block->get_title());
1486 $editpage->navbar->add(get_string('configuration'));
1487 echo $output->header();
1488 echo $output->heading($strheading, 2);
1489 $mform->display();
1490 echo $output->footer();
1491 exit;
1496 * Handle showing/processing the submission from the block editing form.
1497 * @return boolean true if the form was submitted and the new config saved. Does not
1498 * return if the editing form was displayed. False otherwise.
1500 public function process_url_move() {
1501 global $CFG, $DB, $PAGE;
1503 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1504 if (!$blockid) {
1505 return false;
1508 require_sesskey();
1510 $block = $this->find_instance($blockid);
1512 if (!$this->page->user_can_edit_blocks()) {
1513 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1516 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1517 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1518 if (!$newregion || is_null($newweight)) {
1519 // Don't have a valid target position yet, must be just starting the move.
1520 $this->movingblock = $blockid;
1521 $this->page->ensure_param_not_in_url('bui_moveid');
1522 return false;
1525 if (!$this->is_known_region($newregion)) {
1526 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1529 // Move this block. This may involve moving other nearby blocks.
1530 $blocks = $this->birecordsbyregion[$newregion];
1532 $maxweight = self::MAX_WEIGHT;
1533 $minweight = -self::MAX_WEIGHT;
1535 // Initialise the used weights and spareweights array with the default values
1536 $spareweights = array();
1537 $usedweights = array();
1538 for ($i = $minweight; $i <= $maxweight; $i++) {
1539 $spareweights[$i] = $i;
1540 $usedweights[$i] = array();
1543 // Check each block and sort out where we have used weights
1544 foreach ($blocks as $bi) {
1545 if ($bi->weight > $maxweight) {
1546 // If this statement is true then the blocks weight is more than the
1547 // current maximum. To ensure that we can get the best block position
1548 // we will initialise elements within the usedweights and spareweights
1549 // arrays between the blocks weight (which will then be the new max) and
1550 // the current max
1551 $parseweight = $bi->weight;
1552 while (!array_key_exists($parseweight, $usedweights)) {
1553 $usedweights[$parseweight] = array();
1554 $spareweights[$parseweight] = $parseweight;
1555 $parseweight--;
1557 $maxweight = $bi->weight;
1558 } else if ($bi->weight < $minweight) {
1559 // As above except this time the blocks weight is LESS than the
1560 // the current minimum, so we will initialise the array from the
1561 // blocks weight (new minimum) to the current minimum
1562 $parseweight = $bi->weight;
1563 while (!array_key_exists($parseweight, $usedweights)) {
1564 $usedweights[$parseweight] = array();
1565 $spareweights[$parseweight] = $parseweight;
1566 $parseweight++;
1568 $minweight = $bi->weight;
1570 if ($bi->id != $block->instance->id) {
1571 unset($spareweights[$bi->weight]);
1572 $usedweights[$bi->weight][] = $bi->id;
1576 // First we find the nearest gap in the list of weights.
1577 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1578 $bestgap = null;
1579 foreach ($spareweights as $spareweight) {
1580 if (abs($newweight - $spareweight) < $bestdistance) {
1581 $bestdistance = abs($newweight - $spareweight);
1582 $bestgap = $spareweight;
1586 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1587 if (is_null($bestgap)) {
1588 $bestgap = self::MAX_WEIGHT + 1;
1589 while (!empty($usedweights[$bestgap])) {
1590 $bestgap++;
1594 // Now we know the gap we are aiming for, so move all the blocks along.
1595 if ($bestgap < $newweight) {
1596 $newweight = floor($newweight);
1597 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1598 foreach ($usedweights[$weight] as $biid) {
1599 $this->reposition_block($biid, $newregion, $weight - 1);
1602 $this->reposition_block($block->instance->id, $newregion, $newweight);
1603 } else {
1604 $newweight = ceil($newweight);
1605 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1606 if (array_key_exists($weight, $usedweights)) {
1607 foreach ($usedweights[$weight] as $biid) {
1608 $this->reposition_block($biid, $newregion, $weight + 1);
1612 $this->reposition_block($block->instance->id, $newregion, $newweight);
1615 $this->page->ensure_param_not_in_url('bui_moveid');
1616 $this->page->ensure_param_not_in_url('bui_newregion');
1617 $this->page->ensure_param_not_in_url('bui_newweight');
1618 return true;
1622 * Turns the display of normal blocks either on or off.
1624 * @param bool $setting
1626 public function show_only_fake_blocks($setting = true) {
1627 $this->fakeblocksonly = $setting;
1631 /// Helper functions for working with block classes ============================
1634 * Call a class method (one that does not require a block instance) on a block class.
1636 * @param string $blockname the name of the block.
1637 * @param string $method the method name.
1638 * @param array $param parameters to pass to the method.
1639 * @return mixed whatever the method returns.
1641 function block_method_result($blockname, $method, $param = NULL) {
1642 if(!block_load_class($blockname)) {
1643 return NULL;
1645 return call_user_func(array('block_'.$blockname, $method), $param);
1649 * Creates a new instance of the specified block class.
1651 * @param string $blockname the name of the block.
1652 * @param $instance block_instances DB table row (optional).
1653 * @param moodle_page $page the page this block is appearing on.
1654 * @return block_base the requested block instance.
1656 function block_instance($blockname, $instance = NULL, $page = NULL) {
1657 if(!block_load_class($blockname)) {
1658 return false;
1660 $classname = 'block_'.$blockname;
1661 $retval = new $classname;
1662 if($instance !== NULL) {
1663 if (is_null($page)) {
1664 global $PAGE;
1665 $page = $PAGE;
1667 $retval->_load_instance($instance, $page);
1669 return $retval;
1673 * Load the block class for a particular type of block.
1675 * @param string $blockname the name of the block.
1676 * @return boolean success or failure.
1678 function block_load_class($blockname) {
1679 global $CFG;
1681 if(empty($blockname)) {
1682 return false;
1685 $classname = 'block_'.$blockname;
1687 if(class_exists($classname)) {
1688 return true;
1691 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1693 if (file_exists($blockpath)) {
1694 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1695 include_once($blockpath);
1696 }else{
1697 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1698 return false;
1701 return class_exists($classname);
1705 * Given a specific page type, return all the page type patterns that might
1706 * match it.
1708 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1709 * @return array an array of all the page type patterns that might match this page type.
1711 function matching_page_type_patterns($pagetype) {
1712 $patterns = array($pagetype);
1713 $bits = explode('-', $pagetype);
1714 if (count($bits) == 3 && $bits[0] == 'mod') {
1715 if ($bits[2] == 'view') {
1716 $patterns[] = 'mod-*-view';
1717 } else if ($bits[2] == 'index') {
1718 $patterns[] = 'mod-*-index';
1721 while (count($bits) > 0) {
1722 $patterns[] = implode('-', $bits) . '-*';
1723 array_pop($bits);
1725 $patterns[] = '*';
1726 return $patterns;
1730 * Give an specific pattern, return all the page type patterns that would also match it.
1732 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
1733 * @return array of all the page type patterns matching.
1735 function matching_page_type_patterns_from_pattern($pattern) {
1736 $patterns = array($pattern);
1737 if ($pattern === '*') {
1738 return $patterns;
1741 // Only keep the part before the star because we will append -* to all the bits.
1742 $star = strpos($pattern, '-*');
1743 if ($star !== false) {
1744 $pattern = substr($pattern, 0, $star);
1747 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
1748 $patterns = array_unique($patterns);
1750 return $patterns;
1754 * Given a specific page type, parent context and currect context, return all the page type patterns
1755 * that might be used by this block.
1757 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1758 * @param stdClass $parentcontext Block's parent context
1759 * @param stdClass $currentcontext Current context of block
1760 * @return array an array of all the page type patterns that might match this page type.
1762 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1763 global $CFG; // Required for includes bellow.
1765 $bits = explode('-', $pagetype);
1767 $core = core_component::get_core_subsystems();
1768 $plugins = core_component::get_plugin_types();
1770 //progressively strip pieces off the page type looking for a match
1771 $componentarray = null;
1772 for ($i = count($bits); $i > 0; $i--) {
1773 $possiblecomponentarray = array_slice($bits, 0, $i);
1774 $possiblecomponent = implode('', $possiblecomponentarray);
1776 // Check to see if the component is a core component
1777 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1778 $libfile = $core[$possiblecomponent].'/lib.php';
1779 if (file_exists($libfile)) {
1780 require_once($libfile);
1781 $function = $possiblecomponent.'_page_type_list';
1782 if (function_exists($function)) {
1783 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1784 break;
1790 //check the plugin directory and look for a callback
1791 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1793 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1794 if (count($bits) > $i) {
1795 $pluginname = $bits[$i];
1796 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1797 if (!empty($directory)){
1798 $libfile = $directory.'/lib.php';
1799 if (file_exists($libfile)) {
1800 require_once($libfile);
1801 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1802 if (!function_exists($function)) {
1803 $function = $pluginname.'_page_type_list';
1805 if (function_exists($function)) {
1806 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1807 break;
1814 //we'll only get to here if we still don't have any patterns
1815 //the plugin type may have a callback
1816 $directory = $plugins[$possiblecomponent];
1817 $libfile = $directory.'/lib.php';
1818 if (file_exists($libfile)) {
1819 require_once($libfile);
1820 $function = $possiblecomponent.'_page_type_list';
1821 if (function_exists($function)) {
1822 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1823 break;
1830 if (empty($patterns)) {
1831 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1834 // Ensure that the * pattern is always available if editing block 'at distance', so
1835 // we always can 'bring back' it to the original context. MDL-30340
1836 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1837 // TODO: We could change the string here, showing its 'bring back' meaning
1838 $patterns['*'] = get_string('page-x', 'pagetype');
1841 return $patterns;
1845 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1847 * @param string $pagetype
1848 * @param stdClass $parentcontext
1849 * @param stdClass $currentcontext
1850 * @return array
1852 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1853 // Generate page type patterns based on current page type if
1854 // callbacks haven't been defined
1855 $patterns = array($pagetype => $pagetype);
1856 $bits = explode('-', $pagetype);
1857 while (count($bits) > 0) {
1858 $pattern = implode('-', $bits) . '-*';
1859 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1860 // guessing page type description
1861 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1862 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1863 } else {
1864 $patterns[$pattern] = $pattern;
1866 array_pop($bits);
1868 $patterns['*'] = get_string('page-x', 'pagetype');
1869 return $patterns;
1873 * Generates the page type list for the my moodle page
1875 * @param string $pagetype
1876 * @param stdClass $parentcontext
1877 * @param stdClass $currentcontext
1878 * @return array
1880 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1881 return array('my-index' => get_string('page-my-index', 'pagetype'));
1885 * Generates the page type list for a module by either locating and using the modules callback
1886 * or by generating a default list.
1888 * @param string $pagetype
1889 * @param stdClass $parentcontext
1890 * @param stdClass $currentcontext
1891 * @return array
1893 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1894 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1895 if (empty($patterns)) {
1896 // if modules don't have callbacks
1897 // generate two default page type patterns for modules only
1898 $bits = explode('-', $pagetype);
1899 $patterns = array($pagetype => $pagetype);
1900 if ($bits[2] == 'view') {
1901 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1902 } else if ($bits[2] == 'index') {
1903 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1906 return $patterns;
1908 /// Functions update the blocks if required by the request parameters ==========
1911 * Return a {@link block_contents} representing the add a new block UI, if
1912 * this user is allowed to see it.
1914 * @return block_contents an appropriate block_contents, or null if the user
1915 * cannot add any blocks here.
1917 function block_add_block_ui($page, $output) {
1918 global $CFG, $OUTPUT;
1919 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1920 return null;
1923 $bc = new block_contents();
1924 $bc->title = get_string('addblock');
1925 $bc->add_class('block_adminblock');
1926 $bc->attributes['data-block'] = 'adminblock';
1928 $missingblocks = $page->blocks->get_addable_blocks();
1929 if (empty($missingblocks)) {
1930 $bc->content = get_string('noblockstoaddhere');
1931 return $bc;
1934 $menu = array();
1935 foreach ($missingblocks as $block) {
1936 $blockobject = block_instance($block->name);
1937 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1938 $menu[$block->name] = $blockobject->get_title();
1941 core_collator::asort($menu);
1943 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1944 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1945 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1946 $bc->content = $OUTPUT->render($select);
1947 return $bc;
1951 * Actually delete from the database any blocks that are currently on this page,
1952 * but which should not be there according to blocks_name_allowed_in_format.
1954 * @todo Write/Fix this function. Currently returns immediately
1955 * @param $course
1957 function blocks_remove_inappropriate($course) {
1958 // TODO
1959 return;
1961 $blockmanager = blocks_get_by_page($page);
1963 if (empty($blockmanager)) {
1964 return;
1967 if (($pageformat = $page->pagetype) == NULL) {
1968 return;
1971 foreach($blockmanager as $region) {
1972 foreach($region as $instance) {
1973 $block = blocks_get_record($instance->blockid);
1974 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1975 blocks_delete_instance($instance->instance);
1982 * Check that a given name is in a permittable format
1984 * @param string $name
1985 * @param string $pageformat
1986 * @return bool
1988 function blocks_name_allowed_in_format($name, $pageformat) {
1989 $accept = NULL;
1990 $maxdepth = -1;
1991 if (!$bi = block_instance($name)) {
1992 return false;
1995 $formats = $bi->applicable_formats();
1996 if (!$formats) {
1997 $formats = array();
1999 foreach ($formats as $format => $allowed) {
2000 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2001 $depth = substr_count($format, '-');
2002 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2003 $maxdepth = $depth;
2004 $accept = $allowed;
2007 if ($accept === NULL) {
2008 $accept = !empty($formats['all']);
2010 return $accept;
2014 * Delete a block, and associated data.
2016 * @param object $instance a row from the block_instances table
2017 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2018 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2020 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2021 global $DB;
2023 if ($block = block_instance($instance->blockname, $instance)) {
2024 $block->instance_delete();
2026 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2028 if (!$skipblockstables) {
2029 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2030 $DB->delete_records('block_instances', array('id' => $instance->id));
2031 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2036 * Delete all the blocks that belong to a particular context.
2038 * @param int $contextid the context id.
2040 function blocks_delete_all_for_context($contextid) {
2041 global $DB;
2042 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2043 foreach ($instances as $instance) {
2044 blocks_delete_instance($instance, true);
2046 $instances->close();
2047 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2048 $DB->delete_records('block_positions', array('contextid' => $contextid));
2052 * Set a block to be visible or hidden on a particular page.
2054 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2055 * block_positions table as return by block_manager.
2056 * @param moodle_page $page the back to set the visibility with respect to.
2057 * @param integer $newvisibility 1 for visible, 0 for hidden.
2059 function blocks_set_visibility($instance, $page, $newvisibility) {
2060 global $DB;
2061 if (!empty($instance->blockpositionid)) {
2062 // Already have local information on this page.
2063 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2064 return;
2067 // Create a new block_positions record.
2068 $bp = new stdClass;
2069 $bp->blockinstanceid = $instance->id;
2070 $bp->contextid = $page->context->id;
2071 $bp->pagetype = $page->pagetype;
2072 if ($page->subpage) {
2073 $bp->subpage = $page->subpage;
2075 $bp->visible = $newvisibility;
2076 $bp->region = $instance->defaultregion;
2077 $bp->weight = $instance->defaultweight;
2078 $DB->insert_record('block_positions', $bp);
2082 * Get the block record for a particular blockid - that is, a particular type os block.
2084 * @param $int blockid block type id. If null, an array of all block types is returned.
2085 * @param bool $notusedanymore No longer used.
2086 * @return array|object row from block table, or all rows.
2088 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2089 global $PAGE;
2090 $blocks = $PAGE->blocks->get_installed_blocks();
2091 if ($blockid === NULL) {
2092 return $blocks;
2093 } else if (isset($blocks[$blockid])) {
2094 return $blocks[$blockid];
2095 } else {
2096 return false;
2101 * Find a given block by its blockid within a provide array
2103 * @param int $blockid
2104 * @param array $blocksarray
2105 * @return bool|object Instance if found else false
2107 function blocks_find_block($blockid, $blocksarray) {
2108 if (empty($blocksarray)) {
2109 return false;
2111 foreach($blocksarray as $blockgroup) {
2112 if (empty($blockgroup)) {
2113 continue;
2115 foreach($blockgroup as $instance) {
2116 if($instance->blockid == $blockid) {
2117 return $instance;
2121 return false;
2124 // Functions for programatically adding default blocks to pages ================
2127 * Parse a list of default blocks. See config-dist for a description of the format.
2129 * @param string $blocksstr
2130 * @return array
2132 function blocks_parse_default_blocks_list($blocksstr) {
2133 $blocks = array();
2134 $bits = explode(':', $blocksstr);
2135 if (!empty($bits)) {
2136 $leftbits = trim(array_shift($bits));
2137 if ($leftbits != '') {
2138 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2141 if (!empty($bits)) {
2142 $rightbits =trim(array_shift($bits));
2143 if ($rightbits != '') {
2144 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2147 return $blocks;
2151 * @return array the blocks that should be added to the site course by default.
2153 function blocks_get_default_site_course_blocks() {
2154 global $CFG;
2156 if (!empty($CFG->defaultblocks_site)) {
2157 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2158 } else {
2159 return array(
2160 BLOCK_POS_LEFT => array('site_main_menu'),
2161 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2167 * Add the default blocks to a course.
2169 * @param object $course a course object.
2171 function blocks_add_default_course_blocks($course) {
2172 global $CFG;
2174 if (!empty($CFG->defaultblocks_override)) {
2175 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2177 } else if ($course->id == SITEID) {
2178 $blocknames = blocks_get_default_site_course_blocks();
2180 } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2181 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2183 } else {
2184 require_once($CFG->dirroot. '/course/lib.php');
2185 $blocknames = course_get_format($course)->get_default_blocks();
2189 if ($course->id == SITEID) {
2190 $pagetypepattern = 'site-index';
2191 } else {
2192 $pagetypepattern = 'course-view-*';
2194 $page = new moodle_page();
2195 $page->set_course($course);
2196 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2200 * Add the default system-context blocks. E.g. the admin tree.
2202 function blocks_add_default_system_blocks() {
2203 global $DB;
2205 $page = new moodle_page();
2206 $page->set_context(context_system::instance());
2207 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2208 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2210 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2211 $subpagepattern = $defaultmypage->id;
2212 } else {
2213 $subpagepattern = null;
2216 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2217 $newcontent = array('course_overview');
2218 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);