Merge branch 'install_27_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / lib / blocklib.php
blob6d4cb0e713ee34d8b3ca39bb022e3e4db1082e94
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 // Block regions should not be docked during editing when all the blocks are hidden.
521 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
522 return false;
525 $this->check_is_loaded();
526 $this->ensure_content_created($region, $output);
527 if (!$this->region_has_content($region, $output)) {
528 // If the region has no content then nothing is docked at all of course.
529 return false;
531 foreach ($this->visibleblockcontent[$region] as $instance) {
532 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
533 return false;
536 return true;
540 * Checks to see whether any of the blocks within the given regions are docked
542 * @see region_completely_docked
543 * @param array|string $regions array of regions (or single region)
544 * @return bool True if any of the blocks within that region are docked
546 public function region_uses_dock($regions, $output) {
547 if (!$this->page->theme->enable_dock) {
548 return false;
550 $this->check_is_loaded();
551 foreach((array)$regions as $region) {
552 $this->ensure_content_created($region, $output);
553 foreach($this->visibleblockcontent[$region] as $instance) {
554 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
555 return true;
559 return false;
562 /// Actions ====================================================================
565 * This method actually loads the blocks for our page from the database.
567 * @param boolean|null $includeinvisible
568 * null (default) - load hidden blocks if $this->page->user_is_editing();
569 * true - load hidden blocks.
570 * false - don't load hidden blocks.
572 public function load_blocks($includeinvisible = null) {
573 global $DB, $CFG;
575 if (!is_null($this->birecordsbyregion)) {
576 // Already done.
577 return;
580 if ($CFG->version < 2009050619) {
581 // Upgrade/install not complete. Don't try too show any blocks.
582 $this->birecordsbyregion = array();
583 return;
586 // Ensure we have been initialised.
587 if (is_null($this->defaultregion)) {
588 $this->page->initialise_theme_and_output();
589 // If there are still no block regions, then there are no blocks on this page.
590 if (empty($this->regions)) {
591 $this->birecordsbyregion = array();
592 return;
596 // Check if we need to load normal blocks
597 if ($this->fakeblocksonly) {
598 $this->birecordsbyregion = $this->prepare_per_region_arrays();
599 return;
602 if (is_null($includeinvisible)) {
603 $includeinvisible = $this->page->user_is_editing();
605 if ($includeinvisible) {
606 $visiblecheck = '';
607 } else {
608 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
611 $context = $this->page->context;
612 $contexttest = 'bi.parentcontextid = :contextid2';
613 $parentcontextparams = array();
614 $parentcontextids = $context->get_parent_context_ids();
615 if ($parentcontextids) {
616 list($parentcontexttest, $parentcontextparams) =
617 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
618 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
621 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
622 list($pagetypepatterntest, $pagetypepatternparams) =
623 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
625 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
626 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
628 $params = array(
629 'contextlevel' => CONTEXT_BLOCK,
630 'subpage1' => $this->page->subpage,
631 'subpage2' => $this->page->subpage,
632 'contextid1' => $context->id,
633 'contextid2' => $context->id,
634 'pagetype' => $this->page->pagetype,
636 if ($this->page->subpage === '') {
637 $params['subpage1'] = '';
638 $params['subpage2'] = '';
640 $sql = "SELECT
641 bi.id,
642 bp.id AS blockpositionid,
643 bi.blockname,
644 bi.parentcontextid,
645 bi.showinsubcontexts,
646 bi.pagetypepattern,
647 bi.subpagepattern,
648 bi.defaultregion,
649 bi.defaultweight,
650 COALESCE(bp.visible, 1) AS visible,
651 COALESCE(bp.region, bi.defaultregion) AS region,
652 COALESCE(bp.weight, bi.defaultweight) AS weight,
653 bi.configdata
654 $ccselect
656 FROM {block_instances} bi
657 JOIN {block} b ON bi.blockname = b.name
658 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
659 AND bp.contextid = :contextid1
660 AND bp.pagetype = :pagetype
661 AND bp.subpage = :subpage1
662 $ccjoin
664 WHERE
665 $contexttest
666 AND bi.pagetypepattern $pagetypepatterntest
667 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
668 $visiblecheck
669 AND b.visible = 1
671 ORDER BY
672 COALESCE(bp.region, bi.defaultregion),
673 COALESCE(bp.weight, bi.defaultweight),
674 bi.id";
675 $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
677 $this->birecordsbyregion = $this->prepare_per_region_arrays();
678 $unknown = array();
679 foreach ($blockinstances as $bi) {
680 context_helper::preload_from_record($bi);
681 if ($this->is_known_region($bi->region)) {
682 $this->birecordsbyregion[$bi->region][] = $bi;
683 } else {
684 $unknown[] = $bi;
688 // Pages don't necessarily have a defaultregion. The one time this can
689 // happen is when there are no theme block regions, but the script itself
690 // has a block region in the main content area.
691 if (!empty($this->defaultregion)) {
692 $this->birecordsbyregion[$this->defaultregion] =
693 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
698 * Add a block to the current page, or related pages. The block is added to
699 * context $this->page->contextid. If $pagetypepattern $subpagepattern
701 * @param string $blockname The type of block to add.
702 * @param string $region the block region on this page to add the block to.
703 * @param integer $weight determines the order where this block appears in the region.
704 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
705 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
706 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
708 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
709 global $DB;
710 // Allow invisible blocks because this is used when adding default page blocks, which
711 // might include invisible ones if the user makes some default blocks invisible
712 $this->check_known_block_type($blockname, true);
713 $this->check_region_is_known($region);
715 if (empty($pagetypepattern)) {
716 $pagetypepattern = $this->page->pagetype;
719 $blockinstance = new stdClass;
720 $blockinstance->blockname = $blockname;
721 $blockinstance->parentcontextid = $this->page->context->id;
722 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
723 $blockinstance->pagetypepattern = $pagetypepattern;
724 $blockinstance->subpagepattern = $subpagepattern;
725 $blockinstance->defaultregion = $region;
726 $blockinstance->defaultweight = $weight;
727 $blockinstance->configdata = '';
728 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
730 // Ensure the block context is created.
731 context_block::instance($blockinstance->id);
733 // If the new instance was created, allow it to do additional setup
734 if ($block = block_instance($blockname, $blockinstance)) {
735 $block->instance_create();
739 public function add_block_at_end_of_default_region($blockname) {
740 $defaulregion = $this->get_default_region();
742 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
743 if ($lastcurrentblock) {
744 $weight = $lastcurrentblock->weight + 1;
745 } else {
746 $weight = 0;
749 if ($this->page->subpage) {
750 $subpage = $this->page->subpage;
751 } else {
752 $subpage = null;
755 // Special case. Course view page type include the course format, but we
756 // want to add the block non-format-specifically.
757 $pagetypepattern = $this->page->pagetype;
758 if (strpos($pagetypepattern, 'course-view') === 0) {
759 $pagetypepattern = 'course-view-*';
762 // We should end using this for ALL the blocks, making always the 1st option
763 // the default one to be used. Until then, this is one hack to avoid the
764 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
765 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
766 // (the FIRST $pagetypepattern will be set)
768 // We are applying it to all blocks created in mod pages for now and only if the
769 // default pagetype is not one of the available options
770 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
771 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
772 // Only go for the first if the pagetype is not a valid option
773 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
774 $pagetypepattern = key($pagetypelist);
777 // Surely other pages like course-report will need this too, they just are not important
778 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
780 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
784 * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
785 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
786 * and incremented by the position of the block in the $blocks array
788 * @param array $blocks array with array keys the region names, and values an array of block names.
789 * @param string $pagetypepattern optional. Passed to {@link add_block()}
790 * @param string $subpagepattern optional. Passed to {@link add_block()}
791 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
792 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
794 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
795 $initialweight = $weight;
796 $this->add_regions(array_keys($blocks), false);
797 foreach ($blocks as $region => $regionblocks) {
798 foreach ($regionblocks as $offset => $blockname) {
799 $weight = $initialweight + $offset;
800 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
806 * Move a block to a new position on this page.
808 * If this block cannot appear on any other pages, then we change defaultposition/weight
809 * in the block_instances table. Otherwise we just set the position on this page.
811 * @param $blockinstanceid the block instance id.
812 * @param $newregion the new region name.
813 * @param $newweight the new weight.
815 public function reposition_block($blockinstanceid, $newregion, $newweight) {
816 global $DB;
818 $this->check_region_is_known($newregion);
819 $inst = $this->find_instance($blockinstanceid);
821 $bi = $inst->instance;
822 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
823 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
824 (!$this->page->subpage || $bi->subpagepattern)) {
826 // Set default position
827 $newbi = new stdClass;
828 $newbi->id = $bi->id;
829 $newbi->defaultregion = $newregion;
830 $newbi->defaultweight = $newweight;
831 $DB->update_record('block_instances', $newbi);
833 if ($bi->blockpositionid) {
834 $bp = new stdClass;
835 $bp->id = $bi->blockpositionid;
836 $bp->region = $newregion;
837 $bp->weight = $newweight;
838 $DB->update_record('block_positions', $bp);
841 } else {
842 // Just set position on this page.
843 $bp = new stdClass;
844 $bp->region = $newregion;
845 $bp->weight = $newweight;
847 if ($bi->blockpositionid) {
848 $bp->id = $bi->blockpositionid;
849 $DB->update_record('block_positions', $bp);
851 } else {
852 $bp->blockinstanceid = $bi->id;
853 $bp->contextid = $this->page->context->id;
854 $bp->pagetype = $this->page->pagetype;
855 if ($this->page->subpage) {
856 $bp->subpage = $this->page->subpage;
857 } else {
858 $bp->subpage = '';
860 $bp->visible = $bi->visible;
861 $DB->insert_record('block_positions', $bp);
867 * Find a given block by its instance id
869 * @param integer $instanceid
870 * @return block_base
872 public function find_instance($instanceid) {
873 foreach ($this->regions as $region => $notused) {
874 $this->ensure_instances_exist($region);
875 foreach($this->blockinstances[$region] as $instance) {
876 if ($instance->instance->id == $instanceid) {
877 return $instance;
881 throw new block_not_on_page_exception($instanceid, $this->page);
884 /// Inner workings =============================================================
887 * Check whether the page blocks have been loaded yet
889 * @return void Throws coding exception if already loaded
891 protected function check_not_yet_loaded() {
892 if (!is_null($this->birecordsbyregion)) {
893 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.');
898 * Check whether the page blocks have been loaded yet
900 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
902 * @return void Throws coding exception if already loaded
904 protected function check_is_loaded() {
905 if (is_null($this->birecordsbyregion)) {
906 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
911 * Check if a block type is known and usable
913 * @param string $blockname The block type name to search for
914 * @param bool $includeinvisible Include disabled block types in the initial pass
915 * @return void Coding Exception thrown if unknown or not enabled
917 protected function check_known_block_type($blockname, $includeinvisible = false) {
918 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
919 if ($this->is_known_block_type($blockname, true)) {
920 throw new coding_exception('Unknown block type ' . $blockname);
921 } else {
922 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
928 * Check if a region is known by its name
930 * @param string $region
931 * @return void Coding Exception thrown if the region is not known
933 protected function check_region_is_known($region) {
934 if (!$this->is_known_region($region)) {
935 throw new coding_exception('Trying to reference an unknown block region ' . $region);
940 * Returns an array of region names as keys and nested arrays for values
942 * @return array an array where the array keys are the region names, and the array
943 * values are empty arrays.
945 protected function prepare_per_region_arrays() {
946 $result = array();
947 foreach ($this->regions as $region => $notused) {
948 $result[$region] = array();
950 return $result;
954 * Create a set of new block instance from a record array
956 * @param array $birecords An array of block instance records
957 * @return array An array of instantiated block_instance objects
959 protected function create_block_instances($birecords) {
960 $results = array();
961 foreach ($birecords as $record) {
962 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
963 $results[] = $blockobject;
966 return $results;
970 * Create all the block instances for all the blocks that were loaded by
971 * load_blocks. This is used, for example, to ensure that all blocks get a
972 * chance to initialise themselves via the {@link block_base::specialize()}
973 * method, before any output is done.
975 public function create_all_block_instances() {
976 foreach ($this->get_regions() as $region) {
977 $this->ensure_instances_exist($region);
982 * Return an array of content objects from a set of block instances
984 * @param array $instances An array of block instances
985 * @param renderer_base The renderer to use.
986 * @param string $region the region name.
987 * @return array An array of block_content (and possibly block_move_target) objects.
989 protected function create_block_contents($instances, $output, $region) {
990 $results = array();
992 $lastweight = 0;
993 $lastblock = 0;
994 if ($this->movingblock) {
995 $first = reset($instances);
996 if ($first) {
997 $lastweight = $first->instance->weight - 2;
1001 foreach ($instances as $instance) {
1002 $content = $instance->get_content_for_output($output);
1003 if (empty($content)) {
1004 continue;
1007 if ($this->movingblock && $lastweight != $instance->instance->weight &&
1008 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
1009 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
1012 if ($content->blockinstanceid == $this->movingblock) {
1013 $content->add_class('beingmoved');
1014 $content->annotation .= get_string('movingthisblockcancel', 'block',
1015 html_writer::link($this->page->url, get_string('cancel')));
1018 $results[] = $content;
1019 $lastweight = $instance->instance->weight;
1020 $lastblock = $instance->instance->id;
1023 if ($this->movingblock && $lastblock != $this->movingblock) {
1024 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
1026 return $results;
1030 * Ensure block instances exist for a given region
1032 * @param string $region Check for bi's with the instance with this name
1034 protected function ensure_instances_exist($region) {
1035 $this->check_region_is_known($region);
1036 if (!array_key_exists($region, $this->blockinstances)) {
1037 $this->blockinstances[$region] =
1038 $this->create_block_instances($this->birecordsbyregion[$region]);
1043 * Ensure that there is some content within the given region
1045 * @param string $region The name of the region to check
1047 public function ensure_content_created($region, $output) {
1048 $this->ensure_instances_exist($region);
1049 if (!array_key_exists($region, $this->visibleblockcontent)) {
1050 $contents = array();
1051 if (array_key_exists($region, $this->extracontent)) {
1052 $contents = $this->extracontent[$region];
1054 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1055 if ($region == $this->defaultregion) {
1056 $addblockui = block_add_block_ui($this->page, $output);
1057 if ($addblockui) {
1058 $contents[] = $addblockui;
1061 $this->visibleblockcontent[$region] = $contents;
1065 /// Process actions from the URL ===============================================
1068 * Get the appropriate list of editing icons for a block. This is used
1069 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1071 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1072 * @return an array in the format for {@link block_contents::$controls}
1074 public function edit_controls($block) {
1075 global $CFG;
1077 $controls = array();
1078 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1079 $blocktitle = $block->title;
1080 if (empty($blocktitle)) {
1081 $blocktitle = $block->arialabel;
1084 if ($this->page->user_can_edit_blocks()) {
1085 // Move icon.
1086 $str = new lang_string('moveblock', 'block', $blocktitle);
1087 $controls[] = new action_menu_link_primary(
1088 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1089 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1090 $str,
1091 array('class' => 'editing_move')
1096 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1097 // Edit config icon - always show - needed for positioning UI.
1098 $str = new lang_string('configureblock', 'block', $blocktitle);
1099 $controls[] = new action_menu_link_secondary(
1100 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1101 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1102 $str,
1103 array('class' => 'editing_edit')
1108 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1109 // Show/hide icon.
1110 if ($block->instance->visible) {
1111 $str = new lang_string('hideblock', 'block', $blocktitle);
1112 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1113 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1114 $attributes = array('class' => 'editing_hide');
1115 } else {
1116 $str = new lang_string('showblock', 'block', $blocktitle);
1117 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1118 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1119 $attributes = array('class' => 'editing_show');
1121 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1124 // Assign roles icon.
1125 if ($this->page->pagetype != 'my-index' && has_capability('moodle/role:assign', $block->context)) {
1126 //TODO: please note it is sloppy to pass urls through page parameters!!
1127 // it is shortened because some web servers (e.g. IIS by default) give
1128 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1129 $return = $this->page->url->out(false);
1130 $return = str_replace($CFG->wwwroot . '/', '', $return);
1132 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context->id,
1133 'returnurl'=>$return));
1134 // Delete icon.
1135 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1136 $controls[] = new action_menu_link_secondary(
1137 $rolesurl,
1138 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1139 $str,
1140 array('class' => 'editing_roles')
1144 if ($this->user_can_delete_block($block)) {
1145 // Delete icon.
1146 $str = new lang_string('deleteblock', 'block', $blocktitle);
1147 $controls[] = new action_menu_link_secondary(
1148 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1149 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1150 $str,
1151 array('class' => 'editing_delete')
1155 return $controls;
1159 * @param block_base $block a block that appears on this page.
1160 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1162 protected function user_can_delete_block($block) {
1163 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1164 $block->user_can_addto($this->page) &&
1165 !in_array($block->instance->blockname, self::get_undeletable_block_types());
1169 * Process any block actions that were specified in the URL.
1171 * @return boolean true if anything was done. False if not.
1173 public function process_url_actions() {
1174 if (!$this->page->user_is_editing()) {
1175 return false;
1177 return $this->process_url_add() || $this->process_url_delete() ||
1178 $this->process_url_show_hide() || $this->process_url_edit() ||
1179 $this->process_url_move();
1183 * Handle adding a block.
1184 * @return boolean true if anything was done. False if not.
1186 public function process_url_add() {
1187 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1188 if (!$blocktype) {
1189 return false;
1192 require_sesskey();
1194 if (!$this->page->user_can_edit_blocks()) {
1195 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1198 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1199 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1202 $this->add_block_at_end_of_default_region($blocktype);
1204 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1205 $this->page->ensure_param_not_in_url('bui_addblock');
1207 return true;
1211 * Handle deleting a block.
1212 * @return boolean true if anything was done. False if not.
1214 public function process_url_delete() {
1215 global $CFG, $PAGE, $OUTPUT;
1217 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1218 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1220 if (!$blockid) {
1221 return false;
1224 require_sesskey();
1225 $block = $this->page->blocks->find_instance($blockid);
1226 if (!$this->user_can_delete_block($block)) {
1227 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1230 if (!$confirmdelete) {
1231 $deletepage = new moodle_page();
1232 $deletepage->set_pagelayout('admin');
1233 $deletepage->set_course($this->page->course);
1234 $deletepage->set_context($this->page->context);
1235 if ($this->page->cm) {
1236 $deletepage->set_cm($this->page->cm);
1239 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1240 $deleteurlparams = $this->page->url->params();
1241 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1242 $deletepage->set_block_actions_done();
1243 // At this point we are either going to redirect, or display the form, so
1244 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1245 $PAGE = $deletepage;
1246 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1247 $output = $deletepage->get_renderer('core');
1248 $OUTPUT = $output;
1250 $site = get_site();
1251 $blocktitle = $block->get_title();
1252 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1253 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1255 // If the block is being shown in sub contexts display a warning.
1256 if ($block->instance->showinsubcontexts == 1) {
1257 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1258 $systemcontext = context_system::instance();
1259 $messagestring = new stdClass();
1260 $messagestring->location = $parentcontext->get_context_name();
1262 // Checking for blocks that may have visibility on the front page and pages added on that.
1263 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1264 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1265 } else {
1266 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1267 $messagestring->pagetype = $block->instance->pagetypepattern;
1268 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1269 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1273 $message = get_string('deleteblockwarning', 'block', $messagestring);
1276 $PAGE->navbar->add($strdeletecheck);
1277 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1278 $PAGE->set_heading($site->fullname);
1279 echo $OUTPUT->header();
1280 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1281 $cancelurl = new moodle_url($deletepage->url);
1282 $yesbutton = new single_button($confirmurl, get_string('yes'));
1283 $nobutton = new single_button($cancelurl, get_string('no'));
1284 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1285 echo $OUTPUT->footer();
1286 // Make sure that nothing else happens after we have displayed this form.
1287 exit;
1288 } else {
1289 blocks_delete_instance($block->instance);
1290 // bui_deleteid and bui_confirm should not be in the PAGE url.
1291 $this->page->ensure_param_not_in_url('bui_deleteid');
1292 $this->page->ensure_param_not_in_url('bui_confirm');
1293 return true;
1298 * Handle showing or hiding a block.
1299 * @return boolean true if anything was done. False if not.
1301 public function process_url_show_hide() {
1302 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1303 $newvisibility = 0;
1304 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1305 $newvisibility = 1;
1306 } else {
1307 return false;
1310 require_sesskey();
1312 $block = $this->page->blocks->find_instance($blockid);
1314 if (!$this->page->user_can_edit_blocks()) {
1315 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1316 } else if (!$block->instance_can_be_hidden()) {
1317 return false;
1320 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1322 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1323 $this->page->ensure_param_not_in_url('bui_hideid');
1324 $this->page->ensure_param_not_in_url('bui_showid');
1326 return true;
1330 * Handle showing/processing the submission from the block editing form.
1331 * @return boolean true if the form was submitted and the new config saved. Does not
1332 * return if the editing form was displayed. False otherwise.
1334 public function process_url_edit() {
1335 global $CFG, $DB, $PAGE, $OUTPUT;
1337 $blockid = optional_param('bui_editid', null, PARAM_INT);
1338 if (!$blockid) {
1339 return false;
1342 require_sesskey();
1343 require_once($CFG->dirroot . '/blocks/edit_form.php');
1345 $block = $this->find_instance($blockid);
1347 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1348 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1351 $editpage = new moodle_page();
1352 $editpage->set_pagelayout('admin');
1353 $editpage->set_course($this->page->course);
1354 //$editpage->set_context($block->context);
1355 $editpage->set_context($this->page->context);
1356 if ($this->page->cm) {
1357 $editpage->set_cm($this->page->cm);
1359 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1360 $editurlparams = $this->page->url->params();
1361 $editurlparams['bui_editid'] = $blockid;
1362 $editpage->set_url($editurlbase, $editurlparams);
1363 $editpage->set_block_actions_done();
1364 // At this point we are either going to redirect, or display the form, so
1365 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1366 $PAGE = $editpage;
1367 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1368 $output = $editpage->get_renderer('core');
1369 $OUTPUT = $output;
1371 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1372 if (is_readable($formfile)) {
1373 require_once($formfile);
1374 $classname = 'block_' . $block->name() . '_edit_form';
1375 if (!class_exists($classname)) {
1376 $classname = 'block_edit_form';
1378 } else {
1379 $classname = 'block_edit_form';
1382 $mform = new $classname($editpage->url, $block, $this->page);
1383 $mform->set_data($block->instance);
1385 if ($mform->is_cancelled()) {
1386 redirect($this->page->url);
1388 } else if ($data = $mform->get_data()) {
1389 $bi = new stdClass;
1390 $bi->id = $block->instance->id;
1392 // This may get overwritten by the special case handling below.
1393 $bi->pagetypepattern = $data->bui_pagetypepattern;
1394 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1395 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1396 $bi->subpagepattern = null;
1397 } else {
1398 $bi->subpagepattern = $data->bui_subpagepattern;
1401 $systemcontext = context_system::instance();
1402 $frontpagecontext = context_course::instance(SITEID);
1403 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1405 // Updating stickiness and contexts. See MDL-21375 for details.
1406 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1408 // Explicitly set the default context
1409 $bi->parentcontextid = $parentcontext->id;
1411 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1413 // The interface here is a special case because the pagetype pattern is
1414 // totally derived from the context menu. Here are the excpetions. MDL-30340
1416 switch ($data->bui_contexts) {
1417 case BUI_CONTEXTS_ENTIRE_SITE:
1418 // The user wants to show the block across the entire site
1419 $bi->parentcontextid = $systemcontext->id;
1420 $bi->showinsubcontexts = true;
1421 $bi->pagetypepattern = '*';
1422 break;
1423 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1424 // The user wants the block shown on the front page and all subcontexts
1425 $bi->parentcontextid = $frontpagecontext->id;
1426 $bi->showinsubcontexts = true;
1427 $bi->pagetypepattern = '*';
1428 break;
1429 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1430 // The user want to show the front page on the frontpage only
1431 $bi->parentcontextid = $frontpagecontext->id;
1432 $bi->showinsubcontexts = false;
1433 $bi->pagetypepattern = 'site-index';
1434 // This is the only relevant page type anyway but we'll set it explicitly just
1435 // in case the front page grows site-index-* subpages of its own later
1436 break;
1441 $bits = explode('-', $bi->pagetypepattern);
1442 // hacks for some contexts
1443 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1444 // For course context
1445 // is page type pattern is mod-*, change showinsubcontext to 1
1446 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1447 $bi->showinsubcontexts = 1;
1448 } else {
1449 $bi->showinsubcontexts = 0;
1451 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1452 // for user context
1453 // subpagepattern should be null
1454 if ($bits[0] == 'user' or $bits[0] == 'my') {
1455 // we don't need subpagepattern in usercontext
1456 $bi->subpagepattern = null;
1460 $bi->defaultregion = $data->bui_defaultregion;
1461 $bi->defaultweight = $data->bui_defaultweight;
1462 $DB->update_record('block_instances', $bi);
1464 if (!empty($block->config)) {
1465 $config = clone($block->config);
1466 } else {
1467 $config = new stdClass;
1469 foreach ($data as $configfield => $value) {
1470 if (strpos($configfield, 'config_') !== 0) {
1471 continue;
1473 $field = substr($configfield, 7);
1474 $config->$field = $value;
1476 $block->instance_config_save($config);
1478 $bp = new stdClass;
1479 $bp->visible = $data->bui_visible;
1480 $bp->region = $data->bui_region;
1481 $bp->weight = $data->bui_weight;
1482 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1483 $data->bui_weight != $data->bui_defaultweight;
1485 if ($block->instance->blockpositionid && !$needbprecord) {
1486 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1488 } else if ($block->instance->blockpositionid && $needbprecord) {
1489 $bp->id = $block->instance->blockpositionid;
1490 $DB->update_record('block_positions', $bp);
1492 } else if ($needbprecord) {
1493 $bp->blockinstanceid = $block->instance->id;
1494 $bp->contextid = $this->page->context->id;
1495 $bp->pagetype = $this->page->pagetype;
1496 if ($this->page->subpage) {
1497 $bp->subpage = $this->page->subpage;
1498 } else {
1499 $bp->subpage = '';
1501 $DB->insert_record('block_positions', $bp);
1504 redirect($this->page->url);
1506 } else {
1507 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1508 $editpage->set_title($strheading);
1509 $editpage->set_heading($strheading);
1510 $bits = explode('-', $this->page->pagetype);
1511 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1512 // better navbar for tag pages
1513 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1514 $tag = tag_get('id', $this->page->subpage, '*');
1515 // tag search page doesn't have subpageid
1516 if ($tag) {
1517 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1520 $editpage->navbar->add($block->get_title());
1521 $editpage->navbar->add(get_string('configuration'));
1522 echo $output->header();
1523 echo $output->heading($strheading, 2);
1524 $mform->display();
1525 echo $output->footer();
1526 exit;
1531 * Handle showing/processing the submission from the block editing form.
1532 * @return boolean true if the form was submitted and the new config saved. Does not
1533 * return if the editing form was displayed. False otherwise.
1535 public function process_url_move() {
1536 global $CFG, $DB, $PAGE;
1538 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1539 if (!$blockid) {
1540 return false;
1543 require_sesskey();
1545 $block = $this->find_instance($blockid);
1547 if (!$this->page->user_can_edit_blocks()) {
1548 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1551 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1552 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1553 if (!$newregion || is_null($newweight)) {
1554 // Don't have a valid target position yet, must be just starting the move.
1555 $this->movingblock = $blockid;
1556 $this->page->ensure_param_not_in_url('bui_moveid');
1557 return false;
1560 if (!$this->is_known_region($newregion)) {
1561 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1564 // Move this block. This may involve moving other nearby blocks.
1565 $blocks = $this->birecordsbyregion[$newregion];
1567 $maxweight = self::MAX_WEIGHT;
1568 $minweight = -self::MAX_WEIGHT;
1570 // Initialise the used weights and spareweights array with the default values
1571 $spareweights = array();
1572 $usedweights = array();
1573 for ($i = $minweight; $i <= $maxweight; $i++) {
1574 $spareweights[$i] = $i;
1575 $usedweights[$i] = array();
1578 // Check each block and sort out where we have used weights
1579 foreach ($blocks as $bi) {
1580 if ($bi->weight > $maxweight) {
1581 // If this statement is true then the blocks weight is more than the
1582 // current maximum. To ensure that we can get the best block position
1583 // we will initialise elements within the usedweights and spareweights
1584 // arrays between the blocks weight (which will then be the new max) and
1585 // the current max
1586 $parseweight = $bi->weight;
1587 while (!array_key_exists($parseweight, $usedweights)) {
1588 $usedweights[$parseweight] = array();
1589 $spareweights[$parseweight] = $parseweight;
1590 $parseweight--;
1592 $maxweight = $bi->weight;
1593 } else if ($bi->weight < $minweight) {
1594 // As above except this time the blocks weight is LESS than the
1595 // the current minimum, so we will initialise the array from the
1596 // blocks weight (new minimum) to the current minimum
1597 $parseweight = $bi->weight;
1598 while (!array_key_exists($parseweight, $usedweights)) {
1599 $usedweights[$parseweight] = array();
1600 $spareweights[$parseweight] = $parseweight;
1601 $parseweight++;
1603 $minweight = $bi->weight;
1605 if ($bi->id != $block->instance->id) {
1606 unset($spareweights[$bi->weight]);
1607 $usedweights[$bi->weight][] = $bi->id;
1611 // First we find the nearest gap in the list of weights.
1612 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1613 $bestgap = null;
1614 foreach ($spareweights as $spareweight) {
1615 if (abs($newweight - $spareweight) < $bestdistance) {
1616 $bestdistance = abs($newweight - $spareweight);
1617 $bestgap = $spareweight;
1621 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1622 if (is_null($bestgap)) {
1623 $bestgap = self::MAX_WEIGHT + 1;
1624 while (!empty($usedweights[$bestgap])) {
1625 $bestgap++;
1629 // Now we know the gap we are aiming for, so move all the blocks along.
1630 if ($bestgap < $newweight) {
1631 $newweight = floor($newweight);
1632 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1633 if (array_key_exists($weight, $usedweights)) {
1634 foreach ($usedweights[$weight] as $biid) {
1635 $this->reposition_block($biid, $newregion, $weight - 1);
1639 $this->reposition_block($block->instance->id, $newregion, $newweight);
1640 } else {
1641 $newweight = ceil($newweight);
1642 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1643 if (array_key_exists($weight, $usedweights)) {
1644 foreach ($usedweights[$weight] as $biid) {
1645 $this->reposition_block($biid, $newregion, $weight + 1);
1649 $this->reposition_block($block->instance->id, $newregion, $newweight);
1652 $this->page->ensure_param_not_in_url('bui_moveid');
1653 $this->page->ensure_param_not_in_url('bui_newregion');
1654 $this->page->ensure_param_not_in_url('bui_newweight');
1655 return true;
1659 * Turns the display of normal blocks either on or off.
1661 * @param bool $setting
1663 public function show_only_fake_blocks($setting = true) {
1664 $this->fakeblocksonly = $setting;
1668 /// Helper functions for working with block classes ============================
1671 * Call a class method (one that does not require a block instance) on a block class.
1673 * @param string $blockname the name of the block.
1674 * @param string $method the method name.
1675 * @param array $param parameters to pass to the method.
1676 * @return mixed whatever the method returns.
1678 function block_method_result($blockname, $method, $param = NULL) {
1679 if(!block_load_class($blockname)) {
1680 return NULL;
1682 return call_user_func(array('block_'.$blockname, $method), $param);
1686 * Creates a new instance of the specified block class.
1688 * @param string $blockname the name of the block.
1689 * @param $instance block_instances DB table row (optional).
1690 * @param moodle_page $page the page this block is appearing on.
1691 * @return block_base the requested block instance.
1693 function block_instance($blockname, $instance = NULL, $page = NULL) {
1694 if(!block_load_class($blockname)) {
1695 return false;
1697 $classname = 'block_'.$blockname;
1698 $retval = new $classname;
1699 if($instance !== NULL) {
1700 if (is_null($page)) {
1701 global $PAGE;
1702 $page = $PAGE;
1704 $retval->_load_instance($instance, $page);
1706 return $retval;
1710 * Load the block class for a particular type of block.
1712 * @param string $blockname the name of the block.
1713 * @return boolean success or failure.
1715 function block_load_class($blockname) {
1716 global $CFG;
1718 if(empty($blockname)) {
1719 return false;
1722 $classname = 'block_'.$blockname;
1724 if(class_exists($classname)) {
1725 return true;
1728 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1730 if (file_exists($blockpath)) {
1731 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1732 include_once($blockpath);
1733 }else{
1734 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1735 return false;
1738 return class_exists($classname);
1742 * Given a specific page type, return all the page type patterns that might
1743 * match it.
1745 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1746 * @return array an array of all the page type patterns that might match this page type.
1748 function matching_page_type_patterns($pagetype) {
1749 $patterns = array($pagetype);
1750 $bits = explode('-', $pagetype);
1751 if (count($bits) == 3 && $bits[0] == 'mod') {
1752 if ($bits[2] == 'view') {
1753 $patterns[] = 'mod-*-view';
1754 } else if ($bits[2] == 'index') {
1755 $patterns[] = 'mod-*-index';
1758 while (count($bits) > 0) {
1759 $patterns[] = implode('-', $bits) . '-*';
1760 array_pop($bits);
1762 $patterns[] = '*';
1763 return $patterns;
1767 * Give an specific pattern, return all the page type patterns that would also match it.
1769 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
1770 * @return array of all the page type patterns matching.
1772 function matching_page_type_patterns_from_pattern($pattern) {
1773 $patterns = array($pattern);
1774 if ($pattern === '*') {
1775 return $patterns;
1778 // Only keep the part before the star because we will append -* to all the bits.
1779 $star = strpos($pattern, '-*');
1780 if ($star !== false) {
1781 $pattern = substr($pattern, 0, $star);
1784 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
1785 $patterns = array_unique($patterns);
1787 return $patterns;
1791 * Given a specific page type, parent context and currect context, return all the page type patterns
1792 * that might be used by this block.
1794 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1795 * @param stdClass $parentcontext Block's parent context
1796 * @param stdClass $currentcontext Current context of block
1797 * @return array an array of all the page type patterns that might match this page type.
1799 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1800 global $CFG; // Required for includes bellow.
1802 $bits = explode('-', $pagetype);
1804 $core = core_component::get_core_subsystems();
1805 $plugins = core_component::get_plugin_types();
1807 //progressively strip pieces off the page type looking for a match
1808 $componentarray = null;
1809 for ($i = count($bits); $i > 0; $i--) {
1810 $possiblecomponentarray = array_slice($bits, 0, $i);
1811 $possiblecomponent = implode('', $possiblecomponentarray);
1813 // Check to see if the component is a core component
1814 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1815 $libfile = $core[$possiblecomponent].'/lib.php';
1816 if (file_exists($libfile)) {
1817 require_once($libfile);
1818 $function = $possiblecomponent.'_page_type_list';
1819 if (function_exists($function)) {
1820 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1821 break;
1827 //check the plugin directory and look for a callback
1828 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1830 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1831 if (count($bits) > $i) {
1832 $pluginname = $bits[$i];
1833 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1834 if (!empty($directory)){
1835 $libfile = $directory.'/lib.php';
1836 if (file_exists($libfile)) {
1837 require_once($libfile);
1838 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1839 if (!function_exists($function)) {
1840 $function = $pluginname.'_page_type_list';
1842 if (function_exists($function)) {
1843 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1844 break;
1851 //we'll only get to here if we still don't have any patterns
1852 //the plugin type may have a callback
1853 $directory = $plugins[$possiblecomponent];
1854 $libfile = $directory.'/lib.php';
1855 if (file_exists($libfile)) {
1856 require_once($libfile);
1857 $function = $possiblecomponent.'_page_type_list';
1858 if (function_exists($function)) {
1859 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1860 break;
1867 if (empty($patterns)) {
1868 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1871 // Ensure that the * pattern is always available if editing block 'at distance', so
1872 // we always can 'bring back' it to the original context. MDL-30340
1873 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1874 // TODO: We could change the string here, showing its 'bring back' meaning
1875 $patterns['*'] = get_string('page-x', 'pagetype');
1878 return $patterns;
1882 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1884 * @param string $pagetype
1885 * @param stdClass $parentcontext
1886 * @param stdClass $currentcontext
1887 * @return array
1889 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1890 // Generate page type patterns based on current page type if
1891 // callbacks haven't been defined
1892 $patterns = array($pagetype => $pagetype);
1893 $bits = explode('-', $pagetype);
1894 while (count($bits) > 0) {
1895 $pattern = implode('-', $bits) . '-*';
1896 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1897 // guessing page type description
1898 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1899 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1900 } else {
1901 $patterns[$pattern] = $pattern;
1903 array_pop($bits);
1905 $patterns['*'] = get_string('page-x', 'pagetype');
1906 return $patterns;
1910 * Generates the page type list for the my moodle page
1912 * @param string $pagetype
1913 * @param stdClass $parentcontext
1914 * @param stdClass $currentcontext
1915 * @return array
1917 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1918 return array('my-index' => get_string('page-my-index', 'pagetype'));
1922 * Generates the page type list for a module by either locating and using the modules callback
1923 * or by generating a default list.
1925 * @param string $pagetype
1926 * @param stdClass $parentcontext
1927 * @param stdClass $currentcontext
1928 * @return array
1930 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1931 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1932 if (empty($patterns)) {
1933 // if modules don't have callbacks
1934 // generate two default page type patterns for modules only
1935 $bits = explode('-', $pagetype);
1936 $patterns = array($pagetype => $pagetype);
1937 if ($bits[2] == 'view') {
1938 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1939 } else if ($bits[2] == 'index') {
1940 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1943 return $patterns;
1945 /// Functions update the blocks if required by the request parameters ==========
1948 * Return a {@link block_contents} representing the add a new block UI, if
1949 * this user is allowed to see it.
1951 * @return block_contents an appropriate block_contents, or null if the user
1952 * cannot add any blocks here.
1954 function block_add_block_ui($page, $output) {
1955 global $CFG, $OUTPUT;
1956 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1957 return null;
1960 $bc = new block_contents();
1961 $bc->title = get_string('addblock');
1962 $bc->add_class('block_adminblock');
1963 $bc->attributes['data-block'] = 'adminblock';
1965 $missingblocks = $page->blocks->get_addable_blocks();
1966 if (empty($missingblocks)) {
1967 $bc->content = get_string('noblockstoaddhere');
1968 return $bc;
1971 $menu = array();
1972 foreach ($missingblocks as $block) {
1973 $blockobject = block_instance($block->name);
1974 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1975 $menu[$block->name] = $blockobject->get_title();
1978 core_collator::asort($menu);
1980 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1981 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1982 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1983 $bc->content = $OUTPUT->render($select);
1984 return $bc;
1987 // Functions that have been deprecated by block_manager =======================
1990 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1992 * This function returns an array with the IDs of any blocks that you can add to your page.
1993 * Parameters are passed by reference for speed; they are not modified at all.
1995 * @param $page the page object.
1996 * @param $blockmanager Not used.
1997 * @return array of block type ids.
1999 function blocks_get_missing(&$page, &$blockmanager) {
2000 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER);
2001 $blocks = $page->blocks->get_addable_blocks();
2002 $ids = array();
2003 foreach ($blocks as $block) {
2004 $ids[] = $block->id;
2006 return $ids;
2010 * Actually delete from the database any blocks that are currently on this page,
2011 * but which should not be there according to blocks_name_allowed_in_format.
2013 * @todo Write/Fix this function. Currently returns immediately
2014 * @param $course
2016 function blocks_remove_inappropriate($course) {
2017 // TODO
2018 return;
2020 $blockmanager = blocks_get_by_page($page);
2022 if (empty($blockmanager)) {
2023 return;
2026 if (($pageformat = $page->pagetype) == NULL) {
2027 return;
2030 foreach($blockmanager as $region) {
2031 foreach($region as $instance) {
2032 $block = blocks_get_record($instance->blockid);
2033 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
2034 blocks_delete_instance($instance->instance);
2041 * Check that a given name is in a permittable format
2043 * @param string $name
2044 * @param string $pageformat
2045 * @return bool
2047 function blocks_name_allowed_in_format($name, $pageformat) {
2048 $accept = NULL;
2049 $maxdepth = -1;
2050 if (!$bi = block_instance($name)) {
2051 return false;
2054 $formats = $bi->applicable_formats();
2055 if (!$formats) {
2056 $formats = array();
2058 foreach ($formats as $format => $allowed) {
2059 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2060 $depth = substr_count($format, '-');
2061 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2062 $maxdepth = $depth;
2063 $accept = $allowed;
2066 if ($accept === NULL) {
2067 $accept = !empty($formats['all']);
2069 return $accept;
2073 * Delete a block, and associated data.
2075 * @param object $instance a row from the block_instances table
2076 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2077 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2079 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2080 global $DB;
2082 if ($block = block_instance($instance->blockname, $instance)) {
2083 $block->instance_delete();
2085 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2087 if (!$skipblockstables) {
2088 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2089 $DB->delete_records('block_instances', array('id' => $instance->id));
2090 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2095 * Delete all the blocks that belong to a particular context.
2097 * @param int $contextid the context id.
2099 function blocks_delete_all_for_context($contextid) {
2100 global $DB;
2101 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2102 foreach ($instances as $instance) {
2103 blocks_delete_instance($instance, true);
2105 $instances->close();
2106 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2107 $DB->delete_records('block_positions', array('contextid' => $contextid));
2111 * Set a block to be visible or hidden on a particular page.
2113 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2114 * block_positions table as return by block_manager.
2115 * @param moodle_page $page the back to set the visibility with respect to.
2116 * @param integer $newvisibility 1 for visible, 0 for hidden.
2118 function blocks_set_visibility($instance, $page, $newvisibility) {
2119 global $DB;
2120 if (!empty($instance->blockpositionid)) {
2121 // Already have local information on this page.
2122 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2123 return;
2126 // Create a new block_positions record.
2127 $bp = new stdClass;
2128 $bp->blockinstanceid = $instance->id;
2129 $bp->contextid = $page->context->id;
2130 $bp->pagetype = $page->pagetype;
2131 if ($page->subpage) {
2132 $bp->subpage = $page->subpage;
2134 $bp->visible = $newvisibility;
2135 $bp->region = $instance->defaultregion;
2136 $bp->weight = $instance->defaultweight;
2137 $DB->insert_record('block_positions', $bp);
2141 * @deprecated since 2.0
2142 * Delete all the blocks from a particular page.
2144 * @param string $pagetype the page type.
2145 * @param integer $pageid the page id.
2146 * @return bool success or failure.
2148 function blocks_delete_all_on_page($pagetype, $pageid) {
2149 global $DB;
2151 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
2152 'This function cannot work any more. Doing nothing. ' .
2153 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER);
2154 return false;
2158 * Get the block record for a particular blockid - that is, a particular type os block.
2160 * @param $int blockid block type id. If null, an array of all block types is returned.
2161 * @param bool $notusedanymore No longer used.
2162 * @return array|object row from block table, or all rows.
2164 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2165 global $PAGE;
2166 $blocks = $PAGE->blocks->get_installed_blocks();
2167 if ($blockid === NULL) {
2168 return $blocks;
2169 } else if (isset($blocks[$blockid])) {
2170 return $blocks[$blockid];
2171 } else {
2172 return false;
2177 * Find a given block by its blockid within a provide array
2179 * @param int $blockid
2180 * @param array $blocksarray
2181 * @return bool|object Instance if found else false
2183 function blocks_find_block($blockid, $blocksarray) {
2184 if (empty($blocksarray)) {
2185 return false;
2187 foreach($blocksarray as $blockgroup) {
2188 if (empty($blockgroup)) {
2189 continue;
2191 foreach($blockgroup as $instance) {
2192 if($instance->blockid == $blockid) {
2193 return $instance;
2197 return false;
2200 // Functions for programatically adding default blocks to pages ================
2203 * Parse a list of default blocks. See config-dist for a description of the format.
2205 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2206 * @return array the parsed list of default blocks
2208 function blocks_parse_default_blocks_list($blocksstr) {
2209 $blocks = array();
2210 $bits = explode(':', $blocksstr);
2211 if (!empty($bits)) {
2212 $leftbits = trim(array_shift($bits));
2213 if ($leftbits != '') {
2214 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2217 if (!empty($bits)) {
2218 $rightbits = trim(array_shift($bits));
2219 if ($rightbits != '') {
2220 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2223 return $blocks;
2227 * @return array the blocks that should be added to the site course by default.
2229 function blocks_get_default_site_course_blocks() {
2230 global $CFG;
2232 if (!empty($CFG->defaultblocks_site)) {
2233 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2234 } else {
2235 return array(
2236 BLOCK_POS_LEFT => array('site_main_menu'),
2237 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2243 * Add the default blocks to a course.
2245 * @param object $course a course object.
2247 function blocks_add_default_course_blocks($course) {
2248 global $CFG;
2250 if (!empty($CFG->defaultblocks_override)) {
2251 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2253 } else if ($course->id == SITEID) {
2254 $blocknames = blocks_get_default_site_course_blocks();
2256 } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2257 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2259 } else {
2260 require_once($CFG->dirroot. '/course/lib.php');
2261 $blocknames = course_get_format($course)->get_default_blocks();
2265 if ($course->id == SITEID) {
2266 $pagetypepattern = 'site-index';
2267 } else {
2268 $pagetypepattern = 'course-view-*';
2270 $page = new moodle_page();
2271 $page->set_course($course);
2272 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2276 * Add the default system-context blocks. E.g. the admin tree.
2278 function blocks_add_default_system_blocks() {
2279 global $DB;
2281 $page = new moodle_page();
2282 $page->set_context(context_system::instance());
2283 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2284 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2286 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2287 $subpagepattern = $defaultmypage->id;
2288 } else {
2289 $subpagepattern = null;
2292 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);