Merge branch 'MDL-47480-28' of git://github.com/ankitagarwal/moodle into MOODLE_28_STABLE
[moodle.git] / lib / blocklib.php
bloba44c18567ead559b7c08a1e9e6e30a1a30dbacfa
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. Optionally, a starting weight
754 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
755 * and incremented by the position of the block in the $blocks array
757 * @param array $blocks array with array keys the region names, and values an array of block names.
758 * @param string $pagetypepattern optional. Passed to {@link add_block()}
759 * @param string $subpagepattern optional. Passed to {@link add_block()}
760 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
761 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
763 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
764 $initialweight = $weight;
765 $this->add_regions(array_keys($blocks), false);
766 foreach ($blocks as $region => $regionblocks) {
767 foreach ($regionblocks as $offset => $blockname) {
768 $weight = $initialweight + $offset;
769 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
775 * Move a block to a new position on this page.
777 * If this block cannot appear on any other pages, then we change defaultposition/weight
778 * in the block_instances table. Otherwise we just set the position on this page.
780 * @param $blockinstanceid the block instance id.
781 * @param $newregion the new region name.
782 * @param $newweight the new weight.
784 public function reposition_block($blockinstanceid, $newregion, $newweight) {
785 global $DB;
787 $this->check_region_is_known($newregion);
788 $inst = $this->find_instance($blockinstanceid);
790 $bi = $inst->instance;
791 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
792 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
793 (!$this->page->subpage || $bi->subpagepattern)) {
795 // Set default position
796 $newbi = new stdClass;
797 $newbi->id = $bi->id;
798 $newbi->defaultregion = $newregion;
799 $newbi->defaultweight = $newweight;
800 $DB->update_record('block_instances', $newbi);
802 if ($bi->blockpositionid) {
803 $bp = new stdClass;
804 $bp->id = $bi->blockpositionid;
805 $bp->region = $newregion;
806 $bp->weight = $newweight;
807 $DB->update_record('block_positions', $bp);
810 } else {
811 // Just set position on this page.
812 $bp = new stdClass;
813 $bp->region = $newregion;
814 $bp->weight = $newweight;
816 if ($bi->blockpositionid) {
817 $bp->id = $bi->blockpositionid;
818 $DB->update_record('block_positions', $bp);
820 } else {
821 $bp->blockinstanceid = $bi->id;
822 $bp->contextid = $this->page->context->id;
823 $bp->pagetype = $this->page->pagetype;
824 if ($this->page->subpage) {
825 $bp->subpage = $this->page->subpage;
826 } else {
827 $bp->subpage = '';
829 $bp->visible = $bi->visible;
830 $DB->insert_record('block_positions', $bp);
836 * Find a given block by its instance id
838 * @param integer $instanceid
839 * @return block_base
841 public function find_instance($instanceid) {
842 foreach ($this->regions as $region => $notused) {
843 $this->ensure_instances_exist($region);
844 foreach($this->blockinstances[$region] as $instance) {
845 if ($instance->instance->id == $instanceid) {
846 return $instance;
850 throw new block_not_on_page_exception($instanceid, $this->page);
853 /// Inner workings =============================================================
856 * Check whether the page blocks have been loaded yet
858 * @return void Throws coding exception if already loaded
860 protected function check_not_yet_loaded() {
861 if (!is_null($this->birecordsbyregion)) {
862 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.');
867 * Check whether the page blocks have been loaded yet
869 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
871 * @return void Throws coding exception if already loaded
873 protected function check_is_loaded() {
874 if (is_null($this->birecordsbyregion)) {
875 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
880 * Check if a block type is known and usable
882 * @param string $blockname The block type name to search for
883 * @param bool $includeinvisible Include disabled block types in the initial pass
884 * @return void Coding Exception thrown if unknown or not enabled
886 protected function check_known_block_type($blockname, $includeinvisible = false) {
887 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
888 if ($this->is_known_block_type($blockname, true)) {
889 throw new coding_exception('Unknown block type ' . $blockname);
890 } else {
891 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
897 * Check if a region is known by its name
899 * @param string $region
900 * @return void Coding Exception thrown if the region is not known
902 protected function check_region_is_known($region) {
903 if (!$this->is_known_region($region)) {
904 throw new coding_exception('Trying to reference an unknown block region ' . $region);
909 * Returns an array of region names as keys and nested arrays for values
911 * @return array an array where the array keys are the region names, and the array
912 * values are empty arrays.
914 protected function prepare_per_region_arrays() {
915 $result = array();
916 foreach ($this->regions as $region => $notused) {
917 $result[$region] = array();
919 return $result;
923 * Create a set of new block instance from a record array
925 * @param array $birecords An array of block instance records
926 * @return array An array of instantiated block_instance objects
928 protected function create_block_instances($birecords) {
929 $results = array();
930 foreach ($birecords as $record) {
931 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
932 $results[] = $blockobject;
935 return $results;
939 * Create all the block instances for all the blocks that were loaded by
940 * load_blocks. This is used, for example, to ensure that all blocks get a
941 * chance to initialise themselves via the {@link block_base::specialize()}
942 * method, before any output is done.
944 public function create_all_block_instances() {
945 foreach ($this->get_regions() as $region) {
946 $this->ensure_instances_exist($region);
951 * Return an array of content objects from a set of block instances
953 * @param array $instances An array of block instances
954 * @param renderer_base The renderer to use.
955 * @param string $region the region name.
956 * @return array An array of block_content (and possibly block_move_target) objects.
958 protected function create_block_contents($instances, $output, $region) {
959 $results = array();
961 $lastweight = 0;
962 $lastblock = 0;
963 if ($this->movingblock) {
964 $first = reset($instances);
965 if ($first) {
966 $lastweight = $first->instance->weight - 2;
970 foreach ($instances as $instance) {
971 $content = $instance->get_content_for_output($output);
972 if (empty($content)) {
973 continue;
976 if ($this->movingblock && $lastweight != $instance->instance->weight &&
977 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
978 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
981 if ($content->blockinstanceid == $this->movingblock) {
982 $content->add_class('beingmoved');
983 $content->annotation .= get_string('movingthisblockcancel', 'block',
984 html_writer::link($this->page->url, get_string('cancel')));
987 $results[] = $content;
988 $lastweight = $instance->instance->weight;
989 $lastblock = $instance->instance->id;
992 if ($this->movingblock && $lastblock != $this->movingblock) {
993 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
995 return $results;
999 * Ensure block instances exist for a given region
1001 * @param string $region Check for bi's with the instance with this name
1003 protected function ensure_instances_exist($region) {
1004 $this->check_region_is_known($region);
1005 if (!array_key_exists($region, $this->blockinstances)) {
1006 $this->blockinstances[$region] =
1007 $this->create_block_instances($this->birecordsbyregion[$region]);
1012 * Ensure that there is some content within the given region
1014 * @param string $region The name of the region to check
1016 public function ensure_content_created($region, $output) {
1017 $this->ensure_instances_exist($region);
1018 if (!array_key_exists($region, $this->visibleblockcontent)) {
1019 $contents = array();
1020 if (array_key_exists($region, $this->extracontent)) {
1021 $contents = $this->extracontent[$region];
1023 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1024 if ($region == $this->defaultregion) {
1025 $addblockui = block_add_block_ui($this->page, $output);
1026 if ($addblockui) {
1027 $contents[] = $addblockui;
1030 $this->visibleblockcontent[$region] = $contents;
1034 /// Process actions from the URL ===============================================
1037 * Get the appropriate list of editing icons for a block. This is used
1038 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1040 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1041 * @return an array in the format for {@link block_contents::$controls}
1043 public function edit_controls($block) {
1044 global $CFG;
1046 $controls = array();
1047 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1048 $blocktitle = $block->title;
1049 if (empty($blocktitle)) {
1050 $blocktitle = $block->arialabel;
1053 if ($this->page->user_can_edit_blocks()) {
1054 // Move icon.
1055 $str = new lang_string('moveblock', 'block', $blocktitle);
1056 $controls[] = new action_menu_link_primary(
1057 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1058 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1059 $str,
1060 array('class' => 'editing_move')
1065 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1066 // Edit config icon - always show - needed for positioning UI.
1067 $str = new lang_string('configureblock', 'block', $blocktitle);
1068 $controls[] = new action_menu_link_secondary(
1069 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1070 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1071 $str,
1072 array('class' => 'editing_edit')
1077 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1078 // Show/hide icon.
1079 if ($block->instance->visible) {
1080 $str = new lang_string('hideblock', 'block', $blocktitle);
1081 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1082 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1083 $attributes = array('class' => 'editing_hide');
1084 } else {
1085 $str = new lang_string('showblock', 'block', $blocktitle);
1086 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1087 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1088 $attributes = array('class' => 'editing_show');
1090 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1093 // Assign roles icon.
1094 if ($this->page->pagetype != 'my-index' && has_capability('moodle/role:assign', $block->context)) {
1095 //TODO: please note it is sloppy to pass urls through page parameters!!
1096 // it is shortened because some web servers (e.g. IIS by default) give
1097 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1098 $return = $this->page->url->out(false);
1099 $return = str_replace($CFG->wwwroot . '/', '', $return);
1101 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context->id,
1102 'returnurl'=>$return));
1103 // Delete icon.
1104 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1105 $controls[] = new action_menu_link_secondary(
1106 $rolesurl,
1107 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1108 $str,
1109 array('class' => 'editing_roles')
1113 if ($this->user_can_delete_block($block)) {
1114 // Delete icon.
1115 $str = new lang_string('deleteblock', 'block', $blocktitle);
1116 $controls[] = new action_menu_link_secondary(
1117 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1118 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1119 $str,
1120 array('class' => 'editing_delete')
1124 return $controls;
1128 * @param block_base $block a block that appears on this page.
1129 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1131 protected function user_can_delete_block($block) {
1132 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1133 $block->user_can_addto($this->page) &&
1134 !in_array($block->instance->blockname, self::get_undeletable_block_types());
1138 * Process any block actions that were specified in the URL.
1140 * @return boolean true if anything was done. False if not.
1142 public function process_url_actions() {
1143 if (!$this->page->user_is_editing()) {
1144 return false;
1146 return $this->process_url_add() || $this->process_url_delete() ||
1147 $this->process_url_show_hide() || $this->process_url_edit() ||
1148 $this->process_url_move();
1152 * Handle adding a block.
1153 * @return boolean true if anything was done. False if not.
1155 public function process_url_add() {
1156 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1157 if (!$blocktype) {
1158 return false;
1161 require_sesskey();
1163 if (!$this->page->user_can_edit_blocks()) {
1164 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1167 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1168 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1171 $this->add_block_at_end_of_default_region($blocktype);
1173 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1174 $this->page->ensure_param_not_in_url('bui_addblock');
1176 return true;
1180 * Handle deleting a block.
1181 * @return boolean true if anything was done. False if not.
1183 public function process_url_delete() {
1184 global $CFG, $PAGE, $OUTPUT;
1186 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1187 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1189 if (!$blockid) {
1190 return false;
1193 require_sesskey();
1194 $block = $this->page->blocks->find_instance($blockid);
1195 if (!$this->user_can_delete_block($block)) {
1196 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1199 if (!$confirmdelete) {
1200 $deletepage = new moodle_page();
1201 $deletepage->set_pagelayout('admin');
1202 $deletepage->set_course($this->page->course);
1203 $deletepage->set_context($this->page->context);
1204 if ($this->page->cm) {
1205 $deletepage->set_cm($this->page->cm);
1208 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1209 $deleteurlparams = $this->page->url->params();
1210 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1211 $deletepage->set_block_actions_done();
1212 // At this point we are either going to redirect, or display the form, so
1213 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1214 $PAGE = $deletepage;
1215 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1216 $output = $deletepage->get_renderer('core');
1217 $OUTPUT = $output;
1219 $site = get_site();
1220 $blocktitle = $block->get_title();
1221 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1222 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1224 // If the block is being shown in sub contexts display a warning.
1225 if ($block->instance->showinsubcontexts == 1) {
1226 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1227 $systemcontext = context_system::instance();
1228 $messagestring = new stdClass();
1229 $messagestring->location = $parentcontext->get_context_name();
1231 // Checking for blocks that may have visibility on the front page and pages added on that.
1232 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1233 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1234 } else {
1235 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1236 $messagestring->pagetype = $block->instance->pagetypepattern;
1237 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1238 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1242 $message = get_string('deleteblockwarning', 'block', $messagestring);
1245 $PAGE->navbar->add($strdeletecheck);
1246 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1247 $PAGE->set_heading($site->fullname);
1248 echo $OUTPUT->header();
1249 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1250 $cancelurl = new moodle_url($deletepage->url);
1251 $yesbutton = new single_button($confirmurl, get_string('yes'));
1252 $nobutton = new single_button($cancelurl, get_string('no'));
1253 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1254 echo $OUTPUT->footer();
1255 // Make sure that nothing else happens after we have displayed this form.
1256 exit;
1257 } else {
1258 blocks_delete_instance($block->instance);
1259 // bui_deleteid and bui_confirm should not be in the PAGE url.
1260 $this->page->ensure_param_not_in_url('bui_deleteid');
1261 $this->page->ensure_param_not_in_url('bui_confirm');
1262 return true;
1267 * Handle showing or hiding a block.
1268 * @return boolean true if anything was done. False if not.
1270 public function process_url_show_hide() {
1271 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1272 $newvisibility = 0;
1273 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1274 $newvisibility = 1;
1275 } else {
1276 return false;
1279 require_sesskey();
1281 $block = $this->page->blocks->find_instance($blockid);
1283 if (!$this->page->user_can_edit_blocks()) {
1284 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1285 } else if (!$block->instance_can_be_hidden()) {
1286 return false;
1289 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1291 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1292 $this->page->ensure_param_not_in_url('bui_hideid');
1293 $this->page->ensure_param_not_in_url('bui_showid');
1295 return true;
1299 * Handle showing/processing the submission from the block editing form.
1300 * @return boolean true if the form was submitted and the new config saved. Does not
1301 * return if the editing form was displayed. False otherwise.
1303 public function process_url_edit() {
1304 global $CFG, $DB, $PAGE, $OUTPUT;
1306 $blockid = optional_param('bui_editid', null, PARAM_INT);
1307 if (!$blockid) {
1308 return false;
1311 require_sesskey();
1312 require_once($CFG->dirroot . '/blocks/edit_form.php');
1314 $block = $this->find_instance($blockid);
1316 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1317 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1320 $editpage = new moodle_page();
1321 $editpage->set_pagelayout('admin');
1322 $editpage->set_course($this->page->course);
1323 //$editpage->set_context($block->context);
1324 $editpage->set_context($this->page->context);
1325 if ($this->page->cm) {
1326 $editpage->set_cm($this->page->cm);
1328 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1329 $editurlparams = $this->page->url->params();
1330 $editurlparams['bui_editid'] = $blockid;
1331 $editpage->set_url($editurlbase, $editurlparams);
1332 $editpage->set_block_actions_done();
1333 // At this point we are either going to redirect, or display the form, so
1334 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1335 $PAGE = $editpage;
1336 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1337 $output = $editpage->get_renderer('core');
1338 $OUTPUT = $output;
1340 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1341 if (is_readable($formfile)) {
1342 require_once($formfile);
1343 $classname = 'block_' . $block->name() . '_edit_form';
1344 if (!class_exists($classname)) {
1345 $classname = 'block_edit_form';
1347 } else {
1348 $classname = 'block_edit_form';
1351 $mform = new $classname($editpage->url, $block, $this->page);
1352 $mform->set_data($block->instance);
1354 if ($mform->is_cancelled()) {
1355 redirect($this->page->url);
1357 } else if ($data = $mform->get_data()) {
1358 $bi = new stdClass;
1359 $bi->id = $block->instance->id;
1361 // This may get overwritten by the special case handling below.
1362 $bi->pagetypepattern = $data->bui_pagetypepattern;
1363 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1364 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1365 $bi->subpagepattern = null;
1366 } else {
1367 $bi->subpagepattern = $data->bui_subpagepattern;
1370 $systemcontext = context_system::instance();
1371 $frontpagecontext = context_course::instance(SITEID);
1372 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1374 // Updating stickiness and contexts. See MDL-21375 for details.
1375 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1377 // Explicitly set the default context
1378 $bi->parentcontextid = $parentcontext->id;
1380 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1382 // The interface here is a special case because the pagetype pattern is
1383 // totally derived from the context menu. Here are the excpetions. MDL-30340
1385 switch ($data->bui_contexts) {
1386 case BUI_CONTEXTS_ENTIRE_SITE:
1387 // The user wants to show the block across the entire site
1388 $bi->parentcontextid = $systemcontext->id;
1389 $bi->showinsubcontexts = true;
1390 $bi->pagetypepattern = '*';
1391 break;
1392 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1393 // The user wants the block shown on the front page and all subcontexts
1394 $bi->parentcontextid = $frontpagecontext->id;
1395 $bi->showinsubcontexts = true;
1396 $bi->pagetypepattern = '*';
1397 break;
1398 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1399 // The user want to show the front page on the frontpage only
1400 $bi->parentcontextid = $frontpagecontext->id;
1401 $bi->showinsubcontexts = false;
1402 $bi->pagetypepattern = 'site-index';
1403 // This is the only relevant page type anyway but we'll set it explicitly just
1404 // in case the front page grows site-index-* subpages of its own later
1405 break;
1410 $bits = explode('-', $bi->pagetypepattern);
1411 // hacks for some contexts
1412 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1413 // For course context
1414 // is page type pattern is mod-*, change showinsubcontext to 1
1415 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1416 $bi->showinsubcontexts = 1;
1417 } else {
1418 $bi->showinsubcontexts = 0;
1420 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1421 // for user context
1422 // subpagepattern should be null
1423 if ($bits[0] == 'user' or $bits[0] == 'my') {
1424 // we don't need subpagepattern in usercontext
1425 $bi->subpagepattern = null;
1429 $bi->defaultregion = $data->bui_defaultregion;
1430 $bi->defaultweight = $data->bui_defaultweight;
1431 $DB->update_record('block_instances', $bi);
1433 if (!empty($block->config)) {
1434 $config = clone($block->config);
1435 } else {
1436 $config = new stdClass;
1438 foreach ($data as $configfield => $value) {
1439 if (strpos($configfield, 'config_') !== 0) {
1440 continue;
1442 $field = substr($configfield, 7);
1443 $config->$field = $value;
1445 $block->instance_config_save($config);
1447 $bp = new stdClass;
1448 $bp->visible = $data->bui_visible;
1449 $bp->region = $data->bui_region;
1450 $bp->weight = $data->bui_weight;
1451 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1452 $data->bui_weight != $data->bui_defaultweight;
1454 if ($block->instance->blockpositionid && !$needbprecord) {
1455 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1457 } else if ($block->instance->blockpositionid && $needbprecord) {
1458 $bp->id = $block->instance->blockpositionid;
1459 $DB->update_record('block_positions', $bp);
1461 } else if ($needbprecord) {
1462 $bp->blockinstanceid = $block->instance->id;
1463 $bp->contextid = $this->page->context->id;
1464 $bp->pagetype = $this->page->pagetype;
1465 if ($this->page->subpage) {
1466 $bp->subpage = $this->page->subpage;
1467 } else {
1468 $bp->subpage = '';
1470 $DB->insert_record('block_positions', $bp);
1473 redirect($this->page->url);
1475 } else {
1476 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1477 $editpage->set_title($strheading);
1478 $editpage->set_heading($strheading);
1479 $bits = explode('-', $this->page->pagetype);
1480 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1481 // better navbar for tag pages
1482 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1483 $tag = tag_get('id', $this->page->subpage, '*');
1484 // tag search page doesn't have subpageid
1485 if ($tag) {
1486 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1489 $editpage->navbar->add($block->get_title());
1490 $editpage->navbar->add(get_string('configuration'));
1491 echo $output->header();
1492 echo $output->heading($strheading, 2);
1493 $mform->display();
1494 echo $output->footer();
1495 exit;
1500 * Handle showing/processing the submission from the block editing form.
1501 * @return boolean true if the form was submitted and the new config saved. Does not
1502 * return if the editing form was displayed. False otherwise.
1504 public function process_url_move() {
1505 global $CFG, $DB, $PAGE;
1507 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1508 if (!$blockid) {
1509 return false;
1512 require_sesskey();
1514 $block = $this->find_instance($blockid);
1516 if (!$this->page->user_can_edit_blocks()) {
1517 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1520 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1521 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1522 if (!$newregion || is_null($newweight)) {
1523 // Don't have a valid target position yet, must be just starting the move.
1524 $this->movingblock = $blockid;
1525 $this->page->ensure_param_not_in_url('bui_moveid');
1526 return false;
1529 if (!$this->is_known_region($newregion)) {
1530 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1533 // Move this block. This may involve moving other nearby blocks.
1534 $blocks = $this->birecordsbyregion[$newregion];
1536 $maxweight = self::MAX_WEIGHT;
1537 $minweight = -self::MAX_WEIGHT;
1539 // Initialise the used weights and spareweights array with the default values
1540 $spareweights = array();
1541 $usedweights = array();
1542 for ($i = $minweight; $i <= $maxweight; $i++) {
1543 $spareweights[$i] = $i;
1544 $usedweights[$i] = array();
1547 // Check each block and sort out where we have used weights
1548 foreach ($blocks as $bi) {
1549 if ($bi->weight > $maxweight) {
1550 // If this statement is true then the blocks weight is more than the
1551 // current maximum. To ensure that we can get the best block position
1552 // we will initialise elements within the usedweights and spareweights
1553 // arrays between the blocks weight (which will then be the new max) and
1554 // the current max
1555 $parseweight = $bi->weight;
1556 while (!array_key_exists($parseweight, $usedweights)) {
1557 $usedweights[$parseweight] = array();
1558 $spareweights[$parseweight] = $parseweight;
1559 $parseweight--;
1561 $maxweight = $bi->weight;
1562 } else if ($bi->weight < $minweight) {
1563 // As above except this time the blocks weight is LESS than the
1564 // the current minimum, so we will initialise the array from the
1565 // blocks weight (new minimum) to the current minimum
1566 $parseweight = $bi->weight;
1567 while (!array_key_exists($parseweight, $usedweights)) {
1568 $usedweights[$parseweight] = array();
1569 $spareweights[$parseweight] = $parseweight;
1570 $parseweight++;
1572 $minweight = $bi->weight;
1574 if ($bi->id != $block->instance->id) {
1575 unset($spareweights[$bi->weight]);
1576 $usedweights[$bi->weight][] = $bi->id;
1580 // First we find the nearest gap in the list of weights.
1581 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1582 $bestgap = null;
1583 foreach ($spareweights as $spareweight) {
1584 if (abs($newweight - $spareweight) < $bestdistance) {
1585 $bestdistance = abs($newweight - $spareweight);
1586 $bestgap = $spareweight;
1590 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1591 if (is_null($bestgap)) {
1592 $bestgap = self::MAX_WEIGHT + 1;
1593 while (!empty($usedweights[$bestgap])) {
1594 $bestgap++;
1598 // Now we know the gap we are aiming for, so move all the blocks along.
1599 if ($bestgap < $newweight) {
1600 $newweight = floor($newweight);
1601 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1602 if (array_key_exists($weight, $usedweights)) {
1603 foreach ($usedweights[$weight] as $biid) {
1604 $this->reposition_block($biid, $newregion, $weight - 1);
1608 $this->reposition_block($block->instance->id, $newregion, $newweight);
1609 } else {
1610 $newweight = ceil($newweight);
1611 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1612 if (array_key_exists($weight, $usedweights)) {
1613 foreach ($usedweights[$weight] as $biid) {
1614 $this->reposition_block($biid, $newregion, $weight + 1);
1618 $this->reposition_block($block->instance->id, $newregion, $newweight);
1621 $this->page->ensure_param_not_in_url('bui_moveid');
1622 $this->page->ensure_param_not_in_url('bui_newregion');
1623 $this->page->ensure_param_not_in_url('bui_newweight');
1624 return true;
1628 * Turns the display of normal blocks either on or off.
1630 * @param bool $setting
1632 public function show_only_fake_blocks($setting = true) {
1633 $this->fakeblocksonly = $setting;
1637 /// Helper functions for working with block classes ============================
1640 * Call a class method (one that does not require a block instance) on a block class.
1642 * @param string $blockname the name of the block.
1643 * @param string $method the method name.
1644 * @param array $param parameters to pass to the method.
1645 * @return mixed whatever the method returns.
1647 function block_method_result($blockname, $method, $param = NULL) {
1648 if(!block_load_class($blockname)) {
1649 return NULL;
1651 return call_user_func(array('block_'.$blockname, $method), $param);
1655 * Creates a new instance of the specified block class.
1657 * @param string $blockname the name of the block.
1658 * @param $instance block_instances DB table row (optional).
1659 * @param moodle_page $page the page this block is appearing on.
1660 * @return block_base the requested block instance.
1662 function block_instance($blockname, $instance = NULL, $page = NULL) {
1663 if(!block_load_class($blockname)) {
1664 return false;
1666 $classname = 'block_'.$blockname;
1667 $retval = new $classname;
1668 if($instance !== NULL) {
1669 if (is_null($page)) {
1670 global $PAGE;
1671 $page = $PAGE;
1673 $retval->_load_instance($instance, $page);
1675 return $retval;
1679 * Load the block class for a particular type of block.
1681 * @param string $blockname the name of the block.
1682 * @return boolean success or failure.
1684 function block_load_class($blockname) {
1685 global $CFG;
1687 if(empty($blockname)) {
1688 return false;
1691 $classname = 'block_'.$blockname;
1693 if(class_exists($classname)) {
1694 return true;
1697 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1699 if (file_exists($blockpath)) {
1700 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1701 include_once($blockpath);
1702 }else{
1703 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1704 return false;
1707 return class_exists($classname);
1711 * Given a specific page type, return all the page type patterns that might
1712 * match it.
1714 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1715 * @return array an array of all the page type patterns that might match this page type.
1717 function matching_page_type_patterns($pagetype) {
1718 $patterns = array($pagetype);
1719 $bits = explode('-', $pagetype);
1720 if (count($bits) == 3 && $bits[0] == 'mod') {
1721 if ($bits[2] == 'view') {
1722 $patterns[] = 'mod-*-view';
1723 } else if ($bits[2] == 'index') {
1724 $patterns[] = 'mod-*-index';
1727 while (count($bits) > 0) {
1728 $patterns[] = implode('-', $bits) . '-*';
1729 array_pop($bits);
1731 $patterns[] = '*';
1732 return $patterns;
1736 * Give an specific pattern, return all the page type patterns that would also match it.
1738 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
1739 * @return array of all the page type patterns matching.
1741 function matching_page_type_patterns_from_pattern($pattern) {
1742 $patterns = array($pattern);
1743 if ($pattern === '*') {
1744 return $patterns;
1747 // Only keep the part before the star because we will append -* to all the bits.
1748 $star = strpos($pattern, '-*');
1749 if ($star !== false) {
1750 $pattern = substr($pattern, 0, $star);
1753 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
1754 $patterns = array_unique($patterns);
1756 return $patterns;
1760 * Given a specific page type, parent context and currect context, return all the page type patterns
1761 * that might be used by this block.
1763 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1764 * @param stdClass $parentcontext Block's parent context
1765 * @param stdClass $currentcontext Current context of block
1766 * @return array an array of all the page type patterns that might match this page type.
1768 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1769 global $CFG; // Required for includes bellow.
1771 $bits = explode('-', $pagetype);
1773 $core = core_component::get_core_subsystems();
1774 $plugins = core_component::get_plugin_types();
1776 //progressively strip pieces off the page type looking for a match
1777 $componentarray = null;
1778 for ($i = count($bits); $i > 0; $i--) {
1779 $possiblecomponentarray = array_slice($bits, 0, $i);
1780 $possiblecomponent = implode('', $possiblecomponentarray);
1782 // Check to see if the component is a core component
1783 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1784 $libfile = $core[$possiblecomponent].'/lib.php';
1785 if (file_exists($libfile)) {
1786 require_once($libfile);
1787 $function = $possiblecomponent.'_page_type_list';
1788 if (function_exists($function)) {
1789 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1790 break;
1796 //check the plugin directory and look for a callback
1797 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1799 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1800 if (count($bits) > $i) {
1801 $pluginname = $bits[$i];
1802 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1803 if (!empty($directory)){
1804 $libfile = $directory.'/lib.php';
1805 if (file_exists($libfile)) {
1806 require_once($libfile);
1807 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1808 if (!function_exists($function)) {
1809 $function = $pluginname.'_page_type_list';
1811 if (function_exists($function)) {
1812 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1813 break;
1820 //we'll only get to here if we still don't have any patterns
1821 //the plugin type may have a callback
1822 $directory = $plugins[$possiblecomponent];
1823 $libfile = $directory.'/lib.php';
1824 if (file_exists($libfile)) {
1825 require_once($libfile);
1826 $function = $possiblecomponent.'_page_type_list';
1827 if (function_exists($function)) {
1828 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1829 break;
1836 if (empty($patterns)) {
1837 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1840 // Ensure that the * pattern is always available if editing block 'at distance', so
1841 // we always can 'bring back' it to the original context. MDL-30340
1842 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1843 // TODO: We could change the string here, showing its 'bring back' meaning
1844 $patterns['*'] = get_string('page-x', 'pagetype');
1847 return $patterns;
1851 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1853 * @param string $pagetype
1854 * @param stdClass $parentcontext
1855 * @param stdClass $currentcontext
1856 * @return array
1858 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1859 // Generate page type patterns based on current page type if
1860 // callbacks haven't been defined
1861 $patterns = array($pagetype => $pagetype);
1862 $bits = explode('-', $pagetype);
1863 while (count($bits) > 0) {
1864 $pattern = implode('-', $bits) . '-*';
1865 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1866 // guessing page type description
1867 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1868 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1869 } else {
1870 $patterns[$pattern] = $pattern;
1872 array_pop($bits);
1874 $patterns['*'] = get_string('page-x', 'pagetype');
1875 return $patterns;
1879 * Generates the page type list for the my moodle page
1881 * @param string $pagetype
1882 * @param stdClass $parentcontext
1883 * @param stdClass $currentcontext
1884 * @return array
1886 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1887 return array('my-index' => get_string('page-my-index', 'pagetype'));
1891 * Generates the page type list for a module by either locating and using the modules callback
1892 * or by generating a default list.
1894 * @param string $pagetype
1895 * @param stdClass $parentcontext
1896 * @param stdClass $currentcontext
1897 * @return array
1899 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1900 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1901 if (empty($patterns)) {
1902 // if modules don't have callbacks
1903 // generate two default page type patterns for modules only
1904 $bits = explode('-', $pagetype);
1905 $patterns = array($pagetype => $pagetype);
1906 if ($bits[2] == 'view') {
1907 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1908 } else if ($bits[2] == 'index') {
1909 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1912 return $patterns;
1914 /// Functions update the blocks if required by the request parameters ==========
1917 * Return a {@link block_contents} representing the add a new block UI, if
1918 * this user is allowed to see it.
1920 * @return block_contents an appropriate block_contents, or null if the user
1921 * cannot add any blocks here.
1923 function block_add_block_ui($page, $output) {
1924 global $CFG, $OUTPUT;
1925 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1926 return null;
1929 $bc = new block_contents();
1930 $bc->title = get_string('addblock');
1931 $bc->add_class('block_adminblock');
1932 $bc->attributes['data-block'] = 'adminblock';
1934 $missingblocks = $page->blocks->get_addable_blocks();
1935 if (empty($missingblocks)) {
1936 $bc->content = get_string('noblockstoaddhere');
1937 return $bc;
1940 $menu = array();
1941 foreach ($missingblocks as $block) {
1942 $blockobject = block_instance($block->name);
1943 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1944 $menu[$block->name] = $blockobject->get_title();
1947 core_collator::asort($menu);
1949 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1950 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1951 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1952 $bc->content = $OUTPUT->render($select);
1953 return $bc;
1957 * Actually delete from the database any blocks that are currently on this page,
1958 * but which should not be there according to blocks_name_allowed_in_format.
1960 * @todo Write/Fix this function. Currently returns immediately
1961 * @param $course
1963 function blocks_remove_inappropriate($course) {
1964 // TODO
1965 return;
1967 $blockmanager = blocks_get_by_page($page);
1969 if (empty($blockmanager)) {
1970 return;
1973 if (($pageformat = $page->pagetype) == NULL) {
1974 return;
1977 foreach($blockmanager as $region) {
1978 foreach($region as $instance) {
1979 $block = blocks_get_record($instance->blockid);
1980 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1981 blocks_delete_instance($instance->instance);
1988 * Check that a given name is in a permittable format
1990 * @param string $name
1991 * @param string $pageformat
1992 * @return bool
1994 function blocks_name_allowed_in_format($name, $pageformat) {
1995 $accept = NULL;
1996 $maxdepth = -1;
1997 if (!$bi = block_instance($name)) {
1998 return false;
2001 $formats = $bi->applicable_formats();
2002 if (!$formats) {
2003 $formats = array();
2005 foreach ($formats as $format => $allowed) {
2006 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2007 $depth = substr_count($format, '-');
2008 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2009 $maxdepth = $depth;
2010 $accept = $allowed;
2013 if ($accept === NULL) {
2014 $accept = !empty($formats['all']);
2016 return $accept;
2020 * Delete a block, and associated data.
2022 * @param object $instance a row from the block_instances table
2023 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2024 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2026 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2027 global $DB;
2029 if ($block = block_instance($instance->blockname, $instance)) {
2030 $block->instance_delete();
2032 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2034 if (!$skipblockstables) {
2035 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2036 $DB->delete_records('block_instances', array('id' => $instance->id));
2037 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2042 * Delete all the blocks that belong to a particular context.
2044 * @param int $contextid the context id.
2046 function blocks_delete_all_for_context($contextid) {
2047 global $DB;
2048 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2049 foreach ($instances as $instance) {
2050 blocks_delete_instance($instance, true);
2052 $instances->close();
2053 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2054 $DB->delete_records('block_positions', array('contextid' => $contextid));
2058 * Set a block to be visible or hidden on a particular page.
2060 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2061 * block_positions table as return by block_manager.
2062 * @param moodle_page $page the back to set the visibility with respect to.
2063 * @param integer $newvisibility 1 for visible, 0 for hidden.
2065 function blocks_set_visibility($instance, $page, $newvisibility) {
2066 global $DB;
2067 if (!empty($instance->blockpositionid)) {
2068 // Already have local information on this page.
2069 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2070 return;
2073 // Create a new block_positions record.
2074 $bp = new stdClass;
2075 $bp->blockinstanceid = $instance->id;
2076 $bp->contextid = $page->context->id;
2077 $bp->pagetype = $page->pagetype;
2078 if ($page->subpage) {
2079 $bp->subpage = $page->subpage;
2081 $bp->visible = $newvisibility;
2082 $bp->region = $instance->defaultregion;
2083 $bp->weight = $instance->defaultweight;
2084 $DB->insert_record('block_positions', $bp);
2088 * Get the block record for a particular blockid - that is, a particular type os block.
2090 * @param $int blockid block type id. If null, an array of all block types is returned.
2091 * @param bool $notusedanymore No longer used.
2092 * @return array|object row from block table, or all rows.
2094 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2095 global $PAGE;
2096 $blocks = $PAGE->blocks->get_installed_blocks();
2097 if ($blockid === NULL) {
2098 return $blocks;
2099 } else if (isset($blocks[$blockid])) {
2100 return $blocks[$blockid];
2101 } else {
2102 return false;
2107 * Find a given block by its blockid within a provide array
2109 * @param int $blockid
2110 * @param array $blocksarray
2111 * @return bool|object Instance if found else false
2113 function blocks_find_block($blockid, $blocksarray) {
2114 if (empty($blocksarray)) {
2115 return false;
2117 foreach($blocksarray as $blockgroup) {
2118 if (empty($blockgroup)) {
2119 continue;
2121 foreach($blockgroup as $instance) {
2122 if($instance->blockid == $blockid) {
2123 return $instance;
2127 return false;
2130 // Functions for programatically adding default blocks to pages ================
2133 * Parse a list of default blocks. See config-dist for a description of the format.
2135 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2136 * @return array the parsed list of default blocks
2138 function blocks_parse_default_blocks_list($blocksstr) {
2139 $blocks = array();
2140 $bits = explode(':', $blocksstr);
2141 if (!empty($bits)) {
2142 $leftbits = trim(array_shift($bits));
2143 if ($leftbits != '') {
2144 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2147 if (!empty($bits)) {
2148 $rightbits = trim(array_shift($bits));
2149 if ($rightbits != '') {
2150 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2153 return $blocks;
2157 * @return array the blocks that should be added to the site course by default.
2159 function blocks_get_default_site_course_blocks() {
2160 global $CFG;
2162 if (!empty($CFG->defaultblocks_site)) {
2163 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2164 } else {
2165 return array(
2166 BLOCK_POS_LEFT => array('site_main_menu'),
2167 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2173 * Add the default blocks to a course.
2175 * @param object $course a course object.
2177 function blocks_add_default_course_blocks($course) {
2178 global $CFG;
2180 if (!empty($CFG->defaultblocks_override)) {
2181 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2183 } else if ($course->id == SITEID) {
2184 $blocknames = blocks_get_default_site_course_blocks();
2186 } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2187 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2189 } else {
2190 require_once($CFG->dirroot. '/course/lib.php');
2191 $blocknames = course_get_format($course)->get_default_blocks();
2195 if ($course->id == SITEID) {
2196 $pagetypepattern = 'site-index';
2197 } else {
2198 $pagetypepattern = 'course-view-*';
2200 $page = new moodle_page();
2201 $page->set_course($course);
2202 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2206 * Add the default system-context blocks. E.g. the admin tree.
2208 function blocks_add_default_system_blocks() {
2209 global $DB;
2211 $page = new moodle_page();
2212 $page->set_context(context_system::instance());
2213 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2214 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2216 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2217 $subpagepattern = $defaultmypage->id;
2218 } else {
2219 $subpagepattern = null;
2222 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2223 $newcontent = array('course_overview');
2224 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);