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 $this->check_is_loaded();
490 $this->ensure_content_created($region, $output);
491 if (!$this->region_has_content($region, $output)) {
492 // If the region has no content then nothing is docked at all of course.
495 foreach ($this->visibleblockcontent
[$region] as $instance) {
496 if (!empty($instance->content
) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
504 * Checks to see whether any of the blocks within the given regions are docked
506 * @see region_completely_docked
507 * @param array|string $regions array of regions (or single region)
508 * @return bool True if any of the blocks within that region are docked
510 public function region_uses_dock($regions, $output) {
511 if (!$this->page
->theme
->enable_dock
) {
514 $this->check_is_loaded();
515 foreach((array)$regions as $region) {
516 $this->ensure_content_created($region, $output);
517 foreach($this->visibleblockcontent
[$region] as $instance) {
518 if(!empty($instance->content
) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
526 /// Actions ====================================================================
529 * This method actually loads the blocks for our page from the database.
531 * @param boolean|null $includeinvisible
532 * null (default) - load hidden blocks if $this->page->user_is_editing();
533 * true - load hidden blocks.
534 * false - don't load hidden blocks.
536 public function load_blocks($includeinvisible = null) {
539 if (!is_null($this->birecordsbyregion
)) {
544 if ($CFG->version
< 2009050619) {
545 // Upgrade/install not complete. Don't try too show any blocks.
546 $this->birecordsbyregion
= array();
550 // Ensure we have been initialised.
551 if (is_null($this->defaultregion
)) {
552 $this->page
->initialise_theme_and_output();
553 // If there are still no block regions, then there are no blocks on this page.
554 if (empty($this->regions
)) {
555 $this->birecordsbyregion
= array();
560 // Check if we need to load normal blocks
561 if ($this->fakeblocksonly
) {
562 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
566 if (is_null($includeinvisible)) {
567 $includeinvisible = $this->page
->user_is_editing();
569 if ($includeinvisible) {
572 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
575 $context = $this->page
->context
;
576 $contexttest = 'bi.parentcontextid = :contextid2';
577 $parentcontextparams = array();
578 $parentcontextids = $context->get_parent_context_ids();
579 if ($parentcontextids) {
580 list($parentcontexttest, $parentcontextparams) =
581 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
, 'parentcontext');
582 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
585 $pagetypepatterns = matching_page_type_patterns($this->page
->pagetype
);
586 list($pagetypepatterntest, $pagetypepatternparams) =
587 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
, 'pagetypepatterntest');
589 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
590 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
593 'contextlevel' => CONTEXT_BLOCK
,
594 'subpage1' => $this->page
->subpage
,
595 'subpage2' => $this->page
->subpage
,
596 'contextid1' => $context->id
,
597 'contextid2' => $context->id
,
598 'pagetype' => $this->page
->pagetype
,
600 if ($this->page
->subpage
=== '') {
601 $params['subpage1'] = '';
602 $params['subpage2'] = '';
606 bp.id AS blockpositionid,
609 bi.showinsubcontexts,
614 COALESCE(bp.visible, 1) AS visible,
615 COALESCE(bp.region, bi.defaultregion) AS region,
616 COALESCE(bp.weight, bi.defaultweight) AS weight,
620 FROM {block_instances} bi
621 JOIN {block} b ON bi.blockname = b.name
622 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
623 AND bp.contextid = :contextid1
624 AND bp.pagetype = :pagetype
625 AND bp.subpage = :subpage1
630 AND bi.pagetypepattern $pagetypepatterntest
631 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
636 COALESCE(bp.region, bi.defaultregion),
637 COALESCE(bp.weight, bi.defaultweight),
639 $blockinstances = $DB->get_recordset_sql($sql, $params +
$parentcontextparams +
$pagetypepatternparams);
641 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
643 foreach ($blockinstances as $bi) {
644 context_helper
::preload_from_record($bi);
645 if ($this->is_known_region($bi->region
)) {
646 $this->birecordsbyregion
[$bi->region
][] = $bi;
652 // Pages don't necessarily have a defaultregion. The one time this can
653 // happen is when there are no theme block regions, but the script itself
654 // has a block region in the main content area.
655 if (!empty($this->defaultregion
)) {
656 $this->birecordsbyregion
[$this->defaultregion
] =
657 array_merge($this->birecordsbyregion
[$this->defaultregion
], $unknown);
662 * Add a block to the current page, or related pages. The block is added to
663 * context $this->page->contextid. If $pagetypepattern $subpagepattern
665 * @param string $blockname The type of block to add.
666 * @param string $region the block region on this page to add the block to.
667 * @param integer $weight determines the order where this block appears in the region.
668 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
669 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
670 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
672 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
674 // Allow invisible blocks because this is used when adding default page blocks, which
675 // might include invisible ones if the user makes some default blocks invisible
676 $this->check_known_block_type($blockname, true);
677 $this->check_region_is_known($region);
679 if (empty($pagetypepattern)) {
680 $pagetypepattern = $this->page
->pagetype
;
683 $blockinstance = new stdClass
;
684 $blockinstance->blockname
= $blockname;
685 $blockinstance->parentcontextid
= $this->page
->context
->id
;
686 $blockinstance->showinsubcontexts
= !empty($showinsubcontexts);
687 $blockinstance->pagetypepattern
= $pagetypepattern;
688 $blockinstance->subpagepattern
= $subpagepattern;
689 $blockinstance->defaultregion
= $region;
690 $blockinstance->defaultweight
= $weight;
691 $blockinstance->configdata
= '';
692 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
694 // Ensure the block context is created.
695 context_block
::instance($blockinstance->id
);
697 // If the new instance was created, allow it to do additional setup
698 if ($block = block_instance($blockname, $blockinstance)) {
699 $block->instance_create();
703 public function add_block_at_end_of_default_region($blockname) {
704 $defaulregion = $this->get_default_region();
706 $lastcurrentblock = end($this->birecordsbyregion
[$defaulregion]);
707 if ($lastcurrentblock) {
708 $weight = $lastcurrentblock->weight +
1;
713 if ($this->page
->subpage
) {
714 $subpage = $this->page
->subpage
;
719 // Special case. Course view page type include the course format, but we
720 // want to add the block non-format-specifically.
721 $pagetypepattern = $this->page
->pagetype
;
722 if (strpos($pagetypepattern, 'course-view') === 0) {
723 $pagetypepattern = 'course-view-*';
726 // We should end using this for ALL the blocks, making always the 1st option
727 // the default one to be used. Until then, this is one hack to avoid the
728 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
729 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
730 // (the FIRST $pagetypepattern will be set)
732 // We are applying it to all blocks created in mod pages for now and only if the
733 // default pagetype is not one of the available options
734 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
735 $pagetypelist = generate_page_type_patterns($this->page
->pagetype
, null, $this->page
->context
);
736 // Only go for the first if the pagetype is not a valid option
737 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
738 $pagetypepattern = key($pagetypelist);
741 // Surely other pages like course-report will need this too, they just are not important
742 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
744 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
748 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
750 * @param array $blocks array with array keys the region names, and values an array of block names.
751 * @param string $pagetypepattern optional. Passed to @see add_block()
752 * @param string $subpagepattern optional. Passed to @see add_block()
754 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
755 $this->add_regions(array_keys($blocks), false);
756 foreach ($blocks as $region => $regionblocks) {
758 foreach ($regionblocks as $blockname) {
759 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
766 * Move a block to a new position on this page.
768 * If this block cannot appear on any other pages, then we change defaultposition/weight
769 * in the block_instances table. Otherwise we just set the position on this page.
771 * @param $blockinstanceid the block instance id.
772 * @param $newregion the new region name.
773 * @param $newweight the new weight.
775 public function reposition_block($blockinstanceid, $newregion, $newweight) {
778 $this->check_region_is_known($newregion);
779 $inst = $this->find_instance($blockinstanceid);
781 $bi = $inst->instance
;
782 if ($bi->weight
== $bi->defaultweight
&& $bi->region
== $bi->defaultregion
&&
783 !$bi->showinsubcontexts
&& strpos($bi->pagetypepattern
, '*') === false &&
784 (!$this->page
->subpage ||
$bi->subpagepattern
)) {
786 // Set default position
787 $newbi = new stdClass
;
788 $newbi->id
= $bi->id
;
789 $newbi->defaultregion
= $newregion;
790 $newbi->defaultweight
= $newweight;
791 $DB->update_record('block_instances', $newbi);
793 if ($bi->blockpositionid
) {
795 $bp->id
= $bi->blockpositionid
;
796 $bp->region
= $newregion;
797 $bp->weight
= $newweight;
798 $DB->update_record('block_positions', $bp);
802 // Just set position on this page.
804 $bp->region
= $newregion;
805 $bp->weight
= $newweight;
807 if ($bi->blockpositionid
) {
808 $bp->id
= $bi->blockpositionid
;
809 $DB->update_record('block_positions', $bp);
812 $bp->blockinstanceid
= $bi->id
;
813 $bp->contextid
= $this->page
->context
->id
;
814 $bp->pagetype
= $this->page
->pagetype
;
815 if ($this->page
->subpage
) {
816 $bp->subpage
= $this->page
->subpage
;
820 $bp->visible
= $bi->visible
;
821 $DB->insert_record('block_positions', $bp);
827 * Find a given block by its instance id
829 * @param integer $instanceid
832 public function find_instance($instanceid) {
833 foreach ($this->regions
as $region => $notused) {
834 $this->ensure_instances_exist($region);
835 foreach($this->blockinstances
[$region] as $instance) {
836 if ($instance->instance
->id
== $instanceid) {
841 throw new block_not_on_page_exception($instanceid, $this->page
);
844 /// Inner workings =============================================================
847 * Check whether the page blocks have been loaded yet
849 * @return void Throws coding exception if already loaded
851 protected function check_not_yet_loaded() {
852 if (!is_null($this->birecordsbyregion
)) {
853 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.');
858 * Check whether the page blocks have been loaded yet
860 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
862 * @return void Throws coding exception if already loaded
864 protected function check_is_loaded() {
865 if (is_null($this->birecordsbyregion
)) {
866 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
871 * Check if a block type is known and usable
873 * @param string $blockname The block type name to search for
874 * @param bool $includeinvisible Include disabled block types in the initial pass
875 * @return void Coding Exception thrown if unknown or not enabled
877 protected function check_known_block_type($blockname, $includeinvisible = false) {
878 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
879 if ($this->is_known_block_type($blockname, true)) {
880 throw new coding_exception('Unknown block type ' . $blockname);
882 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
888 * Check if a region is known by its name
890 * @param string $region
891 * @return void Coding Exception thrown if the region is not known
893 protected function check_region_is_known($region) {
894 if (!$this->is_known_region($region)) {
895 throw new coding_exception('Trying to reference an unknown block region ' . $region);
900 * Returns an array of region names as keys and nested arrays for values
902 * @return array an array where the array keys are the region names, and the array
903 * values are empty arrays.
905 protected function prepare_per_region_arrays() {
907 foreach ($this->regions
as $region => $notused) {
908 $result[$region] = array();
914 * Create a set of new block instance from a record array
916 * @param array $birecords An array of block instance records
917 * @return array An array of instantiated block_instance objects
919 protected function create_block_instances($birecords) {
921 foreach ($birecords as $record) {
922 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
923 $results[] = $blockobject;
930 * Create all the block instances for all the blocks that were loaded by
931 * load_blocks. This is used, for example, to ensure that all blocks get a
932 * chance to initialise themselves via the {@link block_base::specialize()}
933 * method, before any output is done.
935 public function create_all_block_instances() {
936 foreach ($this->get_regions() as $region) {
937 $this->ensure_instances_exist($region);
942 * Return an array of content objects from a set of block instances
944 * @param array $instances An array of block instances
945 * @param renderer_base The renderer to use.
946 * @param string $region the region name.
947 * @return array An array of block_content (and possibly block_move_target) objects.
949 protected function create_block_contents($instances, $output, $region) {
954 if ($this->movingblock
) {
955 $first = reset($instances);
957 $lastweight = $first->instance
->weight
- 2;
961 foreach ($instances as $instance) {
962 $content = $instance->get_content_for_output($output);
963 if (empty($content)) {
967 if ($this->movingblock
&& $lastweight != $instance->instance
->weight
&&
968 $content->blockinstanceid
!= $this->movingblock
&& $lastblock != $this->movingblock
) {
969 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight +
$instance->instance
->weight
)/2));
972 if ($content->blockinstanceid
== $this->movingblock
) {
973 $content->add_class('beingmoved');
974 $content->annotation
.= get_string('movingthisblockcancel', 'block',
975 html_writer
::link($this->page
->url
, get_string('cancel')));
978 $results[] = $content;
979 $lastweight = $instance->instance
->weight
;
980 $lastblock = $instance->instance
->id
;
983 if ($this->movingblock
&& $lastblock != $this->movingblock
) {
984 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight +
1));
990 * Ensure block instances exist for a given region
992 * @param string $region Check for bi's with the instance with this name
994 protected function ensure_instances_exist($region) {
995 $this->check_region_is_known($region);
996 if (!array_key_exists($region, $this->blockinstances
)) {
997 $this->blockinstances
[$region] =
998 $this->create_block_instances($this->birecordsbyregion
[$region]);
1003 * Ensure that there is some content within the given region
1005 * @param string $region The name of the region to check
1007 public function ensure_content_created($region, $output) {
1008 $this->ensure_instances_exist($region);
1009 if (!array_key_exists($region, $this->visibleblockcontent
)) {
1010 $contents = array();
1011 if (array_key_exists($region, $this->extracontent
)) {
1012 $contents = $this->extracontent
[$region];
1014 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances
[$region], $output, $region));
1015 if ($region == $this->defaultregion
) {
1016 $addblockui = block_add_block_ui($this->page
, $output);
1018 $contents[] = $addblockui;
1021 $this->visibleblockcontent
[$region] = $contents;
1025 /// Process actions from the URL ===============================================
1028 * Get the appropriate list of editing icons for a block. This is used
1029 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1031 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1032 * @return an array in the format for {@link block_contents::$controls}
1034 public function edit_controls($block) {
1037 $controls = array();
1038 $actionurl = $this->page
->url
->out(false, array('sesskey'=> sesskey()));
1039 $blocktitle = $block->title
;
1040 if (empty($blocktitle)) {
1041 $blocktitle = $block->arialabel
;
1044 if ($this->page
->user_can_edit_blocks()) {
1046 $str = new lang_string('moveblock', 'block', $blocktitle);
1047 $controls[] = new action_menu_link_primary(
1048 new moodle_url($actionurl, array('bui_moveid' => $block->instance
->id
)),
1049 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1051 array('class' => 'editing_move')
1056 if ($this->page
->user_can_edit_blocks() ||
$block->user_can_edit()) {
1057 // Edit config icon - always show - needed for positioning UI.
1058 $str = new lang_string('configureblock', 'block', $blocktitle);
1059 $controls[] = new action_menu_link_secondary(
1060 new moodle_url($actionurl, array('bui_editid' => $block->instance
->id
)),
1061 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1063 array('class' => 'editing_edit')
1068 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1070 if ($block->instance
->visible
) {
1071 $str = new lang_string('hideblock', 'block', $blocktitle);
1072 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance
->id
));
1073 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1074 $attributes = array('class' => 'editing_hide');
1076 $str = new lang_string('showblock', 'block', $blocktitle);
1077 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance
->id
));
1078 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1079 $attributes = array('class' => 'editing_show');
1081 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1084 // Assign roles icon.
1085 if (has_capability('moodle/role:assign', $block->context
)) {
1086 //TODO: please note it is sloppy to pass urls through page parameters!!
1087 // it is shortened because some web servers (e.g. IIS by default) give
1088 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1089 $return = $this->page
->url
->out(false);
1090 $return = str_replace($CFG->wwwroot
. '/', '', $return);
1092 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context
->id
,
1093 'returnurl'=>$return));
1095 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1096 $controls[] = new action_menu_link_secondary(
1098 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1100 array('class' => 'editing_roles')
1104 if ($this->user_can_delete_block($block)) {
1106 $str = new lang_string('deleteblock', 'block', $blocktitle);
1107 $controls[] = new action_menu_link_secondary(
1108 new moodle_url($actionurl, array('bui_deleteid' => $block->instance
->id
)),
1109 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1111 array('class' => 'editing_delete')
1119 * @param block_base $block a block that appears on this page.
1120 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1122 protected function user_can_delete_block($block) {
1123 return $this->page
->user_can_edit_blocks() && $block->user_can_edit() &&
1124 $block->user_can_addto($this->page
) &&
1125 !in_array($block->instance
->blockname
, self
::get_undeletable_block_types());
1129 * Process any block actions that were specified in the URL.
1131 * @return boolean true if anything was done. False if not.
1133 public function process_url_actions() {
1134 if (!$this->page
->user_is_editing()) {
1137 return $this->process_url_add() ||
$this->process_url_delete() ||
1138 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1139 $this->process_url_move();
1143 * Handle adding a block.
1144 * @return boolean true if anything was done. False if not.
1146 public function process_url_add() {
1147 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1154 if (!$this->page
->user_can_edit_blocks()) {
1155 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1158 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1159 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1162 $this->add_block_at_end_of_default_region($blocktype);
1164 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1165 $this->page
->ensure_param_not_in_url('bui_addblock');
1171 * Handle deleting a block.
1172 * @return boolean true if anything was done. False if not.
1174 public function process_url_delete() {
1175 global $CFG, $PAGE, $OUTPUT;
1177 $blockid = optional_param('bui_deleteid', null, PARAM_INT
);
1178 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT
);
1185 $block = $this->page
->blocks
->find_instance($blockid);
1186 if (!$this->user_can_delete_block($block)) {
1187 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1190 if (!$confirmdelete) {
1191 $deletepage = new moodle_page();
1192 $deletepage->set_pagelayout('admin');
1193 $deletepage->set_course($this->page
->course
);
1194 $deletepage->set_context($this->page
->context
);
1195 if ($this->page
->cm
) {
1196 $deletepage->set_cm($this->page
->cm
);
1199 $deleteurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1200 $deleteurlparams = $this->page
->url
->params();
1201 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1202 $deletepage->set_block_actions_done();
1203 // At this point we are either going to redirect, or display the form, so
1204 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1205 $PAGE = $deletepage;
1206 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1207 $output = $deletepage->get_renderer('core');
1211 $blocktitle = $block->get_title();
1212 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1213 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1215 // If the block is being shown in sub contexts display a warning.
1216 if ($block->instance
->showinsubcontexts
== 1) {
1217 $parentcontext = context
::instance_by_id($block->instance
->parentcontextid
);
1218 $systemcontext = context_system
::instance();
1219 $messagestring = new stdClass();
1220 $messagestring->location
= $parentcontext->get_context_name();
1222 // Checking for blocks that may have visibility on the front page and pages added on that.
1223 if ($parentcontext->id
!= $systemcontext->id
&& is_inside_frontpage($parentcontext)) {
1224 $messagestring->pagetype
= get_string('showonfrontpageandsubs', 'block');
1226 $pagetypes = generate_page_type_patterns($this->page
->pagetype
, $parentcontext);
1227 $messagestring->pagetype
= $block->instance
->pagetypepattern
;
1228 if (isset($pagetypes[$block->instance
->pagetypepattern
])) {
1229 $messagestring->pagetype
= $pagetypes[$block->instance
->pagetypepattern
];
1233 $message = get_string('deleteblockwarning', 'block', $messagestring);
1236 $PAGE->navbar
->add($strdeletecheck);
1237 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1238 $PAGE->set_heading($site->fullname
);
1239 echo $OUTPUT->header();
1240 $confirmurl = new moodle_url($deletepage->url
, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance
->id
, 'bui_confirm' => 1));
1241 $cancelurl = new moodle_url($deletepage->url
);
1242 $yesbutton = new single_button($confirmurl, get_string('yes'));
1243 $nobutton = new single_button($cancelurl, get_string('no'));
1244 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1245 echo $OUTPUT->footer();
1246 // Make sure that nothing else happens after we have displayed this form.
1249 blocks_delete_instance($block->instance
);
1250 // bui_deleteid and bui_confirm should not be in the PAGE url.
1251 $this->page
->ensure_param_not_in_url('bui_deleteid');
1252 $this->page
->ensure_param_not_in_url('bui_confirm');
1258 * Handle showing or hiding a block.
1259 * @return boolean true if anything was done. False if not.
1261 public function process_url_show_hide() {
1262 if ($blockid = optional_param('bui_hideid', null, PARAM_INT
)) {
1264 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT
)) {
1272 $block = $this->page
->blocks
->find_instance($blockid);
1274 if (!$this->page
->user_can_edit_blocks()) {
1275 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1276 } else if (!$block->instance_can_be_hidden()) {
1280 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1282 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1283 $this->page
->ensure_param_not_in_url('bui_hideid');
1284 $this->page
->ensure_param_not_in_url('bui_showid');
1290 * Handle showing/processing the submission from the block editing form.
1291 * @return boolean true if the form was submitted and the new config saved. Does not
1292 * return if the editing form was displayed. False otherwise.
1294 public function process_url_edit() {
1295 global $CFG, $DB, $PAGE, $OUTPUT;
1297 $blockid = optional_param('bui_editid', null, PARAM_INT
);
1303 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1305 $block = $this->find_instance($blockid);
1307 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1308 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1311 $editpage = new moodle_page();
1312 $editpage->set_pagelayout('admin');
1313 $editpage->set_course($this->page
->course
);
1314 //$editpage->set_context($block->context);
1315 $editpage->set_context($this->page
->context
);
1316 if ($this->page
->cm
) {
1317 $editpage->set_cm($this->page
->cm
);
1319 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1320 $editurlparams = $this->page
->url
->params();
1321 $editurlparams['bui_editid'] = $blockid;
1322 $editpage->set_url($editurlbase, $editurlparams);
1323 $editpage->set_block_actions_done();
1324 // At this point we are either going to redirect, or display the form, so
1325 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1327 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1328 $output = $editpage->get_renderer('core');
1331 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1332 if (is_readable($formfile)) {
1333 require_once($formfile);
1334 $classname = 'block_' . $block->name() . '_edit_form';
1335 if (!class_exists($classname)) {
1336 $classname = 'block_edit_form';
1339 $classname = 'block_edit_form';
1342 $mform = new $classname($editpage->url
, $block, $this->page
);
1343 $mform->set_data($block->instance
);
1345 if ($mform->is_cancelled()) {
1346 redirect($this->page
->url
);
1348 } else if ($data = $mform->get_data()) {
1350 $bi->id
= $block->instance
->id
;
1352 // This may get overwritten by the special case handling below.
1353 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1354 $bi->showinsubcontexts
= (bool) $data->bui_contexts
;
1355 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1356 $bi->subpagepattern
= null;
1358 $bi->subpagepattern
= $data->bui_subpagepattern
;
1361 $systemcontext = context_system
::instance();
1362 $frontpagecontext = context_course
::instance(SITEID
);
1363 $parentcontext = context
::instance_by_id($data->bui_parentcontextid
);
1365 // Updating stickiness and contexts. See MDL-21375 for details.
1366 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1368 // Explicitly set the default context
1369 $bi->parentcontextid
= $parentcontext->id
;
1371 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1373 // The interface here is a special case because the pagetype pattern is
1374 // totally derived from the context menu. Here are the excpetions. MDL-30340
1376 switch ($data->bui_contexts
) {
1377 case BUI_CONTEXTS_ENTIRE_SITE
:
1378 // The user wants to show the block across the entire site
1379 $bi->parentcontextid
= $systemcontext->id
;
1380 $bi->showinsubcontexts
= true;
1381 $bi->pagetypepattern
= '*';
1383 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1384 // The user wants the block shown on the front page and all subcontexts
1385 $bi->parentcontextid
= $frontpagecontext->id
;
1386 $bi->showinsubcontexts
= true;
1387 $bi->pagetypepattern
= '*';
1389 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1390 // The user want to show the front page on the frontpage only
1391 $bi->parentcontextid
= $frontpagecontext->id
;
1392 $bi->showinsubcontexts
= false;
1393 $bi->pagetypepattern
= 'site-index';
1394 // This is the only relevant page type anyway but we'll set it explicitly just
1395 // in case the front page grows site-index-* subpages of its own later
1401 $bits = explode('-', $bi->pagetypepattern
);
1402 // hacks for some contexts
1403 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1404 // For course context
1405 // is page type pattern is mod-*, change showinsubcontext to 1
1406 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1407 $bi->showinsubcontexts
= 1;
1409 $bi->showinsubcontexts
= 0;
1411 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1413 // subpagepattern should be null
1414 if ($bits[0] == 'user' or $bits[0] == 'my') {
1415 // we don't need subpagepattern in usercontext
1416 $bi->subpagepattern
= null;
1420 $bi->defaultregion
= $data->bui_defaultregion
;
1421 $bi->defaultweight
= $data->bui_defaultweight
;
1422 $DB->update_record('block_instances', $bi);
1424 if (!empty($block->config
)) {
1425 $config = clone($block->config
);
1427 $config = new stdClass
;
1429 foreach ($data as $configfield => $value) {
1430 if (strpos($configfield, 'config_') !== 0) {
1433 $field = substr($configfield, 7);
1434 $config->$field = $value;
1436 $block->instance_config_save($config);
1439 $bp->visible
= $data->bui_visible
;
1440 $bp->region
= $data->bui_region
;
1441 $bp->weight
= $data->bui_weight
;
1442 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1443 $data->bui_weight
!= $data->bui_defaultweight
;
1445 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1446 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1448 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1449 $bp->id
= $block->instance
->blockpositionid
;
1450 $DB->update_record('block_positions', $bp);
1452 } else if ($needbprecord) {
1453 $bp->blockinstanceid
= $block->instance
->id
;
1454 $bp->contextid
= $this->page
->context
->id
;
1455 $bp->pagetype
= $this->page
->pagetype
;
1456 if ($this->page
->subpage
) {
1457 $bp->subpage
= $this->page
->subpage
;
1461 $DB->insert_record('block_positions', $bp);
1464 redirect($this->page
->url
);
1467 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1468 $editpage->set_title($strheading);
1469 $editpage->set_heading($strheading);
1470 $bits = explode('-', $this->page
->pagetype
);
1471 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1472 // better navbar for tag pages
1473 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1474 $tag = tag_get('id', $this->page
->subpage
, '*');
1475 // tag search page doesn't have subpageid
1477 $editpage->navbar
->add($tag->name
, new moodle_url('/tag/index.php', array('id'=>$tag->id
)));
1480 $editpage->navbar
->add($block->get_title());
1481 $editpage->navbar
->add(get_string('configuration'));
1482 echo $output->header();
1483 echo $output->heading($strheading, 2);
1485 echo $output->footer();
1491 * Handle showing/processing the submission from the block editing form.
1492 * @return boolean true if the form was submitted and the new config saved. Does not
1493 * return if the editing form was displayed. False otherwise.
1495 public function process_url_move() {
1496 global $CFG, $DB, $PAGE;
1498 $blockid = optional_param('bui_moveid', null, PARAM_INT
);
1505 $block = $this->find_instance($blockid);
1507 if (!$this->page
->user_can_edit_blocks()) {
1508 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1511 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1512 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1513 if (!$newregion ||
is_null($newweight)) {
1514 // Don't have a valid target position yet, must be just starting the move.
1515 $this->movingblock
= $blockid;
1516 $this->page
->ensure_param_not_in_url('bui_moveid');
1520 if (!$this->is_known_region($newregion)) {
1521 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1524 // Move this block. This may involve moving other nearby blocks.
1525 $blocks = $this->birecordsbyregion
[$newregion];
1527 $maxweight = self
::MAX_WEIGHT
;
1528 $minweight = -self
::MAX_WEIGHT
;
1530 // Initialise the used weights and spareweights array with the default values
1531 $spareweights = array();
1532 $usedweights = array();
1533 for ($i = $minweight; $i <= $maxweight; $i++
) {
1534 $spareweights[$i] = $i;
1535 $usedweights[$i] = array();
1538 // Check each block and sort out where we have used weights
1539 foreach ($blocks as $bi) {
1540 if ($bi->weight
> $maxweight) {
1541 // If this statement is true then the blocks weight is more than the
1542 // current maximum. To ensure that we can get the best block position
1543 // we will initialise elements within the usedweights and spareweights
1544 // arrays between the blocks weight (which will then be the new max) and
1546 $parseweight = $bi->weight
;
1547 while (!array_key_exists($parseweight, $usedweights)) {
1548 $usedweights[$parseweight] = array();
1549 $spareweights[$parseweight] = $parseweight;
1552 $maxweight = $bi->weight
;
1553 } else if ($bi->weight
< $minweight) {
1554 // As above except this time the blocks weight is LESS than the
1555 // the current minimum, so we will initialise the array from the
1556 // blocks weight (new minimum) to the current minimum
1557 $parseweight = $bi->weight
;
1558 while (!array_key_exists($parseweight, $usedweights)) {
1559 $usedweights[$parseweight] = array();
1560 $spareweights[$parseweight] = $parseweight;
1563 $minweight = $bi->weight
;
1565 if ($bi->id
!= $block->instance
->id
) {
1566 unset($spareweights[$bi->weight
]);
1567 $usedweights[$bi->weight
][] = $bi->id
;
1571 // First we find the nearest gap in the list of weights.
1572 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1574 foreach ($spareweights as $spareweight) {
1575 if (abs($newweight - $spareweight) < $bestdistance) {
1576 $bestdistance = abs($newweight - $spareweight);
1577 $bestgap = $spareweight;
1581 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1582 if (is_null($bestgap)) {
1583 $bestgap = self
::MAX_WEIGHT +
1;
1584 while (!empty($usedweights[$bestgap])) {
1589 // Now we know the gap we are aiming for, so move all the blocks along.
1590 if ($bestgap < $newweight) {
1591 $newweight = floor($newweight);
1592 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1593 foreach ($usedweights[$weight] as $biid) {
1594 $this->reposition_block($biid, $newregion, $weight - 1);
1597 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1599 $newweight = ceil($newweight);
1600 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1601 if (array_key_exists($weight, $usedweights)) {
1602 foreach ($usedweights[$weight] as $biid) {
1603 $this->reposition_block($biid, $newregion, $weight +
1);
1607 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1610 $this->page
->ensure_param_not_in_url('bui_moveid');
1611 $this->page
->ensure_param_not_in_url('bui_newregion');
1612 $this->page
->ensure_param_not_in_url('bui_newweight');
1617 * Turns the display of normal blocks either on or off.
1619 * @param bool $setting
1621 public function show_only_fake_blocks($setting = true) {
1622 $this->fakeblocksonly
= $setting;
1626 /// Helper functions for working with block classes ============================
1629 * Call a class method (one that does not require a block instance) on a block class.
1631 * @param string $blockname the name of the block.
1632 * @param string $method the method name.
1633 * @param array $param parameters to pass to the method.
1634 * @return mixed whatever the method returns.
1636 function block_method_result($blockname, $method, $param = NULL) {
1637 if(!block_load_class($blockname)) {
1640 return call_user_func(array('block_'.$blockname, $method), $param);
1644 * Creates a new instance of the specified block class.
1646 * @param string $blockname the name of the block.
1647 * @param $instance block_instances DB table row (optional).
1648 * @param moodle_page $page the page this block is appearing on.
1649 * @return block_base the requested block instance.
1651 function block_instance($blockname, $instance = NULL, $page = NULL) {
1652 if(!block_load_class($blockname)) {
1655 $classname = 'block_'.$blockname;
1656 $retval = new $classname;
1657 if($instance !== NULL) {
1658 if (is_null($page)) {
1662 $retval->_load_instance($instance, $page);
1668 * Load the block class for a particular type of block.
1670 * @param string $blockname the name of the block.
1671 * @return boolean success or failure.
1673 function block_load_class($blockname) {
1676 if(empty($blockname)) {
1680 $classname = 'block_'.$blockname;
1682 if(class_exists($classname)) {
1686 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1688 if (file_exists($blockpath)) {
1689 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1690 include_once($blockpath);
1692 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1696 return class_exists($classname);
1700 * Given a specific page type, return all the page type patterns that might
1703 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1704 * @return array an array of all the page type patterns that might match this page type.
1706 function matching_page_type_patterns($pagetype) {
1707 $patterns = array($pagetype);
1708 $bits = explode('-', $pagetype);
1709 if (count($bits) == 3 && $bits[0] == 'mod') {
1710 if ($bits[2] == 'view') {
1711 $patterns[] = 'mod-*-view';
1712 } else if ($bits[2] == 'index') {
1713 $patterns[] = 'mod-*-index';
1716 while (count($bits) > 0) {
1717 $patterns[] = implode('-', $bits) . '-*';
1725 * Given a specific page type, parent context and currect context, return all the page type patterns
1726 * that might be used by this block.
1728 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1729 * @param stdClass $parentcontext Block's parent context
1730 * @param stdClass $currentcontext Current context of block
1731 * @return array an array of all the page type patterns that might match this page type.
1733 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1734 global $CFG; // Required for includes bellow.
1736 $bits = explode('-', $pagetype);
1738 $core = core_component
::get_core_subsystems();
1739 $plugins = core_component
::get_plugin_types();
1741 //progressively strip pieces off the page type looking for a match
1742 $componentarray = null;
1743 for ($i = count($bits); $i > 0; $i--) {
1744 $possiblecomponentarray = array_slice($bits, 0, $i);
1745 $possiblecomponent = implode('', $possiblecomponentarray);
1747 // Check to see if the component is a core component
1748 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1749 $libfile = $core[$possiblecomponent].'/lib.php';
1750 if (file_exists($libfile)) {
1751 require_once($libfile);
1752 $function = $possiblecomponent.'_page_type_list';
1753 if (function_exists($function)) {
1754 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1761 //check the plugin directory and look for a callback
1762 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1764 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1765 if (count($bits) > $i) {
1766 $pluginname = $bits[$i];
1767 $directory = core_component
::get_plugin_directory($possiblecomponent, $pluginname);
1768 if (!empty($directory)){
1769 $libfile = $directory.'/lib.php';
1770 if (file_exists($libfile)) {
1771 require_once($libfile);
1772 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1773 if (!function_exists($function)) {
1774 $function = $pluginname.'_page_type_list';
1776 if (function_exists($function)) {
1777 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1785 //we'll only get to here if we still don't have any patterns
1786 //the plugin type may have a callback
1787 $directory = $plugins[$possiblecomponent];
1788 $libfile = $directory.'/lib.php';
1789 if (file_exists($libfile)) {
1790 require_once($libfile);
1791 $function = $possiblecomponent.'_page_type_list';
1792 if (function_exists($function)) {
1793 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1801 if (empty($patterns)) {
1802 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1805 // Ensure that the * pattern is always available if editing block 'at distance', so
1806 // we always can 'bring back' it to the original context. MDL-30340
1807 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
1808 // TODO: We could change the string here, showing its 'bring back' meaning
1809 $patterns['*'] = get_string('page-x', 'pagetype');
1816 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1818 * @param string $pagetype
1819 * @param stdClass $parentcontext
1820 * @param stdClass $currentcontext
1823 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1824 // Generate page type patterns based on current page type if
1825 // callbacks haven't been defined
1826 $patterns = array($pagetype => $pagetype);
1827 $bits = explode('-', $pagetype);
1828 while (count($bits) > 0) {
1829 $pattern = implode('-', $bits) . '-*';
1830 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1831 // guessing page type description
1832 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1833 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1835 $patterns[$pattern] = $pattern;
1839 $patterns['*'] = get_string('page-x', 'pagetype');
1844 * Generates the page type list for the my moodle page
1846 * @param string $pagetype
1847 * @param stdClass $parentcontext
1848 * @param stdClass $currentcontext
1851 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1852 return array('my-index' => get_string('page-my-index', 'pagetype'));
1856 * Generates the page type list for a module by either locating and using the modules callback
1857 * or by generating a default list.
1859 * @param string $pagetype
1860 * @param stdClass $parentcontext
1861 * @param stdClass $currentcontext
1864 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1865 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1866 if (empty($patterns)) {
1867 // if modules don't have callbacks
1868 // generate two default page type patterns for modules only
1869 $bits = explode('-', $pagetype);
1870 $patterns = array($pagetype => $pagetype);
1871 if ($bits[2] == 'view') {
1872 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1873 } else if ($bits[2] == 'index') {
1874 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1879 /// Functions update the blocks if required by the request parameters ==========
1882 * Return a {@link block_contents} representing the add a new block UI, if
1883 * this user is allowed to see it.
1885 * @return block_contents an appropriate block_contents, or null if the user
1886 * cannot add any blocks here.
1888 function block_add_block_ui($page, $output) {
1889 global $CFG, $OUTPUT;
1890 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
1894 $bc = new block_contents();
1895 $bc->title
= get_string('addblock');
1896 $bc->add_class('block_adminblock');
1897 $bc->attributes
['data-block'] = 'adminblock';
1899 $missingblocks = $page->blocks
->get_addable_blocks();
1900 if (empty($missingblocks)) {
1901 $bc->content
= get_string('noblockstoaddhere');
1906 foreach ($missingblocks as $block) {
1907 $blockobject = block_instance($block->name
);
1908 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1909 $menu[$block->name
] = $blockobject->get_title();
1912 core_collator
::asort($menu);
1914 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
1915 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1916 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1917 $bc->content
= $OUTPUT->render($select);
1922 * Actually delete from the database any blocks that are currently on this page,
1923 * but which should not be there according to blocks_name_allowed_in_format.
1925 * @todo Write/Fix this function. Currently returns immediately
1928 function blocks_remove_inappropriate($course) {
1932 $blockmanager = blocks_get_by_page($page);
1934 if (empty($blockmanager)) {
1938 if (($pageformat = $page->pagetype) == NULL) {
1942 foreach($blockmanager as $region) {
1943 foreach($region as $instance) {
1944 $block = blocks_get_record($instance->blockid);
1945 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1946 blocks_delete_instance($instance->instance);
1953 * Check that a given name is in a permittable format
1955 * @param string $name
1956 * @param string $pageformat
1959 function blocks_name_allowed_in_format($name, $pageformat) {
1962 if (!$bi = block_instance($name)) {
1966 $formats = $bi->applicable_formats();
1970 foreach ($formats as $format => $allowed) {
1971 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1972 $depth = substr_count($format, '-');
1973 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1978 if ($accept === NULL) {
1979 $accept = !empty($formats['all']);
1985 * Delete a block, and associated data.
1987 * @param object $instance a row from the block_instances table
1988 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
1989 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
1991 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
1994 if ($block = block_instance($instance->blockname
, $instance)) {
1995 $block->instance_delete();
1997 context_helper
::delete_instance(CONTEXT_BLOCK
, $instance->id
);
1999 if (!$skipblockstables) {
2000 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
2001 $DB->delete_records('block_instances', array('id' => $instance->id
));
2002 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
2007 * Delete all the blocks that belong to a particular context.
2009 * @param int $contextid the context id.
2011 function blocks_delete_all_for_context($contextid) {
2013 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2014 foreach ($instances as $instance) {
2015 blocks_delete_instance($instance, true);
2017 $instances->close();
2018 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2019 $DB->delete_records('block_positions', array('contextid' => $contextid));
2023 * Set a block to be visible or hidden on a particular page.
2025 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2026 * block_positions table as return by block_manager.
2027 * @param moodle_page $page the back to set the visibility with respect to.
2028 * @param integer $newvisibility 1 for visible, 0 for hidden.
2030 function blocks_set_visibility($instance, $page, $newvisibility) {
2032 if (!empty($instance->blockpositionid
)) {
2033 // Already have local information on this page.
2034 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
2038 // Create a new block_positions record.
2040 $bp->blockinstanceid
= $instance->id
;
2041 $bp->contextid
= $page->context
->id
;
2042 $bp->pagetype
= $page->pagetype
;
2043 if ($page->subpage
) {
2044 $bp->subpage
= $page->subpage
;
2046 $bp->visible
= $newvisibility;
2047 $bp->region
= $instance->defaultregion
;
2048 $bp->weight
= $instance->defaultweight
;
2049 $DB->insert_record('block_positions', $bp);
2053 * Get the block record for a particular blockid - that is, a particular type os block.
2055 * @param $int blockid block type id. If null, an array of all block types is returned.
2056 * @param bool $notusedanymore No longer used.
2057 * @return array|object row from block table, or all rows.
2059 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2061 $blocks = $PAGE->blocks
->get_installed_blocks();
2062 if ($blockid === NULL) {
2064 } else if (isset($blocks[$blockid])) {
2065 return $blocks[$blockid];
2072 * Find a given block by its blockid within a provide array
2074 * @param int $blockid
2075 * @param array $blocksarray
2076 * @return bool|object Instance if found else false
2078 function blocks_find_block($blockid, $blocksarray) {
2079 if (empty($blocksarray)) {
2082 foreach($blocksarray as $blockgroup) {
2083 if (empty($blockgroup)) {
2086 foreach($blockgroup as $instance) {
2087 if($instance->blockid
== $blockid) {
2095 // Functions for programatically adding default blocks to pages ================
2098 * Parse a list of default blocks. See config-dist for a description of the format.
2100 * @param string $blocksstr
2103 function blocks_parse_default_blocks_list($blocksstr) {
2105 $bits = explode(':', $blocksstr);
2106 if (!empty($bits)) {
2107 $leftbits = trim(array_shift($bits));
2108 if ($leftbits != '') {
2109 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2112 if (!empty($bits)) {
2113 $rightbits =trim(array_shift($bits));
2114 if ($rightbits != '') {
2115 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2122 * @return array the blocks that should be added to the site course by default.
2124 function blocks_get_default_site_course_blocks() {
2127 if (!empty($CFG->defaultblocks_site
)) {
2128 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2131 BLOCK_POS_LEFT
=> array('site_main_menu'),
2132 BLOCK_POS_RIGHT
=> array('course_summary', 'calendar_month')
2138 * Add the default blocks to a course.
2140 * @param object $course a course object.
2142 function blocks_add_default_course_blocks($course) {
2145 if (!empty($CFG->defaultblocks_override
)) {
2146 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2148 } else if ($course->id
== SITEID
) {
2149 $blocknames = blocks_get_default_site_course_blocks();
2151 } else if (!empty($CFG->{'defaultblocks_' . $course->format
})) {
2152 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format
});
2155 require_once($CFG->dirroot
. '/course/lib.php');
2156 $blocknames = course_get_format($course)->get_default_blocks();
2160 if ($course->id
== SITEID
) {
2161 $pagetypepattern = 'site-index';
2163 $pagetypepattern = 'course-view-*';
2165 $page = new moodle_page();
2166 $page->set_course($course);
2167 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2171 * Add the default system-context blocks. E.g. the admin tree.
2173 function blocks_add_default_system_blocks() {
2176 $page = new moodle_page();
2177 $page->set_context(context_system
::instance());
2178 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('navigation', 'settings')), '*', null, true);
2179 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2181 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2182 $newcontent = array('course_overview');
2183 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> $newblocks, 'content' => $newcontent), 'my-index');