3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
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();
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');
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);
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
53 class block_not_on_page_exception
extends moodle_exception
{
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) {
61 $a->instanceid
= $instanceid;
62 $a->url
= $page->url
->out();
63 parent
::__construct('blockdoesnotexistonpage', '', $page->url
->out(), $a);
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
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 =========================================================
86 * the moodle_page we are managing blocks for.
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);
111 protected $birecordsbyregion = null;
114 * array region-name => array(block objects); populated as necessary by
115 * the ensure_instances_exist method.
118 protected $blockinstances = array();
121 * array region-name => array(block_contents objects) what actually needs to
122 * be displayed in each region.
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.
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.
143 protected $movingblock = null;
146 * Show only fake blocks
148 protected $fakeblocksonly = false;
150 /// 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) {
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
;
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
)) {
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
)) {
237 foreach ($this->blockinstances
as $region) {
238 foreach ($region as $instance) {
239 if (empty($instance->instance
->blockname
)) {
242 if ($instance->instance
->blockname
== $blockname) {
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
)) {
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)) {
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
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() {
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() {
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
);
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) {
385 $this->check_not_yet_loaded();
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
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) {
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,
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) {
479 // If theme doesn't allow docking or allowblockstodock is not set, then return.
480 if (!$this->page
->theme
->enable_dock ||
empty($CFG->allowblockstodock
)) {
484 // Do not dock the region when the user attemps to move a block.
485 if ($this->movingblock
) {
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()) {
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.
500 foreach ($this->visibleblockcontent
[$region] as $instance) {
501 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
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
) {
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)) {
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) {
544 if (!is_null($this->birecordsbyregion
)) {
549 if ($CFG->version
< 2009050619) {
550 // Upgrade/install not complete. Don't try too show any blocks.
551 $this->birecordsbyregion
= array();
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();
565 // Check if we need to load normal blocks
566 if ($this->fakeblocksonly
) {
567 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
571 if (is_null($includeinvisible)) {
572 $includeinvisible = $this->page
->user_is_editing();
574 if ($includeinvisible) {
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();
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'] = '';
613 bp.id AS blockpositionid,
616 bi.showinsubcontexts,
621 COALESCE(bp.visible, 1) AS visible,
622 COALESCE(bp.region, bi.defaultregion) AS region,
623 COALESCE(bp.weight, bi.defaultweight) AS weight,
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
637 AND bi.pagetypepattern $pagetypepatterntest
638 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
643 COALESCE(bp.region, bi.defaultregion),
644 COALESCE(bp.weight, bi.defaultweight),
646 $blockinstances = $DB->get_recordset_sql($sql, $params +
$parentcontextparams +
$pagetypepatternparams);
648 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
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;
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) {
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;
720 if ($this->page
->subpage
) {
721 $subpage = $this->page
->subpage
;
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) {
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
) {
806 $bp->id
= $bi->blockpositionid
;
807 $bp->region
= $newregion;
808 $bp->weight
= $newweight;
809 $DB->update_record('block_positions', $bp);
813 // Just set position on this page.
815 $bp->region
= $newregion;
816 $bp->weight
= $newweight;
818 if ($bi->blockpositionid
) {
819 $bp->id
= $bi->blockpositionid
;
820 $DB->update_record('block_positions', $bp);
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
;
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
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) {
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);
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() {
918 foreach ($this->regions
as $region => $notused) {
919 $result[$region] = array();
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) {
932 foreach ($birecords as $record) {
933 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
934 $results[] = $blockobject;
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) {
965 if ($this->movingblock
) {
966 $first = reset($instances);
968 $lastweight = $first->instance
->weight
- 2;
972 foreach ($instances as $instance) {
973 $content = $instance->get_content_for_output($output);
974 if (empty($content)) {
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));
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);
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) {
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()) {
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' => '')),
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' => '')),
1074 array('class' => 'editing_edit')
1079 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
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');
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 // Assign roles icon.
1096 if ($this->page
->pagetype
!= 'my-index' && has_capability('moodle/role:assign', $block->context
)) {
1097 //TODO: please note it is sloppy to pass urls through page parameters!!
1098 // it is shortened because some web servers (e.g. IIS by default) give
1099 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1100 $return = $this->page
->url
->out(false);
1101 $return = str_replace($CFG->wwwroot
. '/', '', $return);
1103 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context
->id
,
1104 'returnurl'=>$return));
1106 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1107 $controls[] = new action_menu_link_secondary(
1109 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1111 array('class' => 'editing_roles')
1115 if ($this->user_can_delete_block($block)) {
1117 $str = new lang_string('deleteblock', 'block', $blocktitle);
1118 $controls[] = new action_menu_link_secondary(
1119 new moodle_url($actionurl, array('bui_deleteid' => $block->instance
->id
)),
1120 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1122 array('class' => 'editing_delete')
1130 * @param block_base $block a block that appears on this page.
1131 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1133 protected function user_can_delete_block($block) {
1134 return $this->page
->user_can_edit_blocks() && $block->user_can_edit() &&
1135 $block->user_can_addto($this->page
) &&
1136 !in_array($block->instance
->blockname
, self
::get_undeletable_block_types());
1140 * Process any block actions that were specified in the URL.
1142 * @return boolean true if anything was done. False if not.
1144 public function process_url_actions() {
1145 if (!$this->page
->user_is_editing()) {
1148 return $this->process_url_add() ||
$this->process_url_delete() ||
1149 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1150 $this->process_url_move();
1154 * Handle adding a block.
1155 * @return boolean true if anything was done. False if not.
1157 public function process_url_add() {
1158 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1165 if (!$this->page
->user_can_edit_blocks()) {
1166 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1169 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1170 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1173 $this->add_block_at_end_of_default_region($blocktype);
1175 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1176 $this->page
->ensure_param_not_in_url('bui_addblock');
1182 * Handle deleting a block.
1183 * @return boolean true if anything was done. False if not.
1185 public function process_url_delete() {
1186 global $CFG, $PAGE, $OUTPUT;
1188 $blockid = optional_param('bui_deleteid', null, PARAM_INT
);
1189 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT
);
1196 $block = $this->page
->blocks
->find_instance($blockid);
1197 if (!$this->user_can_delete_block($block)) {
1198 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1201 if (!$confirmdelete) {
1202 $deletepage = new moodle_page();
1203 $deletepage->set_pagelayout('admin');
1204 $deletepage->set_course($this->page
->course
);
1205 $deletepage->set_context($this->page
->context
);
1206 if ($this->page
->cm
) {
1207 $deletepage->set_cm($this->page
->cm
);
1210 $deleteurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1211 $deleteurlparams = $this->page
->url
->params();
1212 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1213 $deletepage->set_block_actions_done();
1214 // At this point we are either going to redirect, or display the form, so
1215 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1216 $PAGE = $deletepage;
1217 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1218 $output = $deletepage->get_renderer('core');
1222 $blocktitle = $block->get_title();
1223 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1224 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1226 // If the block is being shown in sub contexts display a warning.
1227 if ($block->instance
->showinsubcontexts
== 1) {
1228 $parentcontext = context
::instance_by_id($block->instance
->parentcontextid
);
1229 $systemcontext = context_system
::instance();
1230 $messagestring = new stdClass();
1231 $messagestring->location
= $parentcontext->get_context_name();
1233 // Checking for blocks that may have visibility on the front page and pages added on that.
1234 if ($parentcontext->id
!= $systemcontext->id
&& is_inside_frontpage($parentcontext)) {
1235 $messagestring->pagetype
= get_string('showonfrontpageandsubs', 'block');
1237 $pagetypes = generate_page_type_patterns($this->page
->pagetype
, $parentcontext);
1238 $messagestring->pagetype
= $block->instance
->pagetypepattern
;
1239 if (isset($pagetypes[$block->instance
->pagetypepattern
])) {
1240 $messagestring->pagetype
= $pagetypes[$block->instance
->pagetypepattern
];
1244 $message = get_string('deleteblockwarning', 'block', $messagestring);
1247 $PAGE->navbar
->add($strdeletecheck);
1248 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1249 $PAGE->set_heading($site->fullname
);
1250 echo $OUTPUT->header();
1251 $confirmurl = new moodle_url($deletepage->url
, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance
->id
, 'bui_confirm' => 1));
1252 $cancelurl = new moodle_url($deletepage->url
);
1253 $yesbutton = new single_button($confirmurl, get_string('yes'));
1254 $nobutton = new single_button($cancelurl, get_string('no'));
1255 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1256 echo $OUTPUT->footer();
1257 // Make sure that nothing else happens after we have displayed this form.
1260 blocks_delete_instance($block->instance
);
1261 // bui_deleteid and bui_confirm should not be in the PAGE url.
1262 $this->page
->ensure_param_not_in_url('bui_deleteid');
1263 $this->page
->ensure_param_not_in_url('bui_confirm');
1269 * Handle showing or hiding a block.
1270 * @return boolean true if anything was done. False if not.
1272 public function process_url_show_hide() {
1273 if ($blockid = optional_param('bui_hideid', null, PARAM_INT
)) {
1275 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT
)) {
1283 $block = $this->page
->blocks
->find_instance($blockid);
1285 if (!$this->page
->user_can_edit_blocks()) {
1286 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1287 } else if (!$block->instance_can_be_hidden()) {
1291 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1293 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1294 $this->page
->ensure_param_not_in_url('bui_hideid');
1295 $this->page
->ensure_param_not_in_url('bui_showid');
1301 * Handle showing/processing the submission from the block editing form.
1302 * @return boolean true if the form was submitted and the new config saved. Does not
1303 * return if the editing form was displayed. False otherwise.
1305 public function process_url_edit() {
1306 global $CFG, $DB, $PAGE, $OUTPUT;
1308 $blockid = optional_param('bui_editid', null, PARAM_INT
);
1314 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1316 $block = $this->find_instance($blockid);
1318 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1319 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1322 $editpage = new moodle_page();
1323 $editpage->set_pagelayout('admin');
1324 $editpage->set_course($this->page
->course
);
1325 //$editpage->set_context($block->context);
1326 $editpage->set_context($this->page
->context
);
1327 if ($this->page
->cm
) {
1328 $editpage->set_cm($this->page
->cm
);
1330 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1331 $editurlparams = $this->page
->url
->params();
1332 $editurlparams['bui_editid'] = $blockid;
1333 $editpage->set_url($editurlbase, $editurlparams);
1334 $editpage->set_block_actions_done();
1335 // At this point we are either going to redirect, or display the form, so
1336 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1338 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1339 $output = $editpage->get_renderer('core');
1342 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1343 if (is_readable($formfile)) {
1344 require_once($formfile);
1345 $classname = 'block_' . $block->name() . '_edit_form';
1346 if (!class_exists($classname)) {
1347 $classname = 'block_edit_form';
1350 $classname = 'block_edit_form';
1353 $mform = new $classname($editpage->url
, $block, $this->page
);
1354 $mform->set_data($block->instance
);
1356 if ($mform->is_cancelled()) {
1357 redirect($this->page
->url
);
1359 } else if ($data = $mform->get_data()) {
1361 $bi->id
= $block->instance
->id
;
1363 // This may get overwritten by the special case handling below.
1364 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1365 $bi->showinsubcontexts
= (bool) $data->bui_contexts
;
1366 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1367 $bi->subpagepattern
= null;
1369 $bi->subpagepattern
= $data->bui_subpagepattern
;
1372 $systemcontext = context_system
::instance();
1373 $frontpagecontext = context_course
::instance(SITEID
);
1374 $parentcontext = context
::instance_by_id($data->bui_parentcontextid
);
1376 // Updating stickiness and contexts. See MDL-21375 for details.
1377 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1379 // Explicitly set the default context
1380 $bi->parentcontextid
= $parentcontext->id
;
1382 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1384 // The interface here is a special case because the pagetype pattern is
1385 // totally derived from the context menu. Here are the excpetions. MDL-30340
1387 switch ($data->bui_contexts
) {
1388 case BUI_CONTEXTS_ENTIRE_SITE
:
1389 // The user wants to show the block across the entire site
1390 $bi->parentcontextid
= $systemcontext->id
;
1391 $bi->showinsubcontexts
= true;
1392 $bi->pagetypepattern
= '*';
1394 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1395 // The user wants the block shown on the front page and all subcontexts
1396 $bi->parentcontextid
= $frontpagecontext->id
;
1397 $bi->showinsubcontexts
= true;
1398 $bi->pagetypepattern
= '*';
1400 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1401 // The user want to show the front page on the frontpage only
1402 $bi->parentcontextid
= $frontpagecontext->id
;
1403 $bi->showinsubcontexts
= false;
1404 $bi->pagetypepattern
= 'site-index';
1405 // This is the only relevant page type anyway but we'll set it explicitly just
1406 // in case the front page grows site-index-* subpages of its own later
1412 $bits = explode('-', $bi->pagetypepattern
);
1413 // hacks for some contexts
1414 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1415 // For course context
1416 // is page type pattern is mod-*, change showinsubcontext to 1
1417 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1418 $bi->showinsubcontexts
= 1;
1420 $bi->showinsubcontexts
= 0;
1422 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1424 // subpagepattern should be null
1425 if ($bits[0] == 'user' or $bits[0] == 'my') {
1426 // we don't need subpagepattern in usercontext
1427 $bi->subpagepattern
= null;
1431 $bi->defaultregion
= $data->bui_defaultregion
;
1432 $bi->defaultweight
= $data->bui_defaultweight
;
1433 $DB->update_record('block_instances', $bi);
1435 if (!empty($block->config
)) {
1436 $config = clone($block->config
);
1438 $config = new stdClass
;
1440 foreach ($data as $configfield => $value) {
1441 if (strpos($configfield, 'config_') !== 0) {
1444 $field = substr($configfield, 7);
1445 $config->$field = $value;
1447 $block->instance_config_save($config);
1450 $bp->visible
= $data->bui_visible
;
1451 $bp->region
= $data->bui_region
;
1452 $bp->weight
= $data->bui_weight
;
1453 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1454 $data->bui_weight
!= $data->bui_defaultweight
;
1456 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1457 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1459 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1460 $bp->id
= $block->instance
->blockpositionid
;
1461 $DB->update_record('block_positions', $bp);
1463 } else if ($needbprecord) {
1464 $bp->blockinstanceid
= $block->instance
->id
;
1465 $bp->contextid
= $this->page
->context
->id
;
1466 $bp->pagetype
= $this->page
->pagetype
;
1467 if ($this->page
->subpage
) {
1468 $bp->subpage
= $this->page
->subpage
;
1472 $DB->insert_record('block_positions', $bp);
1475 redirect($this->page
->url
);
1478 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1479 $editpage->set_title($strheading);
1480 $editpage->set_heading($strheading);
1481 $bits = explode('-', $this->page
->pagetype
);
1482 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1483 // better navbar for tag pages
1484 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1485 $tag = tag_get('id', $this->page
->subpage
, '*');
1486 // tag search page doesn't have subpageid
1488 $editpage->navbar
->add($tag->name
, new moodle_url('/tag/index.php', array('id'=>$tag->id
)));
1491 $editpage->navbar
->add($block->get_title());
1492 $editpage->navbar
->add(get_string('configuration'));
1493 echo $output->header();
1494 echo $output->heading($strheading, 2);
1496 echo $output->footer();
1502 * Handle showing/processing the submission from the block editing form.
1503 * @return boolean true if the form was submitted and the new config saved. Does not
1504 * return if the editing form was displayed. False otherwise.
1506 public function process_url_move() {
1507 global $CFG, $DB, $PAGE;
1509 $blockid = optional_param('bui_moveid', null, PARAM_INT
);
1516 $block = $this->find_instance($blockid);
1518 if (!$this->page
->user_can_edit_blocks()) {
1519 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1522 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1523 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1524 if (!$newregion ||
is_null($newweight)) {
1525 // Don't have a valid target position yet, must be just starting the move.
1526 $this->movingblock
= $blockid;
1527 $this->page
->ensure_param_not_in_url('bui_moveid');
1531 if (!$this->is_known_region($newregion)) {
1532 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1535 // Move this block. This may involve moving other nearby blocks.
1536 $blocks = $this->birecordsbyregion
[$newregion];
1538 $maxweight = self
::MAX_WEIGHT
;
1539 $minweight = -self
::MAX_WEIGHT
;
1541 // Initialise the used weights and spareweights array with the default values
1542 $spareweights = array();
1543 $usedweights = array();
1544 for ($i = $minweight; $i <= $maxweight; $i++
) {
1545 $spareweights[$i] = $i;
1546 $usedweights[$i] = array();
1549 // Check each block and sort out where we have used weights
1550 foreach ($blocks as $bi) {
1551 if ($bi->weight
> $maxweight) {
1552 // If this statement is true then the blocks weight is more than the
1553 // current maximum. To ensure that we can get the best block position
1554 // we will initialise elements within the usedweights and spareweights
1555 // arrays between the blocks weight (which will then be the new max) and
1557 $parseweight = $bi->weight
;
1558 while (!array_key_exists($parseweight, $usedweights)) {
1559 $usedweights[$parseweight] = array();
1560 $spareweights[$parseweight] = $parseweight;
1563 $maxweight = $bi->weight
;
1564 } else if ($bi->weight
< $minweight) {
1565 // As above except this time the blocks weight is LESS than the
1566 // the current minimum, so we will initialise the array from the
1567 // blocks weight (new minimum) to the current minimum
1568 $parseweight = $bi->weight
;
1569 while (!array_key_exists($parseweight, $usedweights)) {
1570 $usedweights[$parseweight] = array();
1571 $spareweights[$parseweight] = $parseweight;
1574 $minweight = $bi->weight
;
1576 if ($bi->id
!= $block->instance
->id
) {
1577 unset($spareweights[$bi->weight
]);
1578 $usedweights[$bi->weight
][] = $bi->id
;
1582 // First we find the nearest gap in the list of weights.
1583 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1585 foreach ($spareweights as $spareweight) {
1586 if (abs($newweight - $spareweight) < $bestdistance) {
1587 $bestdistance = abs($newweight - $spareweight);
1588 $bestgap = $spareweight;
1592 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1593 if (is_null($bestgap)) {
1594 $bestgap = self
::MAX_WEIGHT +
1;
1595 while (!empty($usedweights[$bestgap])) {
1600 // Now we know the gap we are aiming for, so move all the blocks along.
1601 if ($bestgap < $newweight) {
1602 $newweight = floor($newweight);
1603 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1604 if (array_key_exists($weight, $usedweights)) {
1605 foreach ($usedweights[$weight] as $biid) {
1606 $this->reposition_block($biid, $newregion, $weight - 1);
1610 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1612 $newweight = ceil($newweight);
1613 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1614 if (array_key_exists($weight, $usedweights)) {
1615 foreach ($usedweights[$weight] as $biid) {
1616 $this->reposition_block($biid, $newregion, $weight +
1);
1620 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1623 $this->page
->ensure_param_not_in_url('bui_moveid');
1624 $this->page
->ensure_param_not_in_url('bui_newregion');
1625 $this->page
->ensure_param_not_in_url('bui_newweight');
1630 * Turns the display of normal blocks either on or off.
1632 * @param bool $setting
1634 public function show_only_fake_blocks($setting = true) {
1635 $this->fakeblocksonly
= $setting;
1639 /// Helper functions for working with block classes ============================
1642 * Call a class method (one that does not require a block instance) on a block class.
1644 * @param string $blockname the name of the block.
1645 * @param string $method the method name.
1646 * @param array $param parameters to pass to the method.
1647 * @return mixed whatever the method returns.
1649 function block_method_result($blockname, $method, $param = NULL) {
1650 if(!block_load_class($blockname)) {
1653 return call_user_func(array('block_'.$blockname, $method), $param);
1657 * Creates a new instance of the specified block class.
1659 * @param string $blockname the name of the block.
1660 * @param $instance block_instances DB table row (optional).
1661 * @param moodle_page $page the page this block is appearing on.
1662 * @return block_base the requested block instance.
1664 function block_instance($blockname, $instance = NULL, $page = NULL) {
1665 if(!block_load_class($blockname)) {
1668 $classname = 'block_'.$blockname;
1669 $retval = new $classname;
1670 if($instance !== NULL) {
1671 if (is_null($page)) {
1675 $retval->_load_instance($instance, $page);
1681 * Load the block class for a particular type of block.
1683 * @param string $blockname the name of the block.
1684 * @return boolean success or failure.
1686 function block_load_class($blockname) {
1689 if(empty($blockname)) {
1693 $classname = 'block_'.$blockname;
1695 if(class_exists($classname)) {
1699 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1701 if (file_exists($blockpath)) {
1702 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1703 include_once($blockpath);
1705 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1709 return class_exists($classname);
1713 * Given a specific page type, return all the page type patterns that might
1716 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1717 * @return array an array of all the page type patterns that might match this page type.
1719 function matching_page_type_patterns($pagetype) {
1720 $patterns = array($pagetype);
1721 $bits = explode('-', $pagetype);
1722 if (count($bits) == 3 && $bits[0] == 'mod') {
1723 if ($bits[2] == 'view') {
1724 $patterns[] = 'mod-*-view';
1725 } else if ($bits[2] == 'index') {
1726 $patterns[] = 'mod-*-index';
1729 while (count($bits) > 0) {
1730 $patterns[] = implode('-', $bits) . '-*';
1738 * Give an specific pattern, return all the page type patterns that would also match it.
1740 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
1741 * @return array of all the page type patterns matching.
1743 function matching_page_type_patterns_from_pattern($pattern) {
1744 $patterns = array($pattern);
1745 if ($pattern === '*') {
1749 // Only keep the part before the star because we will append -* to all the bits.
1750 $star = strpos($pattern, '-*');
1751 if ($star !== false) {
1752 $pattern = substr($pattern, 0, $star);
1755 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
1756 $patterns = array_unique($patterns);
1762 * Given a specific page type, parent context and currect context, return all the page type patterns
1763 * that might be used by this block.
1765 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1766 * @param stdClass $parentcontext Block's parent context
1767 * @param stdClass $currentcontext Current context of block
1768 * @return array an array of all the page type patterns that might match this page type.
1770 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1771 global $CFG; // Required for includes bellow.
1773 $bits = explode('-', $pagetype);
1775 $core = core_component
::get_core_subsystems();
1776 $plugins = core_component
::get_plugin_types();
1778 //progressively strip pieces off the page type looking for a match
1779 $componentarray = null;
1780 for ($i = count($bits); $i > 0; $i--) {
1781 $possiblecomponentarray = array_slice($bits, 0, $i);
1782 $possiblecomponent = implode('', $possiblecomponentarray);
1784 // Check to see if the component is a core component
1785 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1786 $libfile = $core[$possiblecomponent].'/lib.php';
1787 if (file_exists($libfile)) {
1788 require_once($libfile);
1789 $function = $possiblecomponent.'_page_type_list';
1790 if (function_exists($function)) {
1791 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1798 //check the plugin directory and look for a callback
1799 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1801 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1802 if (count($bits) > $i) {
1803 $pluginname = $bits[$i];
1804 $directory = core_component
::get_plugin_directory($possiblecomponent, $pluginname);
1805 if (!empty($directory)){
1806 $libfile = $directory.'/lib.php';
1807 if (file_exists($libfile)) {
1808 require_once($libfile);
1809 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1810 if (!function_exists($function)) {
1811 $function = $pluginname.'_page_type_list';
1813 if (function_exists($function)) {
1814 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1822 //we'll only get to here if we still don't have any patterns
1823 //the plugin type may have a callback
1824 $directory = $plugins[$possiblecomponent];
1825 $libfile = $directory.'/lib.php';
1826 if (file_exists($libfile)) {
1827 require_once($libfile);
1828 $function = $possiblecomponent.'_page_type_list';
1829 if (function_exists($function)) {
1830 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1838 if (empty($patterns)) {
1839 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1842 // Ensure that the * pattern is always available if editing block 'at distance', so
1843 // we always can 'bring back' it to the original context. MDL-30340
1844 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
1845 // TODO: We could change the string here, showing its 'bring back' meaning
1846 $patterns['*'] = get_string('page-x', 'pagetype');
1853 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1855 * @param string $pagetype
1856 * @param stdClass $parentcontext
1857 * @param stdClass $currentcontext
1860 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1861 // Generate page type patterns based on current page type if
1862 // callbacks haven't been defined
1863 $patterns = array($pagetype => $pagetype);
1864 $bits = explode('-', $pagetype);
1865 while (count($bits) > 0) {
1866 $pattern = implode('-', $bits) . '-*';
1867 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1868 // guessing page type description
1869 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1870 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1872 $patterns[$pattern] = $pattern;
1876 $patterns['*'] = get_string('page-x', 'pagetype');
1881 * Generates the page type list for the my moodle page
1883 * @param string $pagetype
1884 * @param stdClass $parentcontext
1885 * @param stdClass $currentcontext
1888 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1889 return array('my-index' => get_string('page-my-index', 'pagetype'));
1893 * Generates the page type list for a module by either locating and using the modules callback
1894 * or by generating a default list.
1896 * @param string $pagetype
1897 * @param stdClass $parentcontext
1898 * @param stdClass $currentcontext
1901 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1902 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1903 if (empty($patterns)) {
1904 // if modules don't have callbacks
1905 // generate two default page type patterns for modules only
1906 $bits = explode('-', $pagetype);
1907 $patterns = array($pagetype => $pagetype);
1908 if ($bits[2] == 'view') {
1909 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1910 } else if ($bits[2] == 'index') {
1911 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1916 /// Functions update the blocks if required by the request parameters ==========
1919 * Return a {@link block_contents} representing the add a new block UI, if
1920 * this user is allowed to see it.
1922 * @return block_contents an appropriate block_contents, or null if the user
1923 * cannot add any blocks here.
1925 function block_add_block_ui($page, $output) {
1926 global $CFG, $OUTPUT;
1927 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
1931 $bc = new block_contents();
1932 $bc->title
= get_string('addblock');
1933 $bc->add_class('block_adminblock');
1934 $bc->attributes
['data-block'] = 'adminblock';
1936 $missingblocks = $page->blocks
->get_addable_blocks();
1937 if (empty($missingblocks)) {
1938 $bc->content
= get_string('noblockstoaddhere');
1943 foreach ($missingblocks as $block) {
1944 $blockobject = block_instance($block->name
);
1945 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1946 $menu[$block->name
] = $blockobject->get_title();
1949 core_collator
::asort($menu);
1951 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
1952 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1953 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1954 $bc->content
= $OUTPUT->render($select);
1959 * Actually delete from the database any blocks that are currently on this page,
1960 * but which should not be there according to blocks_name_allowed_in_format.
1962 * @todo Write/Fix this function. Currently returns immediately
1965 function blocks_remove_inappropriate($course) {
1969 $blockmanager = blocks_get_by_page($page);
1971 if (empty($blockmanager)) {
1975 if (($pageformat = $page->pagetype) == NULL) {
1979 foreach($blockmanager as $region) {
1980 foreach($region as $instance) {
1981 $block = blocks_get_record($instance->blockid);
1982 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1983 blocks_delete_instance($instance->instance);
1990 * Check that a given name is in a permittable format
1992 * @param string $name
1993 * @param string $pageformat
1996 function blocks_name_allowed_in_format($name, $pageformat) {
1999 if (!$bi = block_instance($name)) {
2003 $formats = $bi->applicable_formats();
2007 foreach ($formats as $format => $allowed) {
2008 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2009 $depth = substr_count($format, '-');
2010 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2015 if ($accept === NULL) {
2016 $accept = !empty($formats['all']);
2022 * Delete a block, and associated data.
2024 * @param object $instance a row from the block_instances table
2025 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2026 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2028 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2031 if ($block = block_instance($instance->blockname
, $instance)) {
2032 $block->instance_delete();
2034 context_helper
::delete_instance(CONTEXT_BLOCK
, $instance->id
);
2036 if (!$skipblockstables) {
2037 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
2038 $DB->delete_records('block_instances', array('id' => $instance->id
));
2039 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
2044 * Delete all the blocks that belong to a particular context.
2046 * @param int $contextid the context id.
2048 function blocks_delete_all_for_context($contextid) {
2050 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2051 foreach ($instances as $instance) {
2052 blocks_delete_instance($instance, true);
2054 $instances->close();
2055 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2056 $DB->delete_records('block_positions', array('contextid' => $contextid));
2060 * Set a block to be visible or hidden on a particular page.
2062 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2063 * block_positions table as return by block_manager.
2064 * @param moodle_page $page the back to set the visibility with respect to.
2065 * @param integer $newvisibility 1 for visible, 0 for hidden.
2067 function blocks_set_visibility($instance, $page, $newvisibility) {
2069 if (!empty($instance->blockpositionid
)) {
2070 // Already have local information on this page.
2071 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
2075 // Create a new block_positions record.
2077 $bp->blockinstanceid
= $instance->id
;
2078 $bp->contextid
= $page->context
->id
;
2079 $bp->pagetype
= $page->pagetype
;
2080 if ($page->subpage
) {
2081 $bp->subpage
= $page->subpage
;
2083 $bp->visible
= $newvisibility;
2084 $bp->region
= $instance->defaultregion
;
2085 $bp->weight
= $instance->defaultweight
;
2086 $DB->insert_record('block_positions', $bp);
2090 * Get the block record for a particular blockid - that is, a particular type os block.
2092 * @param $int blockid block type id. If null, an array of all block types is returned.
2093 * @param bool $notusedanymore No longer used.
2094 * @return array|object row from block table, or all rows.
2096 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2098 $blocks = $PAGE->blocks
->get_installed_blocks();
2099 if ($blockid === NULL) {
2101 } else if (isset($blocks[$blockid])) {
2102 return $blocks[$blockid];
2109 * Find a given block by its blockid within a provide array
2111 * @param int $blockid
2112 * @param array $blocksarray
2113 * @return bool|object Instance if found else false
2115 function blocks_find_block($blockid, $blocksarray) {
2116 if (empty($blocksarray)) {
2119 foreach($blocksarray as $blockgroup) {
2120 if (empty($blockgroup)) {
2123 foreach($blockgroup as $instance) {
2124 if($instance->blockid
== $blockid) {
2132 // Functions for programatically adding default blocks to pages ================
2135 * Parse a list of default blocks. See config-dist for a description of the format.
2137 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2138 * @return array the parsed list of default blocks
2140 function blocks_parse_default_blocks_list($blocksstr) {
2142 $bits = explode(':', $blocksstr);
2143 if (!empty($bits)) {
2144 $leftbits = trim(array_shift($bits));
2145 if ($leftbits != '') {
2146 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2149 if (!empty($bits)) {
2150 $rightbits = trim(array_shift($bits));
2151 if ($rightbits != '') {
2152 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2159 * @return array the blocks that should be added to the site course by default.
2161 function blocks_get_default_site_course_blocks() {
2164 if (!empty($CFG->defaultblocks_site
)) {
2165 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2168 BLOCK_POS_LEFT
=> array('site_main_menu'),
2169 BLOCK_POS_RIGHT
=> array('course_summary', 'calendar_month')
2175 * Add the default blocks to a course.
2177 * @param object $course a course object.
2179 function blocks_add_default_course_blocks($course) {
2182 if (!empty($CFG->defaultblocks_override
)) {
2183 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2185 } else if ($course->id
== SITEID
) {
2186 $blocknames = blocks_get_default_site_course_blocks();
2188 } else if (!empty($CFG->{'defaultblocks_' . $course->format
})) {
2189 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format
});
2192 require_once($CFG->dirroot
. '/course/lib.php');
2193 $blocknames = course_get_format($course)->get_default_blocks();
2197 if ($course->id
== SITEID
) {
2198 $pagetypepattern = 'site-index';
2200 $pagetypepattern = 'course-view-*';
2202 $page = new moodle_page();
2203 $page->set_course($course);
2204 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2208 * Add the default system-context blocks. E.g. the admin tree.
2210 function blocks_add_default_system_blocks() {
2213 $page = new moodle_page();
2214 $page->set_context(context_system
::instance());
2215 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('navigation', 'settings')), '*', null, true);
2216 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2218 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2219 $subpagepattern = $defaultmypage->id
;
2221 $subpagepattern = null;
2224 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2225 $newcontent = array('course_overview');
2226 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);