MDL-10115 User profile: Allow full list of courses to be viewed on a user's profile
[moodle.git] / lib / blocklib.php
blobafd6cb09db38c5cb706cf77cdb4c308d9434b738
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 * @deprecated since Moodle 2.0. No longer used.
34 define('BLOCK_MOVE_LEFT', 0x01);
35 define('BLOCK_MOVE_RIGHT', 0x02);
36 define('BLOCK_MOVE_UP', 0x04);
37 define('BLOCK_MOVE_DOWN', 0x08);
38 define('BLOCK_CONFIGURE', 0x10);
39 /**#@-*/
41 /**#@+
42 * Default names for the block regions in the standard theme.
44 define('BLOCK_POS_LEFT', 'side-pre');
45 define('BLOCK_POS_RIGHT', 'side-post');
46 /**#@-*/
48 /**#@+
49 * @deprecated since Moodle 2.0. No longer used.
51 define('BLOCKS_PINNED_TRUE',0);
52 define('BLOCKS_PINNED_FALSE',1);
53 define('BLOCKS_PINNED_BOTH',2);
54 /**#@-*/
56 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
57 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
58 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
60 define('BUI_CONTEXTS_CURRENT', 0);
61 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
63 /**
64 * Exception thrown when someone tried to do something with a block that does
65 * not exist on a page.
67 * @copyright 2009 Tim Hunt
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
69 * @since Moodle 2.0
71 class block_not_on_page_exception extends moodle_exception {
72 /**
73 * Constructor
74 * @param int $instanceid the block instance id of the block that was looked for.
75 * @param object $page the current page.
77 public function __construct($instanceid, $page) {
78 $a = new stdClass;
79 $a->instanceid = $instanceid;
80 $a->url = $page->url->out();
81 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
85 /**
86 * This class keeps track of the block that should appear on a moodle_page.
88 * The page to work with as passed to the constructor.
90 * @copyright 2009 Tim Hunt
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 * @since Moodle 2.0
94 class block_manager {
95 /**
96 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
97 * although other weights are valid.
99 const MAX_WEIGHT = 10;
101 /// Field declarations =========================================================
104 * the moodle_page we are managing blocks for.
105 * @var moodle_page
107 protected $page;
109 /** @var array region name => 1.*/
110 protected $regions = array();
112 /** @var string the region where new blocks are added.*/
113 protected $defaultregion = null;
115 /** @var array will be $DB->get_records('blocks') */
116 protected $allblocks = null;
119 * @var array blocks that this user can add to this page. Will be a subset
120 * of $allblocks, but with array keys block->name. Access this via the
121 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
123 protected $addableblocks = null;
126 * Will be an array region-name => array(db rows loaded in load_blocks);
127 * @var array
129 protected $birecordsbyregion = null;
132 * array region-name => array(block objects); populated as necessary by
133 * the ensure_instances_exist method.
134 * @var array
136 protected $blockinstances = array();
139 * array region-name => array(block_contents objects) what actually needs to
140 * be displayed in each region.
141 * @var array
143 protected $visibleblockcontent = array();
146 * array region-name => array(block_contents objects) extra block-like things
147 * to be displayed in each region, before the real blocks.
148 * @var array
150 protected $extracontent = array();
153 * Used by the block move id, to track whether a block is currently being moved.
155 * When you click on the move icon of a block, first the page needs to reload with
156 * extra UI for choosing a new position for a particular block. In that situation
157 * this field holds the id of the block being moved.
159 * @var integer|null
161 protected $movingblock = null;
164 * Show only fake blocks
166 protected $fakeblocksonly = false;
168 /// Constructor ================================================================
171 * Constructor.
172 * @param object $page the moodle_page object object we are managing the blocks for,
173 * or a reasonable faxilimily. (See the comment at the top of this class
174 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
176 public function __construct($page) {
177 $this->page = $page;
180 /// Getter methods =============================================================
183 * Get an array of all region names on this page where a block may appear
185 * @return array the internal names of the regions on this page where block may appear.
187 public function get_regions() {
188 if (is_null($this->defaultregion)) {
189 $this->page->initialise_theme_and_output();
191 return array_keys($this->regions);
195 * Get the region name of the region blocks are added to by default
197 * @return string the internal names of the region where new blocks are added
198 * by default, and where any blocks from an unrecognised region are shown.
199 * (Imagine that blocks were added with one theme selected, then you switched
200 * to a theme with different block positions.)
202 public function get_default_region() {
203 $this->page->initialise_theme_and_output();
204 return $this->defaultregion;
208 * The list of block types that may be added to this page.
210 * @return array block name => record from block table.
212 public function get_addable_blocks() {
213 $this->check_is_loaded();
215 if (!is_null($this->addableblocks)) {
216 return $this->addableblocks;
219 // Lazy load.
220 $this->addableblocks = array();
222 $allblocks = blocks_get_record();
223 if (empty($allblocks)) {
224 return $this->addableblocks;
227 $unaddableblocks = self::get_undeletable_block_types();
228 $pageformat = $this->page->pagetype;
229 foreach($allblocks as $block) {
230 if (!$bi = block_instance($block->name)) {
231 continue;
233 if ($block->visible && !in_array($block->name, $unaddableblocks) &&
234 ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
235 blocks_name_allowed_in_format($block->name, $pageformat) &&
236 $bi->user_can_addto($this->page)) {
237 $this->addableblocks[$block->name] = $block;
241 return $this->addableblocks;
245 * Given a block name, find out of any of them are currently present in the page
247 * @param string $blockname - the basic name of a block (eg "navigation")
248 * @return boolean - is there one of these blocks in the current page?
250 public function is_block_present($blockname) {
251 if (empty($this->blockinstances)) {
252 return false;
255 foreach ($this->blockinstances as $region) {
256 foreach ($region as $instance) {
257 if (empty($instance->instance->blockname)) {
258 continue;
260 if ($instance->instance->blockname == $blockname) {
261 return true;
265 return false;
269 * Find out if a block type is known by the system
271 * @param string $blockname the name of the type of block.
272 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
273 * @return boolean true if this block in installed.
275 public function is_known_block_type($blockname, $includeinvisible = false) {
276 $blocks = $this->get_installed_blocks();
277 foreach ($blocks as $block) {
278 if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
279 return true;
282 return false;
286 * Find out if a region exists on a page
288 * @param string $region a region name
289 * @return boolean true if this region exists on this page.
291 public function is_known_region($region) {
292 return array_key_exists($region, $this->regions);
296 * Get an array of all blocks within a given region
298 * @param string $region a block region that exists on this page.
299 * @return array of block instances.
301 public function get_blocks_for_region($region) {
302 $this->check_is_loaded();
303 $this->ensure_instances_exist($region);
304 return $this->blockinstances[$region];
308 * Returns an array of block content objects that exist in a region
310 * @param string $region a block region that exists on this page.
311 * @return array of block block_contents objects for all the blocks in a region.
313 public function get_content_for_region($region, $output) {
314 $this->check_is_loaded();
315 $this->ensure_content_created($region, $output);
316 return $this->visibleblockcontent[$region];
320 * Helper method used by get_content_for_region.
321 * @param string $region region name
322 * @param float $weight weight. May be fractional, since you may want to move a block
323 * between ones with weight 2 and 3, say ($weight would be 2.5).
324 * @return string URL for moving block $this->movingblock to this position.
326 protected function get_move_target_url($region, $weight) {
327 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
328 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
332 * Determine whether a region contains anything. (Either any real blocks, or
333 * the add new block UI.)
335 * (You may wonder why the $output parameter is required. Unfortunately,
336 * because of the way that blocks work, the only reliable way to find out
337 * if a block will be visible is to get the content for output, and to
338 * get the content, you need a renderer. Fortunately, this is not a
339 * performance problem, because we cache the output that is generated, and
340 * in almost every case where we call region_has_content, we are about to
341 * output the blocks anyway, so we are not doing wasted effort.)
343 * @param string $region a block region that exists on this page.
344 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
345 * @return boolean Whether there is anything in this region.
347 public function region_has_content($region, $output) {
349 if (!$this->is_known_region($region)) {
350 return false;
352 $this->check_is_loaded();
353 $this->ensure_content_created($region, $output);
354 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
355 // Mark Nielsen's patch - part 1
356 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
357 // If editing is on, we need all the block regions visible, for the
358 // move blocks UI.
359 return true;
361 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
365 * Get an array of all of the installed blocks.
367 * @return array contents of the block table.
369 public function get_installed_blocks() {
370 global $DB;
371 if (is_null($this->allblocks)) {
372 $this->allblocks = $DB->get_records('block');
374 return $this->allblocks;
378 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
380 public static function get_undeletable_block_types() {
381 global $CFG;
383 if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
384 return array('navigation','settings');
385 } else if (is_string($CFG->undeletableblocktypes)) {
386 return explode(',', $CFG->undeletableblocktypes);
387 } else {
388 return $CFG->undeletableblocktypes;
392 /// Setter methods =============================================================
395 * Add a region to a page
397 * @param string $region add a named region where blocks may appear on the current page.
398 * This is an internal name, like 'side-pre', not a string to display in the UI.
399 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
401 public function add_region($region, $custom = true) {
402 global $SESSION;
403 $this->check_not_yet_loaded();
404 if ($custom) {
405 if (array_key_exists($region, $this->regions)) {
406 // This here is EXACTLY why we should not be adding block regions into a page. It should
407 // ALWAYS be done in a theme layout.
408 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
410 // We need to register this custom region against the page type being used.
411 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
412 $type = $this->page->pagetype;
413 if (!isset($SESSION->custom_block_regions)) {
414 $SESSION->custom_block_regions = array($type => array($region));
415 } else if (!isset($SESSION->custom_block_regions[$type])) {
416 $SESSION->custom_block_regions[$type] = array($region);
417 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
418 $SESSION->custom_block_regions[$type][] = $region;
421 $this->regions[$region] = 1;
425 * Add an array of regions
426 * @see add_region()
428 * @param array $regions this utility method calls add_region for each array element.
430 public function add_regions($regions, $custom = true) {
431 foreach ($regions as $region) {
432 $this->add_region($region, $custom);
437 * Finds custom block regions associated with a page type and registers them with this block manager.
439 * @param string $pagetype
441 public function add_custom_regions_for_pagetype($pagetype) {
442 global $SESSION;
443 if (isset($SESSION->custom_block_regions[$pagetype])) {
444 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
445 $this->add_region($customregion, false);
451 * Set the default region for new blocks on the page
453 * @param string $defaultregion the internal names of the region where new
454 * blocks should be added by default, and where any blocks from an
455 * unrecognised region are shown.
457 public function set_default_region($defaultregion) {
458 $this->check_not_yet_loaded();
459 if ($defaultregion) {
460 $this->check_region_is_known($defaultregion);
462 $this->defaultregion = $defaultregion;
466 * Add something that looks like a block, but which isn't an actual block_instance,
467 * to this page.
469 * @param block_contents $bc the content of the block-like thing.
470 * @param string $region a block region that exists on this page.
472 public function add_fake_block($bc, $region) {
473 $this->page->initialise_theme_and_output();
474 if (!$this->is_known_region($region)) {
475 $region = $this->get_default_region();
477 if (array_key_exists($region, $this->visibleblockcontent)) {
478 throw new coding_exception('block_manager has already prepared the blocks in region ' .
479 $region . 'for output. It is too late to add a fake block.');
481 if (!isset($bc->attributes['data-block'])) {
482 $bc->attributes['data-block'] = '_fake';
484 $bc->attributes['class'] .= ' block_fake';
485 $this->extracontent[$region][] = $bc;
489 * When the block_manager class was created, the {@link add_fake_block()}
490 * was called add_pretend_block, which is inconsisted with
491 * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
492 * was renamed to add_fake_block. Please update your code.
493 * @param block_contents $bc the content of the block-like thing.
494 * @param string $region a block region that exists on this page.
496 public function add_pretend_block($bc, $region) {
497 debugging(DEBUG_DEVELOPER, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
498 $this->add_fake_block($bc, $region);
502 * Checks to see whether all of the blocks within the given region are docked
504 * @see region_uses_dock
505 * @param string $region
506 * @return bool True if all of the blocks within that region are docked
508 public function region_completely_docked($region, $output) {
509 global $CFG;
510 // If theme doesn't allow docking or allowblockstodock is not set, then return.
511 if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
512 return false;
515 // Do not dock the region when the user attemps to move a block.
516 if ($this->movingblock) {
517 return false;
520 $this->check_is_loaded();
521 $this->ensure_content_created($region, $output);
522 if (!$this->region_has_content($region, $output)) {
523 // If the region has no content then nothing is docked at all of course.
524 return false;
526 foreach ($this->visibleblockcontent[$region] as $instance) {
527 if (!empty($instance->content) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
528 return false;
531 return true;
535 * Checks to see whether any of the blocks within the given regions are docked
537 * @see region_completely_docked
538 * @param array|string $regions array of regions (or single region)
539 * @return bool True if any of the blocks within that region are docked
541 public function region_uses_dock($regions, $output) {
542 if (!$this->page->theme->enable_dock) {
543 return false;
545 $this->check_is_loaded();
546 foreach((array)$regions as $region) {
547 $this->ensure_content_created($region, $output);
548 foreach($this->visibleblockcontent[$region] as $instance) {
549 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
550 return true;
554 return false;
557 /// Actions ====================================================================
560 * This method actually loads the blocks for our page from the database.
562 * @param boolean|null $includeinvisible
563 * null (default) - load hidden blocks if $this->page->user_is_editing();
564 * true - load hidden blocks.
565 * false - don't load hidden blocks.
567 public function load_blocks($includeinvisible = null) {
568 global $DB, $CFG;
570 if (!is_null($this->birecordsbyregion)) {
571 // Already done.
572 return;
575 if ($CFG->version < 2009050619) {
576 // Upgrade/install not complete. Don't try too show any blocks.
577 $this->birecordsbyregion = array();
578 return;
581 // Ensure we have been initialised.
582 if (is_null($this->defaultregion)) {
583 $this->page->initialise_theme_and_output();
584 // If there are still no block regions, then there are no blocks on this page.
585 if (empty($this->regions)) {
586 $this->birecordsbyregion = array();
587 return;
591 // Check if we need to load normal blocks
592 if ($this->fakeblocksonly) {
593 $this->birecordsbyregion = $this->prepare_per_region_arrays();
594 return;
597 if (is_null($includeinvisible)) {
598 $includeinvisible = $this->page->user_is_editing();
600 if ($includeinvisible) {
601 $visiblecheck = '';
602 } else {
603 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
606 $context = $this->page->context;
607 $contexttest = 'bi.parentcontextid = :contextid2';
608 $parentcontextparams = array();
609 $parentcontextids = $context->get_parent_context_ids();
610 if ($parentcontextids) {
611 list($parentcontexttest, $parentcontextparams) =
612 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
613 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
616 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
617 list($pagetypepatterntest, $pagetypepatternparams) =
618 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
620 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
621 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
623 $params = array(
624 'contextlevel' => CONTEXT_BLOCK,
625 'subpage1' => $this->page->subpage,
626 'subpage2' => $this->page->subpage,
627 'contextid1' => $context->id,
628 'contextid2' => $context->id,
629 'pagetype' => $this->page->pagetype,
631 if ($this->page->subpage === '') {
632 $params['subpage1'] = '';
633 $params['subpage2'] = '';
635 $sql = "SELECT
636 bi.id,
637 bp.id AS blockpositionid,
638 bi.blockname,
639 bi.parentcontextid,
640 bi.showinsubcontexts,
641 bi.pagetypepattern,
642 bi.subpagepattern,
643 bi.defaultregion,
644 bi.defaultweight,
645 COALESCE(bp.visible, 1) AS visible,
646 COALESCE(bp.region, bi.defaultregion) AS region,
647 COALESCE(bp.weight, bi.defaultweight) AS weight,
648 bi.configdata
649 $ccselect
651 FROM {block_instances} bi
652 JOIN {block} b ON bi.blockname = b.name
653 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
654 AND bp.contextid = :contextid1
655 AND bp.pagetype = :pagetype
656 AND bp.subpage = :subpage1
657 $ccjoin
659 WHERE
660 $contexttest
661 AND bi.pagetypepattern $pagetypepatterntest
662 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
663 $visiblecheck
664 AND b.visible = 1
666 ORDER BY
667 COALESCE(bp.region, bi.defaultregion),
668 COALESCE(bp.weight, bi.defaultweight),
669 bi.id";
670 $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
672 $this->birecordsbyregion = $this->prepare_per_region_arrays();
673 $unknown = array();
674 foreach ($blockinstances as $bi) {
675 context_helper::preload_from_record($bi);
676 if ($this->is_known_region($bi->region)) {
677 $this->birecordsbyregion[$bi->region][] = $bi;
678 } else {
679 $unknown[] = $bi;
683 // Pages don't necessarily have a defaultregion. The one time this can
684 // happen is when there are no theme block regions, but the script itself
685 // has a block region in the main content area.
686 if (!empty($this->defaultregion)) {
687 $this->birecordsbyregion[$this->defaultregion] =
688 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
693 * Add a block to the current page, or related pages. The block is added to
694 * context $this->page->contextid. If $pagetypepattern $subpagepattern
696 * @param string $blockname The type of block to add.
697 * @param string $region the block region on this page to add the block to.
698 * @param integer $weight determines the order where this block appears in the region.
699 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
700 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
701 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
703 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
704 global $DB;
705 // Allow invisible blocks because this is used when adding default page blocks, which
706 // might include invisible ones if the user makes some default blocks invisible
707 $this->check_known_block_type($blockname, true);
708 $this->check_region_is_known($region);
710 if (empty($pagetypepattern)) {
711 $pagetypepattern = $this->page->pagetype;
714 $blockinstance = new stdClass;
715 $blockinstance->blockname = $blockname;
716 $blockinstance->parentcontextid = $this->page->context->id;
717 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
718 $blockinstance->pagetypepattern = $pagetypepattern;
719 $blockinstance->subpagepattern = $subpagepattern;
720 $blockinstance->defaultregion = $region;
721 $blockinstance->defaultweight = $weight;
722 $blockinstance->configdata = '';
723 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
725 // Ensure the block context is created.
726 context_block::instance($blockinstance->id);
728 // If the new instance was created, allow it to do additional setup
729 if ($block = block_instance($blockname, $blockinstance)) {
730 $block->instance_create();
734 public function add_block_at_end_of_default_region($blockname) {
735 $defaulregion = $this->get_default_region();
737 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
738 if ($lastcurrentblock) {
739 $weight = $lastcurrentblock->weight + 1;
740 } else {
741 $weight = 0;
744 if ($this->page->subpage) {
745 $subpage = $this->page->subpage;
746 } else {
747 $subpage = null;
750 // Special case. Course view page type include the course format, but we
751 // want to add the block non-format-specifically.
752 $pagetypepattern = $this->page->pagetype;
753 if (strpos($pagetypepattern, 'course-view') === 0) {
754 $pagetypepattern = 'course-view-*';
757 // We should end using this for ALL the blocks, making always the 1st option
758 // the default one to be used. Until then, this is one hack to avoid the
759 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
760 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
761 // (the FIRST $pagetypepattern will be set)
763 // We are applying it to all blocks created in mod pages for now and only if the
764 // default pagetype is not one of the available options
765 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
766 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
767 // Only go for the first if the pagetype is not a valid option
768 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
769 $pagetypepattern = key($pagetypelist);
772 // Surely other pages like course-report will need this too, they just are not important
773 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
775 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
779 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
781 * @param array $blocks array with array keys the region names, and values an array of block names.
782 * @param string $pagetypepattern optional. Passed to @see add_block()
783 * @param string $subpagepattern optional. Passed to @see add_block()
785 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
786 $this->add_regions(array_keys($blocks), false);
787 foreach ($blocks as $region => $regionblocks) {
788 $weight = 0;
789 foreach ($regionblocks as $blockname) {
790 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
791 $weight += 1;
797 * Move a block to a new position on this page.
799 * If this block cannot appear on any other pages, then we change defaultposition/weight
800 * in the block_instances table. Otherwise we just set the position on this page.
802 * @param $blockinstanceid the block instance id.
803 * @param $newregion the new region name.
804 * @param $newweight the new weight.
806 public function reposition_block($blockinstanceid, $newregion, $newweight) {
807 global $DB;
809 $this->check_region_is_known($newregion);
810 $inst = $this->find_instance($blockinstanceid);
812 $bi = $inst->instance;
813 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
814 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
815 (!$this->page->subpage || $bi->subpagepattern)) {
817 // Set default position
818 $newbi = new stdClass;
819 $newbi->id = $bi->id;
820 $newbi->defaultregion = $newregion;
821 $newbi->defaultweight = $newweight;
822 $DB->update_record('block_instances', $newbi);
824 if ($bi->blockpositionid) {
825 $bp = new stdClass;
826 $bp->id = $bi->blockpositionid;
827 $bp->region = $newregion;
828 $bp->weight = $newweight;
829 $DB->update_record('block_positions', $bp);
832 } else {
833 // Just set position on this page.
834 $bp = new stdClass;
835 $bp->region = $newregion;
836 $bp->weight = $newweight;
838 if ($bi->blockpositionid) {
839 $bp->id = $bi->blockpositionid;
840 $DB->update_record('block_positions', $bp);
842 } else {
843 $bp->blockinstanceid = $bi->id;
844 $bp->contextid = $this->page->context->id;
845 $bp->pagetype = $this->page->pagetype;
846 if ($this->page->subpage) {
847 $bp->subpage = $this->page->subpage;
848 } else {
849 $bp->subpage = '';
851 $bp->visible = $bi->visible;
852 $DB->insert_record('block_positions', $bp);
858 * Find a given block by its instance id
860 * @param integer $instanceid
861 * @return block_base
863 public function find_instance($instanceid) {
864 foreach ($this->regions as $region => $notused) {
865 $this->ensure_instances_exist($region);
866 foreach($this->blockinstances[$region] as $instance) {
867 if ($instance->instance->id == $instanceid) {
868 return $instance;
872 throw new block_not_on_page_exception($instanceid, $this->page);
875 /// Inner workings =============================================================
878 * Check whether the page blocks have been loaded yet
880 * @return void Throws coding exception if already loaded
882 protected function check_not_yet_loaded() {
883 if (!is_null($this->birecordsbyregion)) {
884 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.');
889 * Check whether the page blocks have been loaded yet
891 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
893 * @return void Throws coding exception if already loaded
895 protected function check_is_loaded() {
896 if (is_null($this->birecordsbyregion)) {
897 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
902 * Check if a block type is known and usable
904 * @param string $blockname The block type name to search for
905 * @param bool $includeinvisible Include disabled block types in the initial pass
906 * @return void Coding Exception thrown if unknown or not enabled
908 protected function check_known_block_type($blockname, $includeinvisible = false) {
909 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
910 if ($this->is_known_block_type($blockname, true)) {
911 throw new coding_exception('Unknown block type ' . $blockname);
912 } else {
913 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
919 * Check if a region is known by its name
921 * @param string $region
922 * @return void Coding Exception thrown if the region is not known
924 protected function check_region_is_known($region) {
925 if (!$this->is_known_region($region)) {
926 throw new coding_exception('Trying to reference an unknown block region ' . $region);
931 * Returns an array of region names as keys and nested arrays for values
933 * @return array an array where the array keys are the region names, and the array
934 * values are empty arrays.
936 protected function prepare_per_region_arrays() {
937 $result = array();
938 foreach ($this->regions as $region => $notused) {
939 $result[$region] = array();
941 return $result;
945 * Create a set of new block instance from a record array
947 * @param array $birecords An array of block instance records
948 * @return array An array of instantiated block_instance objects
950 protected function create_block_instances($birecords) {
951 $results = array();
952 foreach ($birecords as $record) {
953 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
954 $results[] = $blockobject;
957 return $results;
961 * Create all the block instances for all the blocks that were loaded by
962 * load_blocks. This is used, for example, to ensure that all blocks get a
963 * chance to initialise themselves via the {@link block_base::specialize()}
964 * method, before any output is done.
966 public function create_all_block_instances() {
967 foreach ($this->get_regions() as $region) {
968 $this->ensure_instances_exist($region);
973 * Return an array of content objects from a set of block instances
975 * @param array $instances An array of block instances
976 * @param renderer_base The renderer to use.
977 * @param string $region the region name.
978 * @return array An array of block_content (and possibly block_move_target) objects.
980 protected function create_block_contents($instances, $output, $region) {
981 $results = array();
983 $lastweight = 0;
984 $lastblock = 0;
985 if ($this->movingblock) {
986 $first = reset($instances);
987 if ($first) {
988 $lastweight = $first->instance->weight - 2;
992 foreach ($instances as $instance) {
993 $content = $instance->get_content_for_output($output);
994 if (empty($content)) {
995 continue;
998 if ($this->movingblock && $lastweight != $instance->instance->weight &&
999 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
1000 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
1003 if ($content->blockinstanceid == $this->movingblock) {
1004 $content->add_class('beingmoved');
1005 $content->annotation .= get_string('movingthisblockcancel', 'block',
1006 html_writer::link($this->page->url, get_string('cancel')));
1009 $results[] = $content;
1010 $lastweight = $instance->instance->weight;
1011 $lastblock = $instance->instance->id;
1014 if ($this->movingblock && $lastblock != $this->movingblock) {
1015 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
1017 return $results;
1021 * Ensure block instances exist for a given region
1023 * @param string $region Check for bi's with the instance with this name
1025 protected function ensure_instances_exist($region) {
1026 $this->check_region_is_known($region);
1027 if (!array_key_exists($region, $this->blockinstances)) {
1028 $this->blockinstances[$region] =
1029 $this->create_block_instances($this->birecordsbyregion[$region]);
1034 * Ensure that there is some content within the given region
1036 * @param string $region The name of the region to check
1038 public function ensure_content_created($region, $output) {
1039 $this->ensure_instances_exist($region);
1040 if (!array_key_exists($region, $this->visibleblockcontent)) {
1041 $contents = array();
1042 if (array_key_exists($region, $this->extracontent)) {
1043 $contents = $this->extracontent[$region];
1045 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1046 if ($region == $this->defaultregion) {
1047 $addblockui = block_add_block_ui($this->page, $output);
1048 if ($addblockui) {
1049 $contents[] = $addblockui;
1052 $this->visibleblockcontent[$region] = $contents;
1056 /// Process actions from the URL ===============================================
1059 * Get the appropriate list of editing icons for a block. This is used
1060 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1062 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1063 * @return an array in the format for {@link block_contents::$controls}
1065 public function edit_controls($block) {
1066 global $CFG;
1068 $controls = array();
1069 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1070 $blocktitle = $block->title;
1071 if (empty($blocktitle)) {
1072 $blocktitle = $block->arialabel;
1075 if ($this->page->user_can_edit_blocks()) {
1076 // Move icon.
1077 $str = new lang_string('moveblock', 'block', $blocktitle);
1078 $controls[] = new action_menu_link_primary(
1079 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1080 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1081 $str,
1082 array('class' => 'editing_move')
1087 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1088 // Edit config icon - always show - needed for positioning UI.
1089 $str = new lang_string('configureblock', 'block', $blocktitle);
1090 $controls[] = new action_menu_link_secondary(
1091 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1092 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1093 $str,
1094 array('class' => 'editing_edit')
1099 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1100 // Show/hide icon.
1101 if ($block->instance->visible) {
1102 $str = new lang_string('hideblock', 'block', $blocktitle);
1103 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1104 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1105 $attributes = array('class' => 'editing_hide');
1106 } else {
1107 $str = new lang_string('showblock', 'block', $blocktitle);
1108 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1109 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1110 $attributes = array('class' => 'editing_show');
1112 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1115 // Assign roles icon.
1116 if (has_capability('moodle/role:assign', $block->context)) {
1117 //TODO: please note it is sloppy to pass urls through page parameters!!
1118 // it is shortened because some web servers (e.g. IIS by default) give
1119 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1120 $return = $this->page->url->out(false);
1121 $return = str_replace($CFG->wwwroot . '/', '', $return);
1123 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context->id,
1124 'returnurl'=>$return));
1125 // Delete icon.
1126 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1127 $controls[] = new action_menu_link_secondary(
1128 $rolesurl,
1129 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1130 $str,
1131 array('class' => 'editing_roles')
1135 if ($this->user_can_delete_block($block)) {
1136 // Delete icon.
1137 $str = new lang_string('deleteblock', 'block', $blocktitle);
1138 $controls[] = new action_menu_link_secondary(
1139 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1140 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1141 $str,
1142 array('class' => 'editing_delete')
1146 return $controls;
1150 * @param block_base $block a block that appears on this page.
1151 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1153 protected function user_can_delete_block($block) {
1154 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1155 $block->user_can_addto($this->page) &&
1156 !in_array($block->instance->blockname, self::get_undeletable_block_types());
1160 * Process any block actions that were specified in the URL.
1162 * @return boolean true if anything was done. False if not.
1164 public function process_url_actions() {
1165 if (!$this->page->user_is_editing()) {
1166 return false;
1168 return $this->process_url_add() || $this->process_url_delete() ||
1169 $this->process_url_show_hide() || $this->process_url_edit() ||
1170 $this->process_url_move();
1174 * Handle adding a block.
1175 * @return boolean true if anything was done. False if not.
1177 public function process_url_add() {
1178 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1179 if (!$blocktype) {
1180 return false;
1183 require_sesskey();
1185 if (!$this->page->user_can_edit_blocks()) {
1186 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1189 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1190 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1193 $this->add_block_at_end_of_default_region($blocktype);
1195 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1196 $this->page->ensure_param_not_in_url('bui_addblock');
1198 return true;
1202 * Handle deleting a block.
1203 * @return boolean true if anything was done. False if not.
1205 public function process_url_delete() {
1206 global $CFG, $PAGE, $OUTPUT;
1208 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1209 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1211 if (!$blockid) {
1212 return false;
1215 require_sesskey();
1216 $block = $this->page->blocks->find_instance($blockid);
1217 if (!$this->user_can_delete_block($block)) {
1218 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1221 if (!$confirmdelete) {
1222 $deletepage = new moodle_page();
1223 $deletepage->set_pagelayout('admin');
1224 $deletepage->set_course($this->page->course);
1225 $deletepage->set_context($this->page->context);
1226 if ($this->page->cm) {
1227 $deletepage->set_cm($this->page->cm);
1230 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1231 $deleteurlparams = $this->page->url->params();
1232 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1233 $deletepage->set_block_actions_done();
1234 // At this point we are either going to redirect, or display the form, so
1235 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1236 $PAGE = $deletepage;
1237 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1238 $output = $deletepage->get_renderer('core');
1239 $OUTPUT = $output;
1241 $site = get_site();
1242 $blocktitle = $block->get_title();
1243 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1244 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1246 // If the block is being shown in sub contexts display a warning.
1247 if ($block->instance->showinsubcontexts == 1) {
1248 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1249 $systemcontext = context_system::instance();
1250 $messagestring = new stdClass();
1251 $messagestring->location = $parentcontext->get_context_name();
1253 // Checking for blocks that may have visibility on the front page and pages added on that.
1254 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1255 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1256 } else {
1257 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1258 $messagestring->pagetype = $block->instance->pagetypepattern;
1259 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1260 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1264 $message = get_string('deleteblockwarning', 'block', $messagestring);
1267 $PAGE->navbar->add($strdeletecheck);
1268 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1269 $PAGE->set_heading($site->fullname);
1270 echo $OUTPUT->header();
1271 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1272 $cancelurl = new moodle_url($deletepage->url);
1273 $yesbutton = new single_button($confirmurl, get_string('yes'));
1274 $nobutton = new single_button($cancelurl, get_string('no'));
1275 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1276 echo $OUTPUT->footer();
1277 // Make sure that nothing else happens after we have displayed this form.
1278 exit;
1279 } else {
1280 blocks_delete_instance($block->instance);
1281 // bui_deleteid and bui_confirm should not be in the PAGE url.
1282 $this->page->ensure_param_not_in_url('bui_deleteid');
1283 $this->page->ensure_param_not_in_url('bui_confirm');
1284 return true;
1289 * Handle showing or hiding a block.
1290 * @return boolean true if anything was done. False if not.
1292 public function process_url_show_hide() {
1293 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1294 $newvisibility = 0;
1295 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1296 $newvisibility = 1;
1297 } else {
1298 return false;
1301 require_sesskey();
1303 $block = $this->page->blocks->find_instance($blockid);
1305 if (!$this->page->user_can_edit_blocks()) {
1306 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1307 } else if (!$block->instance_can_be_hidden()) {
1308 return false;
1311 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1313 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1314 $this->page->ensure_param_not_in_url('bui_hideid');
1315 $this->page->ensure_param_not_in_url('bui_showid');
1317 return true;
1321 * Handle showing/processing the submission from the block editing form.
1322 * @return boolean true if the form was submitted and the new config saved. Does not
1323 * return if the editing form was displayed. False otherwise.
1325 public function process_url_edit() {
1326 global $CFG, $DB, $PAGE, $OUTPUT;
1328 $blockid = optional_param('bui_editid', null, PARAM_INT);
1329 if (!$blockid) {
1330 return false;
1333 require_sesskey();
1334 require_once($CFG->dirroot . '/blocks/edit_form.php');
1336 $block = $this->find_instance($blockid);
1338 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1339 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1342 $editpage = new moodle_page();
1343 $editpage->set_pagelayout('admin');
1344 $editpage->set_course($this->page->course);
1345 //$editpage->set_context($block->context);
1346 $editpage->set_context($this->page->context);
1347 if ($this->page->cm) {
1348 $editpage->set_cm($this->page->cm);
1350 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1351 $editurlparams = $this->page->url->params();
1352 $editurlparams['bui_editid'] = $blockid;
1353 $editpage->set_url($editurlbase, $editurlparams);
1354 $editpage->set_block_actions_done();
1355 // At this point we are either going to redirect, or display the form, so
1356 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1357 $PAGE = $editpage;
1358 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1359 $output = $editpage->get_renderer('core');
1360 $OUTPUT = $output;
1362 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1363 if (is_readable($formfile)) {
1364 require_once($formfile);
1365 $classname = 'block_' . $block->name() . '_edit_form';
1366 if (!class_exists($classname)) {
1367 $classname = 'block_edit_form';
1369 } else {
1370 $classname = 'block_edit_form';
1373 $mform = new $classname($editpage->url, $block, $this->page);
1374 $mform->set_data($block->instance);
1376 if ($mform->is_cancelled()) {
1377 redirect($this->page->url);
1379 } else if ($data = $mform->get_data()) {
1380 $bi = new stdClass;
1381 $bi->id = $block->instance->id;
1383 // This may get overwritten by the special case handling below.
1384 $bi->pagetypepattern = $data->bui_pagetypepattern;
1385 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1386 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1387 $bi->subpagepattern = null;
1388 } else {
1389 $bi->subpagepattern = $data->bui_subpagepattern;
1392 $systemcontext = context_system::instance();
1393 $frontpagecontext = context_course::instance(SITEID);
1394 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1396 // Updating stickiness and contexts. See MDL-21375 for details.
1397 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1399 // Explicitly set the default context
1400 $bi->parentcontextid = $parentcontext->id;
1402 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1404 // The interface here is a special case because the pagetype pattern is
1405 // totally derived from the context menu. Here are the excpetions. MDL-30340
1407 switch ($data->bui_contexts) {
1408 case BUI_CONTEXTS_ENTIRE_SITE:
1409 // The user wants to show the block across the entire site
1410 $bi->parentcontextid = $systemcontext->id;
1411 $bi->showinsubcontexts = true;
1412 $bi->pagetypepattern = '*';
1413 break;
1414 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1415 // The user wants the block shown on the front page and all subcontexts
1416 $bi->parentcontextid = $frontpagecontext->id;
1417 $bi->showinsubcontexts = true;
1418 $bi->pagetypepattern = '*';
1419 break;
1420 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1421 // The user want to show the front page on the frontpage only
1422 $bi->parentcontextid = $frontpagecontext->id;
1423 $bi->showinsubcontexts = false;
1424 $bi->pagetypepattern = 'site-index';
1425 // This is the only relevant page type anyway but we'll set it explicitly just
1426 // in case the front page grows site-index-* subpages of its own later
1427 break;
1432 $bits = explode('-', $bi->pagetypepattern);
1433 // hacks for some contexts
1434 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1435 // For course context
1436 // is page type pattern is mod-*, change showinsubcontext to 1
1437 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1438 $bi->showinsubcontexts = 1;
1439 } else {
1440 $bi->showinsubcontexts = 0;
1442 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1443 // for user context
1444 // subpagepattern should be null
1445 if ($bits[0] == 'user' or $bits[0] == 'my') {
1446 // we don't need subpagepattern in usercontext
1447 $bi->subpagepattern = null;
1451 $bi->defaultregion = $data->bui_defaultregion;
1452 $bi->defaultweight = $data->bui_defaultweight;
1453 $DB->update_record('block_instances', $bi);
1455 if (!empty($block->config)) {
1456 $config = clone($block->config);
1457 } else {
1458 $config = new stdClass;
1460 foreach ($data as $configfield => $value) {
1461 if (strpos($configfield, 'config_') !== 0) {
1462 continue;
1464 $field = substr($configfield, 7);
1465 $config->$field = $value;
1467 $block->instance_config_save($config);
1469 $bp = new stdClass;
1470 $bp->visible = $data->bui_visible;
1471 $bp->region = $data->bui_region;
1472 $bp->weight = $data->bui_weight;
1473 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1474 $data->bui_weight != $data->bui_defaultweight;
1476 if ($block->instance->blockpositionid && !$needbprecord) {
1477 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1479 } else if ($block->instance->blockpositionid && $needbprecord) {
1480 $bp->id = $block->instance->blockpositionid;
1481 $DB->update_record('block_positions', $bp);
1483 } else if ($needbprecord) {
1484 $bp->blockinstanceid = $block->instance->id;
1485 $bp->contextid = $this->page->context->id;
1486 $bp->pagetype = $this->page->pagetype;
1487 if ($this->page->subpage) {
1488 $bp->subpage = $this->page->subpage;
1489 } else {
1490 $bp->subpage = '';
1492 $DB->insert_record('block_positions', $bp);
1495 redirect($this->page->url);
1497 } else {
1498 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1499 $editpage->set_title($strheading);
1500 $editpage->set_heading($strheading);
1501 $bits = explode('-', $this->page->pagetype);
1502 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1503 // better navbar for tag pages
1504 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1505 $tag = tag_get('id', $this->page->subpage, '*');
1506 // tag search page doesn't have subpageid
1507 if ($tag) {
1508 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1511 $editpage->navbar->add($block->get_title());
1512 $editpage->navbar->add(get_string('configuration'));
1513 echo $output->header();
1514 echo $output->heading($strheading, 2);
1515 $mform->display();
1516 echo $output->footer();
1517 exit;
1522 * Handle showing/processing the submission from the block editing form.
1523 * @return boolean true if the form was submitted and the new config saved. Does not
1524 * return if the editing form was displayed. False otherwise.
1526 public function process_url_move() {
1527 global $CFG, $DB, $PAGE;
1529 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1530 if (!$blockid) {
1531 return false;
1534 require_sesskey();
1536 $block = $this->find_instance($blockid);
1538 if (!$this->page->user_can_edit_blocks()) {
1539 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1542 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1543 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1544 if (!$newregion || is_null($newweight)) {
1545 // Don't have a valid target position yet, must be just starting the move.
1546 $this->movingblock = $blockid;
1547 $this->page->ensure_param_not_in_url('bui_moveid');
1548 return false;
1551 if (!$this->is_known_region($newregion)) {
1552 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1555 // Move this block. This may involve moving other nearby blocks.
1556 $blocks = $this->birecordsbyregion[$newregion];
1558 $maxweight = self::MAX_WEIGHT;
1559 $minweight = -self::MAX_WEIGHT;
1561 // Initialise the used weights and spareweights array with the default values
1562 $spareweights = array();
1563 $usedweights = array();
1564 for ($i = $minweight; $i <= $maxweight; $i++) {
1565 $spareweights[$i] = $i;
1566 $usedweights[$i] = array();
1569 // Check each block and sort out where we have used weights
1570 foreach ($blocks as $bi) {
1571 if ($bi->weight > $maxweight) {
1572 // If this statement is true then the blocks weight is more than the
1573 // current maximum. To ensure that we can get the best block position
1574 // we will initialise elements within the usedweights and spareweights
1575 // arrays between the blocks weight (which will then be the new max) and
1576 // the current max
1577 $parseweight = $bi->weight;
1578 while (!array_key_exists($parseweight, $usedweights)) {
1579 $usedweights[$parseweight] = array();
1580 $spareweights[$parseweight] = $parseweight;
1581 $parseweight--;
1583 $maxweight = $bi->weight;
1584 } else if ($bi->weight < $minweight) {
1585 // As above except this time the blocks weight is LESS than the
1586 // the current minimum, so we will initialise the array from the
1587 // blocks weight (new minimum) to the current minimum
1588 $parseweight = $bi->weight;
1589 while (!array_key_exists($parseweight, $usedweights)) {
1590 $usedweights[$parseweight] = array();
1591 $spareweights[$parseweight] = $parseweight;
1592 $parseweight++;
1594 $minweight = $bi->weight;
1596 if ($bi->id != $block->instance->id) {
1597 unset($spareweights[$bi->weight]);
1598 $usedweights[$bi->weight][] = $bi->id;
1602 // First we find the nearest gap in the list of weights.
1603 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1604 $bestgap = null;
1605 foreach ($spareweights as $spareweight) {
1606 if (abs($newweight - $spareweight) < $bestdistance) {
1607 $bestdistance = abs($newweight - $spareweight);
1608 $bestgap = $spareweight;
1612 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1613 if (is_null($bestgap)) {
1614 $bestgap = self::MAX_WEIGHT + 1;
1615 while (!empty($usedweights[$bestgap])) {
1616 $bestgap++;
1620 // Now we know the gap we are aiming for, so move all the blocks along.
1621 if ($bestgap < $newweight) {
1622 $newweight = floor($newweight);
1623 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1624 foreach ($usedweights[$weight] as $biid) {
1625 $this->reposition_block($biid, $newregion, $weight - 1);
1628 $this->reposition_block($block->instance->id, $newregion, $newweight);
1629 } else {
1630 $newweight = ceil($newweight);
1631 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1632 if (array_key_exists($weight, $usedweights)) {
1633 foreach ($usedweights[$weight] as $biid) {
1634 $this->reposition_block($biid, $newregion, $weight + 1);
1638 $this->reposition_block($block->instance->id, $newregion, $newweight);
1641 $this->page->ensure_param_not_in_url('bui_moveid');
1642 $this->page->ensure_param_not_in_url('bui_newregion');
1643 $this->page->ensure_param_not_in_url('bui_newweight');
1644 return true;
1648 * Turns the display of normal blocks either on or off.
1650 * @param bool $setting
1652 public function show_only_fake_blocks($setting = true) {
1653 $this->fakeblocksonly = $setting;
1657 /// Helper functions for working with block classes ============================
1660 * Call a class method (one that does not require a block instance) on a block class.
1662 * @param string $blockname the name of the block.
1663 * @param string $method the method name.
1664 * @param array $param parameters to pass to the method.
1665 * @return mixed whatever the method returns.
1667 function block_method_result($blockname, $method, $param = NULL) {
1668 if(!block_load_class($blockname)) {
1669 return NULL;
1671 return call_user_func(array('block_'.$blockname, $method), $param);
1675 * Creates a new instance of the specified block class.
1677 * @param string $blockname the name of the block.
1678 * @param $instance block_instances DB table row (optional).
1679 * @param moodle_page $page the page this block is appearing on.
1680 * @return block_base the requested block instance.
1682 function block_instance($blockname, $instance = NULL, $page = NULL) {
1683 if(!block_load_class($blockname)) {
1684 return false;
1686 $classname = 'block_'.$blockname;
1687 $retval = new $classname;
1688 if($instance !== NULL) {
1689 if (is_null($page)) {
1690 global $PAGE;
1691 $page = $PAGE;
1693 $retval->_load_instance($instance, $page);
1695 return $retval;
1699 * Load the block class for a particular type of block.
1701 * @param string $blockname the name of the block.
1702 * @return boolean success or failure.
1704 function block_load_class($blockname) {
1705 global $CFG;
1707 if(empty($blockname)) {
1708 return false;
1711 $classname = 'block_'.$blockname;
1713 if(class_exists($classname)) {
1714 return true;
1717 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1719 if (file_exists($blockpath)) {
1720 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1721 include_once($blockpath);
1722 }else{
1723 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1724 return false;
1727 return class_exists($classname);
1731 * Given a specific page type, return all the page type patterns that might
1732 * match it.
1734 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1735 * @return array an array of all the page type patterns that might match this page type.
1737 function matching_page_type_patterns($pagetype) {
1738 $patterns = array($pagetype);
1739 $bits = explode('-', $pagetype);
1740 if (count($bits) == 3 && $bits[0] == 'mod') {
1741 if ($bits[2] == 'view') {
1742 $patterns[] = 'mod-*-view';
1743 } else if ($bits[2] == 'index') {
1744 $patterns[] = 'mod-*-index';
1747 while (count($bits) > 0) {
1748 $patterns[] = implode('-', $bits) . '-*';
1749 array_pop($bits);
1751 $patterns[] = '*';
1752 return $patterns;
1756 * Given a specific page type, parent context and currect context, return all the page type patterns
1757 * that might be used by this block.
1759 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1760 * @param stdClass $parentcontext Block's parent context
1761 * @param stdClass $currentcontext Current context of block
1762 * @return array an array of all the page type patterns that might match this page type.
1764 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1765 global $CFG; // Required for includes bellow.
1767 $bits = explode('-', $pagetype);
1769 $core = core_component::get_core_subsystems();
1770 $plugins = core_component::get_plugin_types();
1772 //progressively strip pieces off the page type looking for a match
1773 $componentarray = null;
1774 for ($i = count($bits); $i > 0; $i--) {
1775 $possiblecomponentarray = array_slice($bits, 0, $i);
1776 $possiblecomponent = implode('', $possiblecomponentarray);
1778 // Check to see if the component is a core component
1779 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1780 $libfile = $core[$possiblecomponent].'/lib.php';
1781 if (file_exists($libfile)) {
1782 require_once($libfile);
1783 $function = $possiblecomponent.'_page_type_list';
1784 if (function_exists($function)) {
1785 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1786 break;
1792 //check the plugin directory and look for a callback
1793 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1795 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1796 if (count($bits) > $i) {
1797 $pluginname = $bits[$i];
1798 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1799 if (!empty($directory)){
1800 $libfile = $directory.'/lib.php';
1801 if (file_exists($libfile)) {
1802 require_once($libfile);
1803 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1804 if (!function_exists($function)) {
1805 $function = $pluginname.'_page_type_list';
1807 if (function_exists($function)) {
1808 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1809 break;
1816 //we'll only get to here if we still don't have any patterns
1817 //the plugin type may have a callback
1818 $directory = $plugins[$possiblecomponent];
1819 $libfile = $directory.'/lib.php';
1820 if (file_exists($libfile)) {
1821 require_once($libfile);
1822 $function = $possiblecomponent.'_page_type_list';
1823 if (function_exists($function)) {
1824 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1825 break;
1832 if (empty($patterns)) {
1833 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1836 // Ensure that the * pattern is always available if editing block 'at distance', so
1837 // we always can 'bring back' it to the original context. MDL-30340
1838 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1839 // TODO: We could change the string here, showing its 'bring back' meaning
1840 $patterns['*'] = get_string('page-x', 'pagetype');
1843 return $patterns;
1847 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1849 * @param string $pagetype
1850 * @param stdClass $parentcontext
1851 * @param stdClass $currentcontext
1852 * @return array
1854 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1855 // Generate page type patterns based on current page type if
1856 // callbacks haven't been defined
1857 $patterns = array($pagetype => $pagetype);
1858 $bits = explode('-', $pagetype);
1859 while (count($bits) > 0) {
1860 $pattern = implode('-', $bits) . '-*';
1861 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1862 // guessing page type description
1863 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1864 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1865 } else {
1866 $patterns[$pattern] = $pattern;
1868 array_pop($bits);
1870 $patterns['*'] = get_string('page-x', 'pagetype');
1871 return $patterns;
1875 * Generates the page type list for the my moodle page
1877 * @param string $pagetype
1878 * @param stdClass $parentcontext
1879 * @param stdClass $currentcontext
1880 * @return array
1882 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1883 return array('my-index' => get_string('page-my-index', 'pagetype'));
1887 * Generates the page type list for a module by either locating and using the modules callback
1888 * or by generating a default list.
1890 * @param string $pagetype
1891 * @param stdClass $parentcontext
1892 * @param stdClass $currentcontext
1893 * @return array
1895 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1896 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1897 if (empty($patterns)) {
1898 // if modules don't have callbacks
1899 // generate two default page type patterns for modules only
1900 $bits = explode('-', $pagetype);
1901 $patterns = array($pagetype => $pagetype);
1902 if ($bits[2] == 'view') {
1903 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1904 } else if ($bits[2] == 'index') {
1905 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1908 return $patterns;
1910 /// Functions update the blocks if required by the request parameters ==========
1913 * Return a {@link block_contents} representing the add a new block UI, if
1914 * this user is allowed to see it.
1916 * @return block_contents an appropriate block_contents, or null if the user
1917 * cannot add any blocks here.
1919 function block_add_block_ui($page, $output) {
1920 global $CFG, $OUTPUT;
1921 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1922 return null;
1925 $bc = new block_contents();
1926 $bc->title = get_string('addblock');
1927 $bc->add_class('block_adminblock');
1928 $bc->attributes['data-block'] = 'adminblock';
1930 $missingblocks = $page->blocks->get_addable_blocks();
1931 if (empty($missingblocks)) {
1932 $bc->content = get_string('noblockstoaddhere');
1933 return $bc;
1936 $menu = array();
1937 foreach ($missingblocks as $block) {
1938 $blockobject = block_instance($block->name);
1939 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1940 $menu[$block->name] = $blockobject->get_title();
1943 core_collator::asort($menu);
1945 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1946 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1947 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1948 $bc->content = $OUTPUT->render($select);
1949 return $bc;
1952 // Functions that have been deprecated by block_manager =======================
1955 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1957 * This function returns an array with the IDs of any blocks that you can add to your page.
1958 * Parameters are passed by reference for speed; they are not modified at all.
1960 * @param $page the page object.
1961 * @param $blockmanager Not used.
1962 * @return array of block type ids.
1964 function blocks_get_missing(&$page, &$blockmanager) {
1965 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER);
1966 $blocks = $page->blocks->get_addable_blocks();
1967 $ids = array();
1968 foreach ($blocks as $block) {
1969 $ids[] = $block->id;
1971 return $ids;
1975 * Actually delete from the database any blocks that are currently on this page,
1976 * but which should not be there according to blocks_name_allowed_in_format.
1978 * @todo Write/Fix this function. Currently returns immediately
1979 * @param $course
1981 function blocks_remove_inappropriate($course) {
1982 // TODO
1983 return;
1985 $blockmanager = blocks_get_by_page($page);
1987 if (empty($blockmanager)) {
1988 return;
1991 if (($pageformat = $page->pagetype) == NULL) {
1992 return;
1995 foreach($blockmanager as $region) {
1996 foreach($region as $instance) {
1997 $block = blocks_get_record($instance->blockid);
1998 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1999 blocks_delete_instance($instance->instance);
2006 * Check that a given name is in a permittable format
2008 * @param string $name
2009 * @param string $pageformat
2010 * @return bool
2012 function blocks_name_allowed_in_format($name, $pageformat) {
2013 $accept = NULL;
2014 $maxdepth = -1;
2015 if (!$bi = block_instance($name)) {
2016 return false;
2019 $formats = $bi->applicable_formats();
2020 if (!$formats) {
2021 $formats = array();
2023 foreach ($formats as $format => $allowed) {
2024 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2025 $depth = substr_count($format, '-');
2026 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2027 $maxdepth = $depth;
2028 $accept = $allowed;
2031 if ($accept === NULL) {
2032 $accept = !empty($formats['all']);
2034 return $accept;
2038 * Delete a block, and associated data.
2040 * @param object $instance a row from the block_instances table
2041 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2042 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2044 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2045 global $DB;
2047 if ($block = block_instance($instance->blockname, $instance)) {
2048 $block->instance_delete();
2050 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2052 if (!$skipblockstables) {
2053 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2054 $DB->delete_records('block_instances', array('id' => $instance->id));
2055 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2060 * Delete all the blocks that belong to a particular context.
2062 * @param int $contextid the context id.
2064 function blocks_delete_all_for_context($contextid) {
2065 global $DB;
2066 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2067 foreach ($instances as $instance) {
2068 blocks_delete_instance($instance, true);
2070 $instances->close();
2071 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2072 $DB->delete_records('block_positions', array('contextid' => $contextid));
2076 * Set a block to be visible or hidden on a particular page.
2078 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2079 * block_positions table as return by block_manager.
2080 * @param moodle_page $page the back to set the visibility with respect to.
2081 * @param integer $newvisibility 1 for visible, 0 for hidden.
2083 function blocks_set_visibility($instance, $page, $newvisibility) {
2084 global $DB;
2085 if (!empty($instance->blockpositionid)) {
2086 // Already have local information on this page.
2087 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2088 return;
2091 // Create a new block_positions record.
2092 $bp = new stdClass;
2093 $bp->blockinstanceid = $instance->id;
2094 $bp->contextid = $page->context->id;
2095 $bp->pagetype = $page->pagetype;
2096 if ($page->subpage) {
2097 $bp->subpage = $page->subpage;
2099 $bp->visible = $newvisibility;
2100 $bp->region = $instance->defaultregion;
2101 $bp->weight = $instance->defaultweight;
2102 $DB->insert_record('block_positions', $bp);
2106 * @deprecated since 2.0
2107 * Delete all the blocks from a particular page.
2109 * @param string $pagetype the page type.
2110 * @param integer $pageid the page id.
2111 * @return bool success or failure.
2113 function blocks_delete_all_on_page($pagetype, $pageid) {
2114 global $DB;
2116 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
2117 'This function cannot work any more. Doing nothing. ' .
2118 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER);
2119 return false;
2123 * Get the block record for a particular blockid - that is, a particular type os block.
2125 * @param $int blockid block type id. If null, an array of all block types is returned.
2126 * @param bool $notusedanymore No longer used.
2127 * @return array|object row from block table, or all rows.
2129 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2130 global $PAGE;
2131 $blocks = $PAGE->blocks->get_installed_blocks();
2132 if ($blockid === NULL) {
2133 return $blocks;
2134 } else if (isset($blocks[$blockid])) {
2135 return $blocks[$blockid];
2136 } else {
2137 return false;
2142 * Find a given block by its blockid within a provide array
2144 * @param int $blockid
2145 * @param array $blocksarray
2146 * @return bool|object Instance if found else false
2148 function blocks_find_block($blockid, $blocksarray) {
2149 if (empty($blocksarray)) {
2150 return false;
2152 foreach($blocksarray as $blockgroup) {
2153 if (empty($blockgroup)) {
2154 continue;
2156 foreach($blockgroup as $instance) {
2157 if($instance->blockid == $blockid) {
2158 return $instance;
2162 return false;
2165 // Functions for programatically adding default blocks to pages ================
2168 * Parse a list of default blocks. See config-dist for a description of the format.
2170 * @param string $blocksstr
2171 * @return array
2173 function blocks_parse_default_blocks_list($blocksstr) {
2174 $blocks = array();
2175 $bits = explode(':', $blocksstr);
2176 if (!empty($bits)) {
2177 $leftbits = trim(array_shift($bits));
2178 if ($leftbits != '') {
2179 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2182 if (!empty($bits)) {
2183 $rightbits =trim(array_shift($bits));
2184 if ($rightbits != '') {
2185 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2188 return $blocks;
2192 * @return array the blocks that should be added to the site course by default.
2194 function blocks_get_default_site_course_blocks() {
2195 global $CFG;
2197 if (!empty($CFG->defaultblocks_site)) {
2198 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2199 } else {
2200 return array(
2201 BLOCK_POS_LEFT => array('site_main_menu'),
2202 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2208 * Add the default blocks to a course.
2210 * @param object $course a course object.
2212 function blocks_add_default_course_blocks($course) {
2213 global $CFG;
2215 if (!empty($CFG->defaultblocks_override)) {
2216 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2218 } else if ($course->id == SITEID) {
2219 $blocknames = blocks_get_default_site_course_blocks();
2221 } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2222 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2224 } else {
2225 require_once($CFG->dirroot. '/course/lib.php');
2226 $blocknames = course_get_format($course)->get_default_blocks();
2230 if ($course->id == SITEID) {
2231 $pagetypepattern = 'site-index';
2232 } else {
2233 $pagetypepattern = 'course-view-*';
2235 $page = new moodle_page();
2236 $page->set_course($course);
2237 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2241 * Add the default system-context blocks. E.g. the admin tree.
2243 function blocks_add_default_system_blocks() {
2244 global $DB;
2246 $page = new moodle_page();
2247 $page->set_context(context_system::instance());
2248 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2249 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2251 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2252 $subpagepattern = $defaultmypage->id;
2253 } else {
2254 $subpagepattern = null;
2257 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);