MDL-49823 webservice: Support gravatar profile images
[moodle.git] / lib / blocklib.php
blob56208b6fdc63988ce31314852bee8393c2f63aa4
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
23 * @package core
24 * @subpackage block
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**#@+
32 * Default names for the block regions in the standard theme.
34 define('BLOCK_POS_LEFT', 'side-pre');
35 define('BLOCK_POS_RIGHT', 'side-post');
36 /**#@-*/
38 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
39 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
40 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
42 define('BUI_CONTEXTS_CURRENT', 0);
43 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
45 /**
46 * Exception thrown when someone tried to do something with a block that does
47 * not exist on a page.
49 * @copyright 2009 Tim Hunt
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 * @since Moodle 2.0
53 class block_not_on_page_exception extends moodle_exception {
54 /**
55 * Constructor
56 * @param int $instanceid the block instance id of the block that was looked for.
57 * @param object $page the current page.
59 public function __construct($instanceid, $page) {
60 $a = new stdClass;
61 $a->instanceid = $instanceid;
62 $a->url = $page->url->out();
63 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
67 /**
68 * This class keeps track of the block that should appear on a moodle_page.
70 * The page to work with as passed to the constructor.
72 * @copyright 2009 Tim Hunt
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
74 * @since Moodle 2.0
76 class block_manager {
77 /**
78 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
79 * although other weights are valid.
81 const MAX_WEIGHT = 10;
83 /// Field declarations =========================================================
85 /**
86 * the moodle_page we are managing blocks for.
87 * @var moodle_page
89 protected $page;
91 /** @var array region name => 1.*/
92 protected $regions = array();
94 /** @var string the region where new blocks are added.*/
95 protected $defaultregion = null;
97 /** @var array will be $DB->get_records('blocks') */
98 protected $allblocks = null;
101 * @var array blocks that this user can add to this page. Will be a subset
102 * of $allblocks, but with array keys block->name. Access this via the
103 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
105 protected $addableblocks = null;
108 * Will be an array region-name => array(db rows loaded in load_blocks);
109 * @var array
111 protected $birecordsbyregion = null;
114 * array region-name => array(block objects); populated as necessary by
115 * the ensure_instances_exist method.
116 * @var array
118 protected $blockinstances = array();
121 * array region-name => array(block_contents objects) what actually needs to
122 * be displayed in each region.
123 * @var array
125 protected $visibleblockcontent = array();
128 * array region-name => array(block_contents objects) extra block-like things
129 * to be displayed in each region, before the real blocks.
130 * @var array
132 protected $extracontent = array();
135 * Used by the block move id, to track whether a block is currently being moved.
137 * When you click on the move icon of a block, first the page needs to reload with
138 * extra UI for choosing a new position for a particular block. In that situation
139 * this field holds the id of the block being moved.
141 * @var integer|null
143 protected $movingblock = null;
146 * Show only fake blocks
148 protected $fakeblocksonly = false;
150 /// Constructor ================================================================
153 * Constructor.
154 * @param object $page the moodle_page object object we are managing the blocks for,
155 * or a reasonable faxilimily. (See the comment at the top of this class
156 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
158 public function __construct($page) {
159 $this->page = $page;
162 /// Getter methods =============================================================
165 * Get an array of all region names on this page where a block may appear
167 * @return array the internal names of the regions on this page where block may appear.
169 public function get_regions() {
170 if (is_null($this->defaultregion)) {
171 $this->page->initialise_theme_and_output();
173 return array_keys($this->regions);
177 * Get the region name of the region blocks are added to by default
179 * @return string the internal names of the region where new blocks are added
180 * by default, and where any blocks from an unrecognised region are shown.
181 * (Imagine that blocks were added with one theme selected, then you switched
182 * to a theme with different block positions.)
184 public function get_default_region() {
185 $this->page->initialise_theme_and_output();
186 return $this->defaultregion;
190 * The list of block types that may be added to this page.
192 * @return array block name => record from block table.
194 public function get_addable_blocks() {
195 $this->check_is_loaded();
197 if (!is_null($this->addableblocks)) {
198 return $this->addableblocks;
201 // Lazy load.
202 $this->addableblocks = array();
204 $allblocks = blocks_get_record();
205 if (empty($allblocks)) {
206 return $this->addableblocks;
209 $unaddableblocks = self::get_undeletable_block_types();
210 $pageformat = $this->page->pagetype;
211 foreach($allblocks as $block) {
212 if (!$bi = block_instance($block->name)) {
213 continue;
215 if ($block->visible && !in_array($block->name, $unaddableblocks) &&
216 ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
217 blocks_name_allowed_in_format($block->name, $pageformat) &&
218 $bi->user_can_addto($this->page)) {
219 $this->addableblocks[$block->name] = $block;
223 return $this->addableblocks;
227 * Given a block name, find out of any of them are currently present in the page
229 * @param string $blockname - the basic name of a block (eg "navigation")
230 * @return boolean - is there one of these blocks in the current page?
232 public function is_block_present($blockname) {
233 if (empty($this->blockinstances)) {
234 return false;
237 foreach ($this->blockinstances as $region) {
238 foreach ($region as $instance) {
239 if (empty($instance->instance->blockname)) {
240 continue;
242 if ($instance->instance->blockname == $blockname) {
243 return true;
247 return false;
251 * Find out if a block type is known by the system
253 * @param string $blockname the name of the type of block.
254 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
255 * @return boolean true if this block in installed.
257 public function is_known_block_type($blockname, $includeinvisible = false) {
258 $blocks = $this->get_installed_blocks();
259 foreach ($blocks as $block) {
260 if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
261 return true;
264 return false;
268 * Find out if a region exists on a page
270 * @param string $region a region name
271 * @return boolean true if this region exists on this page.
273 public function is_known_region($region) {
274 return array_key_exists($region, $this->regions);
278 * Get an array of all blocks within a given region
280 * @param string $region a block region that exists on this page.
281 * @return array of block instances.
283 public function get_blocks_for_region($region) {
284 $this->check_is_loaded();
285 $this->ensure_instances_exist($region);
286 return $this->blockinstances[$region];
290 * Returns an array of block content objects that exist in a region
292 * @param string $region a block region that exists on this page.
293 * @return array of block block_contents objects for all the blocks in a region.
295 public function get_content_for_region($region, $output) {
296 $this->check_is_loaded();
297 $this->ensure_content_created($region, $output);
298 return $this->visibleblockcontent[$region];
302 * Helper method used by get_content_for_region.
303 * @param string $region region name
304 * @param float $weight weight. May be fractional, since you may want to move a block
305 * between ones with weight 2 and 3, say ($weight would be 2.5).
306 * @return string URL for moving block $this->movingblock to this position.
308 protected function get_move_target_url($region, $weight) {
309 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
310 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
314 * Determine whether a region contains anything. (Either any real blocks, or
315 * the add new block UI.)
317 * (You may wonder why the $output parameter is required. Unfortunately,
318 * because of the way that blocks work, the only reliable way to find out
319 * if a block will be visible is to get the content for output, and to
320 * get the content, you need a renderer. Fortunately, this is not a
321 * performance problem, because we cache the output that is generated, and
322 * in almost every case where we call region_has_content, we are about to
323 * output the blocks anyway, so we are not doing wasted effort.)
325 * @param string $region a block region that exists on this page.
326 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
327 * @return boolean Whether there is anything in this region.
329 public function region_has_content($region, $output) {
331 if (!$this->is_known_region($region)) {
332 return false;
334 $this->check_is_loaded();
335 $this->ensure_content_created($region, $output);
336 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
337 // Mark Nielsen's patch - part 1
338 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
339 // If editing is on, we need all the block regions visible, for the
340 // move blocks UI.
341 return true;
343 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
347 * Get an array of all of the installed blocks.
349 * @return array contents of the block table.
351 public function get_installed_blocks() {
352 global $DB;
353 if (is_null($this->allblocks)) {
354 $this->allblocks = $DB->get_records('block');
356 return $this->allblocks;
360 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
362 public static function get_undeletable_block_types() {
363 global $CFG;
365 if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
366 return array('navigation','settings');
367 } else if (is_string($CFG->undeletableblocktypes)) {
368 return explode(',', $CFG->undeletableblocktypes);
369 } else {
370 return $CFG->undeletableblocktypes;
374 /// Setter methods =============================================================
377 * Add a region to a page
379 * @param string $region add a named region where blocks may appear on the current page.
380 * This is an internal name, like 'side-pre', not a string to display in the UI.
381 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
383 public function add_region($region, $custom = true) {
384 global $SESSION;
385 $this->check_not_yet_loaded();
386 if ($custom) {
387 if (array_key_exists($region, $this->regions)) {
388 // This here is EXACTLY why we should not be adding block regions into a page. It should
389 // ALWAYS be done in a theme layout.
390 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
392 // We need to register this custom region against the page type being used.
393 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
394 $type = $this->page->pagetype;
395 if (!isset($SESSION->custom_block_regions)) {
396 $SESSION->custom_block_regions = array($type => array($region));
397 } else if (!isset($SESSION->custom_block_regions[$type])) {
398 $SESSION->custom_block_regions[$type] = array($region);
399 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
400 $SESSION->custom_block_regions[$type][] = $region;
403 $this->regions[$region] = 1;
407 * Add an array of regions
408 * @see add_region()
410 * @param array $regions this utility method calls add_region for each array element.
412 public function add_regions($regions, $custom = true) {
413 foreach ($regions as $region) {
414 $this->add_region($region, $custom);
419 * Finds custom block regions associated with a page type and registers them with this block manager.
421 * @param string $pagetype
423 public function add_custom_regions_for_pagetype($pagetype) {
424 global $SESSION;
425 if (isset($SESSION->custom_block_regions[$pagetype])) {
426 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
427 $this->add_region($customregion, false);
433 * Set the default region for new blocks on the page
435 * @param string $defaultregion the internal names of the region where new
436 * blocks should be added by default, and where any blocks from an
437 * unrecognised region are shown.
439 public function set_default_region($defaultregion) {
440 $this->check_not_yet_loaded();
441 if ($defaultregion) {
442 $this->check_region_is_known($defaultregion);
444 $this->defaultregion = $defaultregion;
448 * Add something that looks like a block, but which isn't an actual block_instance,
449 * to this page.
451 * @param block_contents $bc the content of the block-like thing.
452 * @param string $region a block region that exists on this page.
454 public function add_fake_block($bc, $region) {
455 $this->page->initialise_theme_and_output();
456 if (!$this->is_known_region($region)) {
457 $region = $this->get_default_region();
459 if (array_key_exists($region, $this->visibleblockcontent)) {
460 throw new coding_exception('block_manager has already prepared the blocks in region ' .
461 $region . 'for output. It is too late to add a fake block.');
463 if (!isset($bc->attributes['data-block'])) {
464 $bc->attributes['data-block'] = '_fake';
466 $bc->attributes['class'] .= ' block_fake';
467 $this->extracontent[$region][] = $bc;
471 * Checks to see whether all of the blocks within the given region are docked
473 * @see region_uses_dock
474 * @param string $region
475 * @return bool True if all of the blocks within that region are docked
477 public function region_completely_docked($region, $output) {
478 global $CFG;
479 // If theme doesn't allow docking or allowblockstodock is not set, then return.
480 if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
481 return false;
484 // Do not dock the region when the user attemps to move a block.
485 if ($this->movingblock) {
486 return false;
489 // Block regions should not be docked during editing when all the blocks are hidden.
490 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
491 return false;
494 $this->check_is_loaded();
495 $this->ensure_content_created($region, $output);
496 if (!$this->region_has_content($region, $output)) {
497 // If the region has no content then nothing is docked at all of course.
498 return false;
500 foreach ($this->visibleblockcontent[$region] as $instance) {
501 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
502 return false;
505 return true;
509 * Checks to see whether any of the blocks within the given regions are docked
511 * @see region_completely_docked
512 * @param array|string $regions array of regions (or single region)
513 * @return bool True if any of the blocks within that region are docked
515 public function region_uses_dock($regions, $output) {
516 if (!$this->page->theme->enable_dock) {
517 return false;
519 $this->check_is_loaded();
520 foreach((array)$regions as $region) {
521 $this->ensure_content_created($region, $output);
522 foreach($this->visibleblockcontent[$region] as $instance) {
523 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
524 return true;
528 return false;
531 /// Actions ====================================================================
534 * This method actually loads the blocks for our page from the database.
536 * @param boolean|null $includeinvisible
537 * null (default) - load hidden blocks if $this->page->user_is_editing();
538 * true - load hidden blocks.
539 * false - don't load hidden blocks.
541 public function load_blocks($includeinvisible = null) {
542 global $DB, $CFG;
544 if (!is_null($this->birecordsbyregion)) {
545 // Already done.
546 return;
549 if ($CFG->version < 2009050619) {
550 // Upgrade/install not complete. Don't try too show any blocks.
551 $this->birecordsbyregion = array();
552 return;
555 // Ensure we have been initialised.
556 if (is_null($this->defaultregion)) {
557 $this->page->initialise_theme_and_output();
558 // If there are still no block regions, then there are no blocks on this page.
559 if (empty($this->regions)) {
560 $this->birecordsbyregion = array();
561 return;
565 // Check if we need to load normal blocks
566 if ($this->fakeblocksonly) {
567 $this->birecordsbyregion = $this->prepare_per_region_arrays();
568 return;
571 if (is_null($includeinvisible)) {
572 $includeinvisible = $this->page->user_is_editing();
574 if ($includeinvisible) {
575 $visiblecheck = '';
576 } else {
577 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
580 $context = $this->page->context;
581 $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
582 $parentcontextparams = array();
583 $parentcontextids = $context->get_parent_context_ids();
584 if ($parentcontextids) {
585 list($parentcontexttest, $parentcontextparams) =
586 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
587 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
590 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
591 list($pagetypepatterntest, $pagetypepatternparams) =
592 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
594 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
595 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
597 $systemcontext = context_system::instance();
598 $params = array(
599 'contextlevel' => CONTEXT_BLOCK,
600 'subpage1' => $this->page->subpage,
601 'subpage2' => $this->page->subpage,
602 'contextid1' => $context->id,
603 'contextid2' => $context->id,
604 'contextid3' => $systemcontext->id,
605 'pagetype' => $this->page->pagetype,
607 if ($this->page->subpage === '') {
608 $params['subpage1'] = '';
609 $params['subpage2'] = '';
611 $sql = "SELECT
612 bi.id,
613 bp.id AS blockpositionid,
614 bi.blockname,
615 bi.parentcontextid,
616 bi.showinsubcontexts,
617 bi.pagetypepattern,
618 bi.subpagepattern,
619 bi.defaultregion,
620 bi.defaultweight,
621 COALESCE(bp.visible, 1) AS visible,
622 COALESCE(bp.region, bi.defaultregion) AS region,
623 COALESCE(bp.weight, bi.defaultweight) AS weight,
624 bi.configdata
625 $ccselect
627 FROM {block_instances} bi
628 JOIN {block} b ON bi.blockname = b.name
629 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
630 AND bp.contextid = :contextid1
631 AND bp.pagetype = :pagetype
632 AND bp.subpage = :subpage1
633 $ccjoin
635 WHERE
636 $contexttest
637 AND bi.pagetypepattern $pagetypepatterntest
638 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
639 $visiblecheck
640 AND b.visible = 1
642 ORDER BY
643 COALESCE(bp.region, bi.defaultregion),
644 COALESCE(bp.weight, bi.defaultweight),
645 bi.id";
646 $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
648 $this->birecordsbyregion = $this->prepare_per_region_arrays();
649 $unknown = array();
650 foreach ($blockinstances as $bi) {
651 context_helper::preload_from_record($bi);
652 if ($this->is_known_region($bi->region)) {
653 $this->birecordsbyregion[$bi->region][] = $bi;
654 } else {
655 $unknown[] = $bi;
659 // Pages don't necessarily have a defaultregion. The one time this can
660 // happen is when there are no theme block regions, but the script itself
661 // has a block region in the main content area.
662 if (!empty($this->defaultregion)) {
663 $this->birecordsbyregion[$this->defaultregion] =
664 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
669 * Add a block to the current page, or related pages. The block is added to
670 * context $this->page->contextid. If $pagetypepattern $subpagepattern
672 * @param string $blockname The type of block to add.
673 * @param string $region the block region on this page to add the block to.
674 * @param integer $weight determines the order where this block appears in the region.
675 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
676 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
677 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
679 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
680 global $DB;
681 // Allow invisible blocks because this is used when adding default page blocks, which
682 // might include invisible ones if the user makes some default blocks invisible
683 $this->check_known_block_type($blockname, true);
684 $this->check_region_is_known($region);
686 if (empty($pagetypepattern)) {
687 $pagetypepattern = $this->page->pagetype;
690 $blockinstance = new stdClass;
691 $blockinstance->blockname = $blockname;
692 $blockinstance->parentcontextid = $this->page->context->id;
693 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
694 $blockinstance->pagetypepattern = $pagetypepattern;
695 $blockinstance->subpagepattern = $subpagepattern;
696 $blockinstance->defaultregion = $region;
697 $blockinstance->defaultweight = $weight;
698 $blockinstance->configdata = '';
699 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
701 // Ensure the block context is created.
702 context_block::instance($blockinstance->id);
704 // If the new instance was created, allow it to do additional setup
705 if ($block = block_instance($blockname, $blockinstance)) {
706 $block->instance_create();
710 public function add_block_at_end_of_default_region($blockname) {
711 $defaulregion = $this->get_default_region();
713 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
714 if ($lastcurrentblock) {
715 $weight = $lastcurrentblock->weight + 1;
716 } else {
717 $weight = 0;
720 if ($this->page->subpage) {
721 $subpage = $this->page->subpage;
722 } else {
723 $subpage = null;
726 // Special case. Course view page type include the course format, but we
727 // want to add the block non-format-specifically.
728 $pagetypepattern = $this->page->pagetype;
729 if (strpos($pagetypepattern, 'course-view') === 0) {
730 $pagetypepattern = 'course-view-*';
733 // We should end using this for ALL the blocks, making always the 1st option
734 // the default one to be used. Until then, this is one hack to avoid the
735 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
736 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
737 // (the FIRST $pagetypepattern will be set)
739 // We are applying it to all blocks created in mod pages for now and only if the
740 // default pagetype is not one of the available options
741 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
742 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
743 // Only go for the first if the pagetype is not a valid option
744 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
745 $pagetypepattern = key($pagetypelist);
748 // Surely other pages like course-report will need this too, they just are not important
749 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
751 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
755 * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
756 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
757 * and incremented by the position of the block in the $blocks array
759 * @param array $blocks array with array keys the region names, and values an array of block names.
760 * @param string $pagetypepattern optional. Passed to {@link add_block()}
761 * @param string $subpagepattern optional. Passed to {@link add_block()}
762 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
763 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
765 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
766 $initialweight = $weight;
767 $this->add_regions(array_keys($blocks), false);
768 foreach ($blocks as $region => $regionblocks) {
769 foreach ($regionblocks as $offset => $blockname) {
770 $weight = $initialweight + $offset;
771 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
777 * Move a block to a new position on this page.
779 * If this block cannot appear on any other pages, then we change defaultposition/weight
780 * in the block_instances table. Otherwise we just set the position on this page.
782 * @param $blockinstanceid the block instance id.
783 * @param $newregion the new region name.
784 * @param $newweight the new weight.
786 public function reposition_block($blockinstanceid, $newregion, $newweight) {
787 global $DB;
789 $this->check_region_is_known($newregion);
790 $inst = $this->find_instance($blockinstanceid);
792 $bi = $inst->instance;
793 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
794 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
795 (!$this->page->subpage || $bi->subpagepattern)) {
797 // Set default position
798 $newbi = new stdClass;
799 $newbi->id = $bi->id;
800 $newbi->defaultregion = $newregion;
801 $newbi->defaultweight = $newweight;
802 $DB->update_record('block_instances', $newbi);
804 if ($bi->blockpositionid) {
805 $bp = new stdClass;
806 $bp->id = $bi->blockpositionid;
807 $bp->region = $newregion;
808 $bp->weight = $newweight;
809 $DB->update_record('block_positions', $bp);
812 } else {
813 // Just set position on this page.
814 $bp = new stdClass;
815 $bp->region = $newregion;
816 $bp->weight = $newweight;
818 if ($bi->blockpositionid) {
819 $bp->id = $bi->blockpositionid;
820 $DB->update_record('block_positions', $bp);
822 } else {
823 $bp->blockinstanceid = $bi->id;
824 $bp->contextid = $this->page->context->id;
825 $bp->pagetype = $this->page->pagetype;
826 if ($this->page->subpage) {
827 $bp->subpage = $this->page->subpage;
828 } else {
829 $bp->subpage = '';
831 $bp->visible = $bi->visible;
832 $DB->insert_record('block_positions', $bp);
838 * Find a given block by its instance id
840 * @param integer $instanceid
841 * @return block_base
843 public function find_instance($instanceid) {
844 foreach ($this->regions as $region => $notused) {
845 $this->ensure_instances_exist($region);
846 foreach($this->blockinstances[$region] as $instance) {
847 if ($instance->instance->id == $instanceid) {
848 return $instance;
852 throw new block_not_on_page_exception($instanceid, $this->page);
855 /// Inner workings =============================================================
858 * Check whether the page blocks have been loaded yet
860 * @return void Throws coding exception if already loaded
862 protected function check_not_yet_loaded() {
863 if (!is_null($this->birecordsbyregion)) {
864 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.');
869 * Check whether the page blocks have been loaded yet
871 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
873 * @return void Throws coding exception if already loaded
875 protected function check_is_loaded() {
876 if (is_null($this->birecordsbyregion)) {
877 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
882 * Check if a block type is known and usable
884 * @param string $blockname The block type name to search for
885 * @param bool $includeinvisible Include disabled block types in the initial pass
886 * @return void Coding Exception thrown if unknown or not enabled
888 protected function check_known_block_type($blockname, $includeinvisible = false) {
889 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
890 if ($this->is_known_block_type($blockname, true)) {
891 throw new coding_exception('Unknown block type ' . $blockname);
892 } else {
893 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
899 * Check if a region is known by its name
901 * @param string $region
902 * @return void Coding Exception thrown if the region is not known
904 protected function check_region_is_known($region) {
905 if (!$this->is_known_region($region)) {
906 throw new coding_exception('Trying to reference an unknown block region ' . $region);
911 * Returns an array of region names as keys and nested arrays for values
913 * @return array an array where the array keys are the region names, and the array
914 * values are empty arrays.
916 protected function prepare_per_region_arrays() {
917 $result = array();
918 foreach ($this->regions as $region => $notused) {
919 $result[$region] = array();
921 return $result;
925 * Create a set of new block instance from a record array
927 * @param array $birecords An array of block instance records
928 * @return array An array of instantiated block_instance objects
930 protected function create_block_instances($birecords) {
931 $results = array();
932 foreach ($birecords as $record) {
933 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
934 $results[] = $blockobject;
937 return $results;
941 * Create all the block instances for all the blocks that were loaded by
942 * load_blocks. This is used, for example, to ensure that all blocks get a
943 * chance to initialise themselves via the {@link block_base::specialize()}
944 * method, before any output is done.
946 public function create_all_block_instances() {
947 foreach ($this->get_regions() as $region) {
948 $this->ensure_instances_exist($region);
953 * Return an array of content objects from a set of block instances
955 * @param array $instances An array of block instances
956 * @param renderer_base The renderer to use.
957 * @param string $region the region name.
958 * @return array An array of block_content (and possibly block_move_target) objects.
960 protected function create_block_contents($instances, $output, $region) {
961 $results = array();
963 $lastweight = 0;
964 $lastblock = 0;
965 if ($this->movingblock) {
966 $first = reset($instances);
967 if ($first) {
968 $lastweight = $first->instance->weight - 2;
972 foreach ($instances as $instance) {
973 $content = $instance->get_content_for_output($output);
974 if (empty($content)) {
975 continue;
978 if ($this->movingblock && $lastweight != $instance->instance->weight &&
979 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
980 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
983 if ($content->blockinstanceid == $this->movingblock) {
984 $content->add_class('beingmoved');
985 $content->annotation .= get_string('movingthisblockcancel', 'block',
986 html_writer::link($this->page->url, get_string('cancel')));
989 $results[] = $content;
990 $lastweight = $instance->instance->weight;
991 $lastblock = $instance->instance->id;
994 if ($this->movingblock && $lastblock != $this->movingblock) {
995 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
997 return $results;
1001 * Ensure block instances exist for a given region
1003 * @param string $region Check for bi's with the instance with this name
1005 protected function ensure_instances_exist($region) {
1006 $this->check_region_is_known($region);
1007 if (!array_key_exists($region, $this->blockinstances)) {
1008 $this->blockinstances[$region] =
1009 $this->create_block_instances($this->birecordsbyregion[$region]);
1014 * Ensure that there is some content within the given region
1016 * @param string $region The name of the region to check
1018 public function ensure_content_created($region, $output) {
1019 $this->ensure_instances_exist($region);
1020 if (!array_key_exists($region, $this->visibleblockcontent)) {
1021 $contents = array();
1022 if (array_key_exists($region, $this->extracontent)) {
1023 $contents = $this->extracontent[$region];
1025 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1026 if ($region == $this->defaultregion) {
1027 $addblockui = block_add_block_ui($this->page, $output);
1028 if ($addblockui) {
1029 $contents[] = $addblockui;
1032 $this->visibleblockcontent[$region] = $contents;
1036 /// Process actions from the URL ===============================================
1039 * Get the appropriate list of editing icons for a block. This is used
1040 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1042 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1043 * @return an array in the format for {@link block_contents::$controls}
1045 public function edit_controls($block) {
1046 global $CFG;
1048 $controls = array();
1049 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1050 $blocktitle = $block->title;
1051 if (empty($blocktitle)) {
1052 $blocktitle = $block->arialabel;
1055 if ($this->page->user_can_edit_blocks()) {
1056 // Move icon.
1057 $str = new lang_string('moveblock', 'block', $blocktitle);
1058 $controls[] = new action_menu_link_primary(
1059 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1060 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1061 $str,
1062 array('class' => 'editing_move')
1067 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1068 // Edit config icon - always show - needed for positioning UI.
1069 $str = new lang_string('configureblock', 'block', $blocktitle);
1070 $controls[] = new action_menu_link_secondary(
1071 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1072 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1073 $str,
1074 array('class' => 'editing_edit')
1079 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1080 // Show/hide icon.
1081 if ($block->instance->visible) {
1082 $str = new lang_string('hideblock', 'block', $blocktitle);
1083 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1084 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1085 $attributes = array('class' => 'editing_hide');
1086 } else {
1087 $str = new lang_string('showblock', 'block', $blocktitle);
1088 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1089 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1090 $attributes = array('class' => 'editing_show');
1092 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1095 // Display either "Assign roles" or "Permissions" or "Change permissions" icon (whichever first is available).
1096 if ($this->page->pagetype != 'my-index') {
1097 $rolesurl = null;
1099 if (get_assignable_roles($block->context, ROLENAME_SHORT)) {
1100 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id));
1101 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1102 $icon = 'i/assignroles';
1103 } else if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) {
1104 $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id));
1105 $str = get_string('permissions', 'role');
1106 $icon = 'i/permissions';
1107 } else if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) {
1108 $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id));
1109 $str = get_string('checkpermissions', 'role');
1110 $icon = 'i/checkpermissions';
1113 if ($rolesurl) {
1114 //TODO: please note it is sloppy to pass urls through page parameters!!
1115 // it is shortened because some web servers (e.g. IIS by default) give
1116 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1117 $return = $this->page->url->out(false);
1118 $return = str_replace($CFG->wwwroot . '/', '', $return);
1119 $rolesurl->param('returnurl', $return);
1121 $controls[] = new action_menu_link_secondary(
1122 $rolesurl,
1123 new pix_icon($icon, $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1124 $str,
1125 array('class' => 'editing_roles')
1130 if ($this->user_can_delete_block($block)) {
1131 // Delete icon.
1132 $str = new lang_string('deleteblock', 'block', $blocktitle);
1133 $controls[] = new action_menu_link_secondary(
1134 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1135 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1136 $str,
1137 array('class' => 'editing_delete')
1141 return $controls;
1145 * @param block_base $block a block that appears on this page.
1146 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1148 protected function user_can_delete_block($block) {
1149 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1150 $block->user_can_addto($this->page) &&
1151 !in_array($block->instance->blockname, self::get_undeletable_block_types());
1155 * Process any block actions that were specified in the URL.
1157 * @return boolean true if anything was done. False if not.
1159 public function process_url_actions() {
1160 if (!$this->page->user_is_editing()) {
1161 return false;
1163 return $this->process_url_add() || $this->process_url_delete() ||
1164 $this->process_url_show_hide() || $this->process_url_edit() ||
1165 $this->process_url_move();
1169 * Handle adding a block.
1170 * @return boolean true if anything was done. False if not.
1172 public function process_url_add() {
1173 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1174 if (!$blocktype) {
1175 return false;
1178 require_sesskey();
1180 if (!$this->page->user_can_edit_blocks()) {
1181 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1184 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1185 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1188 $this->add_block_at_end_of_default_region($blocktype);
1190 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1191 $this->page->ensure_param_not_in_url('bui_addblock');
1193 return true;
1197 * Handle deleting a block.
1198 * @return boolean true if anything was done. False if not.
1200 public function process_url_delete() {
1201 global $CFG, $PAGE, $OUTPUT;
1203 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1204 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1206 if (!$blockid) {
1207 return false;
1210 require_sesskey();
1211 $block = $this->page->blocks->find_instance($blockid);
1212 if (!$this->user_can_delete_block($block)) {
1213 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1216 if (!$confirmdelete) {
1217 $deletepage = new moodle_page();
1218 $deletepage->set_pagelayout('admin');
1219 $deletepage->set_course($this->page->course);
1220 $deletepage->set_context($this->page->context);
1221 if ($this->page->cm) {
1222 $deletepage->set_cm($this->page->cm);
1225 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1226 $deleteurlparams = $this->page->url->params();
1227 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1228 $deletepage->set_block_actions_done();
1229 // At this point we are either going to redirect, or display the form, so
1230 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1231 $PAGE = $deletepage;
1232 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1233 $output = $deletepage->get_renderer('core');
1234 $OUTPUT = $output;
1236 $site = get_site();
1237 $blocktitle = $block->get_title();
1238 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1239 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1241 // If the block is being shown in sub contexts display a warning.
1242 if ($block->instance->showinsubcontexts == 1) {
1243 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1244 $systemcontext = context_system::instance();
1245 $messagestring = new stdClass();
1246 $messagestring->location = $parentcontext->get_context_name();
1248 // Checking for blocks that may have visibility on the front page and pages added on that.
1249 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1250 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1251 } else {
1252 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1253 $messagestring->pagetype = $block->instance->pagetypepattern;
1254 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1255 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1259 $message = get_string('deleteblockwarning', 'block', $messagestring);
1262 $PAGE->navbar->add($strdeletecheck);
1263 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1264 $PAGE->set_heading($site->fullname);
1265 echo $OUTPUT->header();
1266 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1267 $cancelurl = new moodle_url($deletepage->url);
1268 $yesbutton = new single_button($confirmurl, get_string('yes'));
1269 $nobutton = new single_button($cancelurl, get_string('no'));
1270 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1271 echo $OUTPUT->footer();
1272 // Make sure that nothing else happens after we have displayed this form.
1273 exit;
1274 } else {
1275 blocks_delete_instance($block->instance);
1276 // bui_deleteid and bui_confirm should not be in the PAGE url.
1277 $this->page->ensure_param_not_in_url('bui_deleteid');
1278 $this->page->ensure_param_not_in_url('bui_confirm');
1279 return true;
1284 * Handle showing or hiding a block.
1285 * @return boolean true if anything was done. False if not.
1287 public function process_url_show_hide() {
1288 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1289 $newvisibility = 0;
1290 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1291 $newvisibility = 1;
1292 } else {
1293 return false;
1296 require_sesskey();
1298 $block = $this->page->blocks->find_instance($blockid);
1300 if (!$this->page->user_can_edit_blocks()) {
1301 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1302 } else if (!$block->instance_can_be_hidden()) {
1303 return false;
1306 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1308 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1309 $this->page->ensure_param_not_in_url('bui_hideid');
1310 $this->page->ensure_param_not_in_url('bui_showid');
1312 return true;
1316 * Handle showing/processing the submission from the block editing form.
1317 * @return boolean true if the form was submitted and the new config saved. Does not
1318 * return if the editing form was displayed. False otherwise.
1320 public function process_url_edit() {
1321 global $CFG, $DB, $PAGE, $OUTPUT;
1323 $blockid = optional_param('bui_editid', null, PARAM_INT);
1324 if (!$blockid) {
1325 return false;
1328 require_sesskey();
1329 require_once($CFG->dirroot . '/blocks/edit_form.php');
1331 $block = $this->find_instance($blockid);
1333 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1334 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1337 $editpage = new moodle_page();
1338 $editpage->set_pagelayout('admin');
1339 $editpage->set_course($this->page->course);
1340 //$editpage->set_context($block->context);
1341 $editpage->set_context($this->page->context);
1342 if ($this->page->cm) {
1343 $editpage->set_cm($this->page->cm);
1345 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1346 $editurlparams = $this->page->url->params();
1347 $editurlparams['bui_editid'] = $blockid;
1348 $editpage->set_url($editurlbase, $editurlparams);
1349 $editpage->set_block_actions_done();
1350 // At this point we are either going to redirect, or display the form, so
1351 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1352 $PAGE = $editpage;
1353 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1354 $output = $editpage->get_renderer('core');
1355 $OUTPUT = $output;
1357 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1358 if (is_readable($formfile)) {
1359 require_once($formfile);
1360 $classname = 'block_' . $block->name() . '_edit_form';
1361 if (!class_exists($classname)) {
1362 $classname = 'block_edit_form';
1364 } else {
1365 $classname = 'block_edit_form';
1368 $mform = new $classname($editpage->url, $block, $this->page);
1369 $mform->set_data($block->instance);
1371 if ($mform->is_cancelled()) {
1372 redirect($this->page->url);
1374 } else if ($data = $mform->get_data()) {
1375 $bi = new stdClass;
1376 $bi->id = $block->instance->id;
1378 // This may get overwritten by the special case handling below.
1379 $bi->pagetypepattern = $data->bui_pagetypepattern;
1380 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1381 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1382 $bi->subpagepattern = null;
1383 } else {
1384 $bi->subpagepattern = $data->bui_subpagepattern;
1387 $systemcontext = context_system::instance();
1388 $frontpagecontext = context_course::instance(SITEID);
1389 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1391 // Updating stickiness and contexts. See MDL-21375 for details.
1392 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1394 // Explicitly set the default context
1395 $bi->parentcontextid = $parentcontext->id;
1397 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1399 // The interface here is a special case because the pagetype pattern is
1400 // totally derived from the context menu. Here are the excpetions. MDL-30340
1402 switch ($data->bui_contexts) {
1403 case BUI_CONTEXTS_ENTIRE_SITE:
1404 // The user wants to show the block across the entire site
1405 $bi->parentcontextid = $systemcontext->id;
1406 $bi->showinsubcontexts = true;
1407 $bi->pagetypepattern = '*';
1408 break;
1409 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1410 // The user wants the block shown on the front page and all subcontexts
1411 $bi->parentcontextid = $frontpagecontext->id;
1412 $bi->showinsubcontexts = true;
1413 $bi->pagetypepattern = '*';
1414 break;
1415 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1416 // The user want to show the front page on the frontpage only
1417 $bi->parentcontextid = $frontpagecontext->id;
1418 $bi->showinsubcontexts = false;
1419 $bi->pagetypepattern = 'site-index';
1420 // This is the only relevant page type anyway but we'll set it explicitly just
1421 // in case the front page grows site-index-* subpages of its own later
1422 break;
1427 $bits = explode('-', $bi->pagetypepattern);
1428 // hacks for some contexts
1429 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1430 // For course context
1431 // is page type pattern is mod-*, change showinsubcontext to 1
1432 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1433 $bi->showinsubcontexts = 1;
1434 } else {
1435 $bi->showinsubcontexts = 0;
1437 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1438 // for user context
1439 // subpagepattern should be null
1440 if ($bits[0] == 'user' or $bits[0] == 'my') {
1441 // we don't need subpagepattern in usercontext
1442 $bi->subpagepattern = null;
1446 $bi->defaultregion = $data->bui_defaultregion;
1447 $bi->defaultweight = $data->bui_defaultweight;
1448 $DB->update_record('block_instances', $bi);
1450 if (!empty($block->config)) {
1451 $config = clone($block->config);
1452 } else {
1453 $config = new stdClass;
1455 foreach ($data as $configfield => $value) {
1456 if (strpos($configfield, 'config_') !== 0) {
1457 continue;
1459 $field = substr($configfield, 7);
1460 $config->$field = $value;
1462 $block->instance_config_save($config);
1464 $bp = new stdClass;
1465 $bp->visible = $data->bui_visible;
1466 $bp->region = $data->bui_region;
1467 $bp->weight = $data->bui_weight;
1468 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1469 $data->bui_weight != $data->bui_defaultweight;
1471 if ($block->instance->blockpositionid && !$needbprecord) {
1472 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1474 } else if ($block->instance->blockpositionid && $needbprecord) {
1475 $bp->id = $block->instance->blockpositionid;
1476 $DB->update_record('block_positions', $bp);
1478 } else if ($needbprecord) {
1479 $bp->blockinstanceid = $block->instance->id;
1480 $bp->contextid = $this->page->context->id;
1481 $bp->pagetype = $this->page->pagetype;
1482 if ($this->page->subpage) {
1483 $bp->subpage = $this->page->subpage;
1484 } else {
1485 $bp->subpage = '';
1487 $DB->insert_record('block_positions', $bp);
1490 redirect($this->page->url);
1492 } else {
1493 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1494 $editpage->set_title($strheading);
1495 $editpage->set_heading($strheading);
1496 $bits = explode('-', $this->page->pagetype);
1497 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1498 // better navbar for tag pages
1499 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1500 $tag = tag_get('id', $this->page->subpage, '*');
1501 // tag search page doesn't have subpageid
1502 if ($tag) {
1503 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1506 $editpage->navbar->add($block->get_title());
1507 $editpage->navbar->add(get_string('configuration'));
1508 echo $output->header();
1509 echo $output->heading($strheading, 2);
1510 $mform->display();
1511 echo $output->footer();
1512 exit;
1517 * Handle showing/processing the submission from the block editing form.
1518 * @return boolean true if the form was submitted and the new config saved. Does not
1519 * return if the editing form was displayed. False otherwise.
1521 public function process_url_move() {
1522 global $CFG, $DB, $PAGE;
1524 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1525 if (!$blockid) {
1526 return false;
1529 require_sesskey();
1531 $block = $this->find_instance($blockid);
1533 if (!$this->page->user_can_edit_blocks()) {
1534 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1537 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1538 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1539 if (!$newregion || is_null($newweight)) {
1540 // Don't have a valid target position yet, must be just starting the move.
1541 $this->movingblock = $blockid;
1542 $this->page->ensure_param_not_in_url('bui_moveid');
1543 return false;
1546 if (!$this->is_known_region($newregion)) {
1547 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1550 // Move this block. This may involve moving other nearby blocks.
1551 $blocks = $this->birecordsbyregion[$newregion];
1553 $maxweight = self::MAX_WEIGHT;
1554 $minweight = -self::MAX_WEIGHT;
1556 // Initialise the used weights and spareweights array with the default values
1557 $spareweights = array();
1558 $usedweights = array();
1559 for ($i = $minweight; $i <= $maxweight; $i++) {
1560 $spareweights[$i] = $i;
1561 $usedweights[$i] = array();
1564 // Check each block and sort out where we have used weights
1565 foreach ($blocks as $bi) {
1566 if ($bi->weight > $maxweight) {
1567 // If this statement is true then the blocks weight is more than the
1568 // current maximum. To ensure that we can get the best block position
1569 // we will initialise elements within the usedweights and spareweights
1570 // arrays between the blocks weight (which will then be the new max) and
1571 // the current max
1572 $parseweight = $bi->weight;
1573 while (!array_key_exists($parseweight, $usedweights)) {
1574 $usedweights[$parseweight] = array();
1575 $spareweights[$parseweight] = $parseweight;
1576 $parseweight--;
1578 $maxweight = $bi->weight;
1579 } else if ($bi->weight < $minweight) {
1580 // As above except this time the blocks weight is LESS than the
1581 // the current minimum, so we will initialise the array from the
1582 // blocks weight (new minimum) to the current minimum
1583 $parseweight = $bi->weight;
1584 while (!array_key_exists($parseweight, $usedweights)) {
1585 $usedweights[$parseweight] = array();
1586 $spareweights[$parseweight] = $parseweight;
1587 $parseweight++;
1589 $minweight = $bi->weight;
1591 if ($bi->id != $block->instance->id) {
1592 unset($spareweights[$bi->weight]);
1593 $usedweights[$bi->weight][] = $bi->id;
1597 // First we find the nearest gap in the list of weights.
1598 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1599 $bestgap = null;
1600 foreach ($spareweights as $spareweight) {
1601 if (abs($newweight - $spareweight) < $bestdistance) {
1602 $bestdistance = abs($newweight - $spareweight);
1603 $bestgap = $spareweight;
1607 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1608 if (is_null($bestgap)) {
1609 $bestgap = self::MAX_WEIGHT + 1;
1610 while (!empty($usedweights[$bestgap])) {
1611 $bestgap++;
1615 // Now we know the gap we are aiming for, so move all the blocks along.
1616 if ($bestgap < $newweight) {
1617 $newweight = floor($newweight);
1618 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1619 if (array_key_exists($weight, $usedweights)) {
1620 foreach ($usedweights[$weight] as $biid) {
1621 $this->reposition_block($biid, $newregion, $weight - 1);
1625 $this->reposition_block($block->instance->id, $newregion, $newweight);
1626 } else {
1627 $newweight = ceil($newweight);
1628 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1629 if (array_key_exists($weight, $usedweights)) {
1630 foreach ($usedweights[$weight] as $biid) {
1631 $this->reposition_block($biid, $newregion, $weight + 1);
1635 $this->reposition_block($block->instance->id, $newregion, $newweight);
1638 $this->page->ensure_param_not_in_url('bui_moveid');
1639 $this->page->ensure_param_not_in_url('bui_newregion');
1640 $this->page->ensure_param_not_in_url('bui_newweight');
1641 return true;
1645 * Turns the display of normal blocks either on or off.
1647 * @param bool $setting
1649 public function show_only_fake_blocks($setting = true) {
1650 $this->fakeblocksonly = $setting;
1654 /// Helper functions for working with block classes ============================
1657 * Call a class method (one that does not require a block instance) on a block class.
1659 * @param string $blockname the name of the block.
1660 * @param string $method the method name.
1661 * @param array $param parameters to pass to the method.
1662 * @return mixed whatever the method returns.
1664 function block_method_result($blockname, $method, $param = NULL) {
1665 if(!block_load_class($blockname)) {
1666 return NULL;
1668 return call_user_func(array('block_'.$blockname, $method), $param);
1672 * Creates a new instance of the specified block class.
1674 * @param string $blockname the name of the block.
1675 * @param $instance block_instances DB table row (optional).
1676 * @param moodle_page $page the page this block is appearing on.
1677 * @return block_base the requested block instance.
1679 function block_instance($blockname, $instance = NULL, $page = NULL) {
1680 if(!block_load_class($blockname)) {
1681 return false;
1683 $classname = 'block_'.$blockname;
1684 $retval = new $classname;
1685 if($instance !== NULL) {
1686 if (is_null($page)) {
1687 global $PAGE;
1688 $page = $PAGE;
1690 $retval->_load_instance($instance, $page);
1692 return $retval;
1696 * Load the block class for a particular type of block.
1698 * @param string $blockname the name of the block.
1699 * @return boolean success or failure.
1701 function block_load_class($blockname) {
1702 global $CFG;
1704 if(empty($blockname)) {
1705 return false;
1708 $classname = 'block_'.$blockname;
1710 if(class_exists($classname)) {
1711 return true;
1714 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1716 if (file_exists($blockpath)) {
1717 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1718 include_once($blockpath);
1719 }else{
1720 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1721 return false;
1724 return class_exists($classname);
1728 * Given a specific page type, return all the page type patterns that might
1729 * match it.
1731 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1732 * @return array an array of all the page type patterns that might match this page type.
1734 function matching_page_type_patterns($pagetype) {
1735 $patterns = array($pagetype);
1736 $bits = explode('-', $pagetype);
1737 if (count($bits) == 3 && $bits[0] == 'mod') {
1738 if ($bits[2] == 'view') {
1739 $patterns[] = 'mod-*-view';
1740 } else if ($bits[2] == 'index') {
1741 $patterns[] = 'mod-*-index';
1744 while (count($bits) > 0) {
1745 $patterns[] = implode('-', $bits) . '-*';
1746 array_pop($bits);
1748 $patterns[] = '*';
1749 return $patterns;
1753 * Give an specific pattern, return all the page type patterns that would also match it.
1755 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
1756 * @return array of all the page type patterns matching.
1758 function matching_page_type_patterns_from_pattern($pattern) {
1759 $patterns = array($pattern);
1760 if ($pattern === '*') {
1761 return $patterns;
1764 // Only keep the part before the star because we will append -* to all the bits.
1765 $star = strpos($pattern, '-*');
1766 if ($star !== false) {
1767 $pattern = substr($pattern, 0, $star);
1770 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
1771 $patterns = array_unique($patterns);
1773 return $patterns;
1777 * Given a specific page type, parent context and currect context, return all the page type patterns
1778 * that might be used by this block.
1780 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1781 * @param stdClass $parentcontext Block's parent context
1782 * @param stdClass $currentcontext Current context of block
1783 * @return array an array of all the page type patterns that might match this page type.
1785 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1786 global $CFG; // Required for includes bellow.
1788 $bits = explode('-', $pagetype);
1790 $core = core_component::get_core_subsystems();
1791 $plugins = core_component::get_plugin_types();
1793 //progressively strip pieces off the page type looking for a match
1794 $componentarray = null;
1795 for ($i = count($bits); $i > 0; $i--) {
1796 $possiblecomponentarray = array_slice($bits, 0, $i);
1797 $possiblecomponent = implode('', $possiblecomponentarray);
1799 // Check to see if the component is a core component
1800 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1801 $libfile = $core[$possiblecomponent].'/lib.php';
1802 if (file_exists($libfile)) {
1803 require_once($libfile);
1804 $function = $possiblecomponent.'_page_type_list';
1805 if (function_exists($function)) {
1806 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1807 break;
1813 //check the plugin directory and look for a callback
1814 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1816 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1817 if (count($bits) > $i) {
1818 $pluginname = $bits[$i];
1819 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1820 if (!empty($directory)){
1821 $libfile = $directory.'/lib.php';
1822 if (file_exists($libfile)) {
1823 require_once($libfile);
1824 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1825 if (!function_exists($function)) {
1826 $function = $pluginname.'_page_type_list';
1828 if (function_exists($function)) {
1829 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1830 break;
1837 //we'll only get to here if we still don't have any patterns
1838 //the plugin type may have a callback
1839 $directory = $plugins[$possiblecomponent];
1840 $libfile = $directory.'/lib.php';
1841 if (file_exists($libfile)) {
1842 require_once($libfile);
1843 $function = $possiblecomponent.'_page_type_list';
1844 if (function_exists($function)) {
1845 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1846 break;
1853 if (empty($patterns)) {
1854 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1857 // Ensure that the * pattern is always available if editing block 'at distance', so
1858 // we always can 'bring back' it to the original context. MDL-30340
1859 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1860 // TODO: We could change the string here, showing its 'bring back' meaning
1861 $patterns['*'] = get_string('page-x', 'pagetype');
1864 return $patterns;
1868 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1870 * @param string $pagetype
1871 * @param stdClass $parentcontext
1872 * @param stdClass $currentcontext
1873 * @return array
1875 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1876 // Generate page type patterns based on current page type if
1877 // callbacks haven't been defined
1878 $patterns = array($pagetype => $pagetype);
1879 $bits = explode('-', $pagetype);
1880 while (count($bits) > 0) {
1881 $pattern = implode('-', $bits) . '-*';
1882 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1883 // guessing page type description
1884 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1885 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1886 } else {
1887 $patterns[$pattern] = $pattern;
1889 array_pop($bits);
1891 $patterns['*'] = get_string('page-x', 'pagetype');
1892 return $patterns;
1896 * Generates the page type list for the my moodle page
1898 * @param string $pagetype
1899 * @param stdClass $parentcontext
1900 * @param stdClass $currentcontext
1901 * @return array
1903 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1904 return array('my-index' => get_string('page-my-index', 'pagetype'));
1908 * Generates the page type list for a module by either locating and using the modules callback
1909 * or by generating a default list.
1911 * @param string $pagetype
1912 * @param stdClass $parentcontext
1913 * @param stdClass $currentcontext
1914 * @return array
1916 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1917 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1918 if (empty($patterns)) {
1919 // if modules don't have callbacks
1920 // generate two default page type patterns for modules only
1921 $bits = explode('-', $pagetype);
1922 $patterns = array($pagetype => $pagetype);
1923 if ($bits[2] == 'view') {
1924 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1925 } else if ($bits[2] == 'index') {
1926 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1929 return $patterns;
1931 /// Functions update the blocks if required by the request parameters ==========
1934 * Return a {@link block_contents} representing the add a new block UI, if
1935 * this user is allowed to see it.
1937 * @return block_contents an appropriate block_contents, or null if the user
1938 * cannot add any blocks here.
1940 function block_add_block_ui($page, $output) {
1941 global $CFG, $OUTPUT;
1942 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1943 return null;
1946 $bc = new block_contents();
1947 $bc->title = get_string('addblock');
1948 $bc->add_class('block_adminblock');
1949 $bc->attributes['data-block'] = 'adminblock';
1951 $missingblocks = $page->blocks->get_addable_blocks();
1952 if (empty($missingblocks)) {
1953 $bc->content = get_string('noblockstoaddhere');
1954 return $bc;
1957 $menu = array();
1958 foreach ($missingblocks as $block) {
1959 $blockobject = block_instance($block->name);
1960 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1961 $menu[$block->name] = $blockobject->get_title();
1964 core_collator::asort($menu);
1966 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1967 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1968 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1969 $bc->content = $OUTPUT->render($select);
1970 return $bc;
1974 * Actually delete from the database any blocks that are currently on this page,
1975 * but which should not be there according to blocks_name_allowed_in_format.
1977 * @todo Write/Fix this function. Currently returns immediately
1978 * @param $course
1980 function blocks_remove_inappropriate($course) {
1981 // TODO
1982 return;
1984 $blockmanager = blocks_get_by_page($page);
1986 if (empty($blockmanager)) {
1987 return;
1990 if (($pageformat = $page->pagetype) == NULL) {
1991 return;
1994 foreach($blockmanager as $region) {
1995 foreach($region as $instance) {
1996 $block = blocks_get_record($instance->blockid);
1997 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1998 blocks_delete_instance($instance->instance);
2005 * Check that a given name is in a permittable format
2007 * @param string $name
2008 * @param string $pageformat
2009 * @return bool
2011 function blocks_name_allowed_in_format($name, $pageformat) {
2012 $accept = NULL;
2013 $maxdepth = -1;
2014 if (!$bi = block_instance($name)) {
2015 return false;
2018 $formats = $bi->applicable_formats();
2019 if (!$formats) {
2020 $formats = array();
2022 foreach ($formats as $format => $allowed) {
2023 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2024 $depth = substr_count($format, '-');
2025 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2026 $maxdepth = $depth;
2027 $accept = $allowed;
2030 if ($accept === NULL) {
2031 $accept = !empty($formats['all']);
2033 return $accept;
2037 * Delete a block, and associated data.
2039 * @param object $instance a row from the block_instances table
2040 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2041 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2043 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2044 global $DB;
2046 if ($block = block_instance($instance->blockname, $instance)) {
2047 $block->instance_delete();
2049 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2051 if (!$skipblockstables) {
2052 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2053 $DB->delete_records('block_instances', array('id' => $instance->id));
2054 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2059 * Delete multiple blocks at once.
2061 * @param array $instanceids A list of block instance ID.
2063 function blocks_delete_instances($instanceids) {
2064 global $DB;
2066 $instances = $DB->get_recordset_list('block_instances', 'id', $instanceids);
2067 foreach ($instances as $instance) {
2068 blocks_delete_instance($instance, false, true);
2070 $instances->close();
2072 $DB->delete_records_list('block_positions', 'blockinstanceid', $instanceids);
2073 $DB->delete_records_list('block_instances', 'id', $instanceids);
2075 $preferences = array();
2076 foreach ($instanceids as $instanceid) {
2077 $preferences[] = 'block' . $instanceid . 'hidden';
2078 $preferences[] = 'docked_block_instance_' . $instanceid;
2080 $DB->delete_records_list('user_preferences', 'name', $preferences);
2084 * Delete all the blocks that belong to a particular context.
2086 * @param int $contextid the context id.
2088 function blocks_delete_all_for_context($contextid) {
2089 global $DB;
2090 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2091 foreach ($instances as $instance) {
2092 blocks_delete_instance($instance, true);
2094 $instances->close();
2095 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2096 $DB->delete_records('block_positions', array('contextid' => $contextid));
2100 * Set a block to be visible or hidden on a particular page.
2102 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2103 * block_positions table as return by block_manager.
2104 * @param moodle_page $page the back to set the visibility with respect to.
2105 * @param integer $newvisibility 1 for visible, 0 for hidden.
2107 function blocks_set_visibility($instance, $page, $newvisibility) {
2108 global $DB;
2109 if (!empty($instance->blockpositionid)) {
2110 // Already have local information on this page.
2111 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2112 return;
2115 // Create a new block_positions record.
2116 $bp = new stdClass;
2117 $bp->blockinstanceid = $instance->id;
2118 $bp->contextid = $page->context->id;
2119 $bp->pagetype = $page->pagetype;
2120 if ($page->subpage) {
2121 $bp->subpage = $page->subpage;
2123 $bp->visible = $newvisibility;
2124 $bp->region = $instance->defaultregion;
2125 $bp->weight = $instance->defaultweight;
2126 $DB->insert_record('block_positions', $bp);
2130 * Get the block record for a particular blockid - that is, a particular type os block.
2132 * @param $int blockid block type id. If null, an array of all block types is returned.
2133 * @param bool $notusedanymore No longer used.
2134 * @return array|object row from block table, or all rows.
2136 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2137 global $PAGE;
2138 $blocks = $PAGE->blocks->get_installed_blocks();
2139 if ($blockid === NULL) {
2140 return $blocks;
2141 } else if (isset($blocks[$blockid])) {
2142 return $blocks[$blockid];
2143 } else {
2144 return false;
2149 * Find a given block by its blockid within a provide array
2151 * @param int $blockid
2152 * @param array $blocksarray
2153 * @return bool|object Instance if found else false
2155 function blocks_find_block($blockid, $blocksarray) {
2156 if (empty($blocksarray)) {
2157 return false;
2159 foreach($blocksarray as $blockgroup) {
2160 if (empty($blockgroup)) {
2161 continue;
2163 foreach($blockgroup as $instance) {
2164 if($instance->blockid == $blockid) {
2165 return $instance;
2169 return false;
2172 // Functions for programatically adding default blocks to pages ================
2175 * Parse a list of default blocks. See config-dist for a description of the format.
2177 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2178 * @return array the parsed list of default blocks
2180 function blocks_parse_default_blocks_list($blocksstr) {
2181 $blocks = array();
2182 $bits = explode(':', $blocksstr);
2183 if (!empty($bits)) {
2184 $leftbits = trim(array_shift($bits));
2185 if ($leftbits != '') {
2186 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2189 if (!empty($bits)) {
2190 $rightbits = trim(array_shift($bits));
2191 if ($rightbits != '') {
2192 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2195 return $blocks;
2199 * @return array the blocks that should be added to the site course by default.
2201 function blocks_get_default_site_course_blocks() {
2202 global $CFG;
2204 if (!empty($CFG->defaultblocks_site)) {
2205 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2206 } else {
2207 return array(
2208 BLOCK_POS_LEFT => array('site_main_menu'),
2209 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2215 * Add the default blocks to a course.
2217 * @param object $course a course object.
2219 function blocks_add_default_course_blocks($course) {
2220 global $CFG;
2222 if (!empty($CFG->defaultblocks_override)) {
2223 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2225 } else if ($course->id == SITEID) {
2226 $blocknames = blocks_get_default_site_course_blocks();
2228 } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2229 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2231 } else {
2232 require_once($CFG->dirroot. '/course/lib.php');
2233 $blocknames = course_get_format($course)->get_default_blocks();
2237 if ($course->id == SITEID) {
2238 $pagetypepattern = 'site-index';
2239 } else {
2240 $pagetypepattern = 'course-view-*';
2242 $page = new moodle_page();
2243 $page->set_course($course);
2244 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2248 * Add the default system-context blocks. E.g. the admin tree.
2250 function blocks_add_default_system_blocks() {
2251 global $DB;
2253 $page = new moodle_page();
2254 $page->set_context(context_system::instance());
2255 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2256 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2258 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2259 $subpagepattern = $defaultmypage->id;
2260 } else {
2261 $subpagepattern = null;
2264 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2265 $newcontent = array('course_overview');
2266 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);