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 * @deprecated since Moodle 2.0. No longer used.
34 define('BLOCK_MOVE_LEFT', 0x01);
35 define('BLOCK_MOVE_RIGHT', 0x02);
36 define('BLOCK_MOVE_UP', 0x04);
37 define('BLOCK_MOVE_DOWN', 0x08);
38 define('BLOCK_CONFIGURE', 0x10);
42 * Default names for the block regions in the standard theme.
44 define('BLOCK_POS_LEFT', 'side-pre');
45 define('BLOCK_POS_RIGHT', 'side-post');
49 * @deprecated since Moodle 2.0. No longer used.
51 define('BLOCKS_PINNED_TRUE',0);
52 define('BLOCKS_PINNED_FALSE',1);
53 define('BLOCKS_PINNED_BOTH',2);
56 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
57 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
58 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
60 define('BUI_CONTEXTS_CURRENT', 0);
61 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
64 * Exception thrown when someone tried to do something with a block that does
65 * not exist on a page.
67 * @copyright 2009 Tim Hunt
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
71 class block_not_on_page_exception
extends moodle_exception
{
74 * @param int $instanceid the block instance id of the block that was looked for.
75 * @param object $page the current page.
77 public function __construct($instanceid, $page) {
79 $a->instanceid
= $instanceid;
80 $a->url
= $page->url
->out();
81 parent
::__construct('blockdoesnotexistonpage', '', $page->url
->out(), $a);
86 * This class keeps track of the block that should appear on a moodle_page.
88 * The page to work with as passed to the constructor.
90 * @copyright 2009 Tim Hunt
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
96 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
97 * although other weights are valid.
99 const MAX_WEIGHT
= 10;
101 /// Field declarations =========================================================
104 * the moodle_page we are managing blocks for.
109 /** @var array region name => 1.*/
110 protected $regions = array();
112 /** @var string the region where new blocks are added.*/
113 protected $defaultregion = null;
115 /** @var array will be $DB->get_records('blocks') */
116 protected $allblocks = null;
119 * @var array blocks that this user can add to this page. Will be a subset
120 * of $allblocks, but with array keys block->name. Access this via the
121 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
123 protected $addableblocks = null;
126 * Will be an array region-name => array(db rows loaded in load_blocks);
129 protected $birecordsbyregion = null;
132 * array region-name => array(block objects); populated as necessary by
133 * the ensure_instances_exist method.
136 protected $blockinstances = array();
139 * array region-name => array(block_contents objects) what actually needs to
140 * be displayed in each region.
143 protected $visibleblockcontent = array();
146 * array region-name => array(block_contents objects) extra block-like things
147 * to be displayed in each region, before the real blocks.
150 protected $extracontent = array();
153 * Used by the block move id, to track whether a block is currently being moved.
155 * When you click on the move icon of a block, first the page needs to reload with
156 * extra UI for choosing a new position for a particular block. In that situation
157 * this field holds the id of the block being moved.
161 protected $movingblock = null;
164 * Show only fake blocks
166 protected $fakeblocksonly = false;
168 /// Constructor ================================================================
172 * @param object $page the moodle_page object object we are managing the blocks for,
173 * or a reasonable faxilimily. (See the comment at the top of this class
174 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
176 public function __construct($page) {
180 /// Getter methods =============================================================
183 * Get an array of all region names on this page where a block may appear
185 * @return array the internal names of the regions on this page where block may appear.
187 public function get_regions() {
188 if (is_null($this->defaultregion
)) {
189 $this->page
->initialise_theme_and_output();
191 return array_keys($this->regions
);
195 * Get the region name of the region blocks are added to by default
197 * @return string the internal names of the region where new blocks are added
198 * by default, and where any blocks from an unrecognised region are shown.
199 * (Imagine that blocks were added with one theme selected, then you switched
200 * to a theme with different block positions.)
202 public function get_default_region() {
203 $this->page
->initialise_theme_and_output();
204 return $this->defaultregion
;
208 * The list of block types that may be added to this page.
210 * @return array block name => record from block table.
212 public function get_addable_blocks() {
213 $this->check_is_loaded();
215 if (!is_null($this->addableblocks
)) {
216 return $this->addableblocks
;
220 $this->addableblocks
= array();
222 $allblocks = blocks_get_record();
223 if (empty($allblocks)) {
224 return $this->addableblocks
;
227 $pageformat = $this->page
->pagetype
;
228 foreach($allblocks as $block) {
229 if (!$bi = block_instance($block->name
)) {
232 if ($block->visible
&&
233 ($bi->instance_allow_multiple() ||
!$this->is_block_present($block->name
)) &&
234 blocks_name_allowed_in_format($block->name
, $pageformat) &&
235 $bi->user_can_addto($this->page
)) {
236 $this->addableblocks
[$block->name
] = $block;
240 return $this->addableblocks
;
244 * Given a block name, find out of any of them are currently present in the page
246 * @param string $blockname - the basic name of a block (eg "navigation")
247 * @return boolean - is there one of these blocks in the current page?
249 public function is_block_present($blockname) {
250 if (empty($this->blockinstances
)) {
254 foreach ($this->blockinstances
as $region) {
255 foreach ($region as $instance) {
256 if (empty($instance->instance
->blockname
)) {
259 if ($instance->instance
->blockname
== $blockname) {
268 * Find out if a block type is known by the system
270 * @param string $blockname the name of the type of block.
271 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
272 * @return boolean true if this block in installed.
274 public function is_known_block_type($blockname, $includeinvisible = false) {
275 $blocks = $this->get_installed_blocks();
276 foreach ($blocks as $block) {
277 if ($block->name
== $blockname && ($includeinvisible ||
$block->visible
)) {
285 * Find out if a region exists on a page
287 * @param string $region a region name
288 * @return boolean true if this region exists on this page.
290 public function is_known_region($region) {
291 return array_key_exists($region, $this->regions
);
295 * Get an array of all blocks within a given region
297 * @param string $region a block region that exists on this page.
298 * @return array of block instances.
300 public function get_blocks_for_region($region) {
301 $this->check_is_loaded();
302 $this->ensure_instances_exist($region);
303 return $this->blockinstances
[$region];
307 * Returns an array of block content objects that exist in a region
309 * @param string $region a block region that exists on this page.
310 * @return array of block block_contents objects for all the blocks in a region.
312 public function get_content_for_region($region, $output) {
313 $this->check_is_loaded();
314 $this->ensure_content_created($region, $output);
315 return $this->visibleblockcontent
[$region];
319 * Helper method used by get_content_for_region.
320 * @param string $region region name
321 * @param float $weight weight. May be fractional, since you may want to move a block
322 * between ones with weight 2 and 3, say ($weight would be 2.5).
323 * @return string URL for moving block $this->movingblock to this position.
325 protected function get_move_target_url($region, $weight) {
326 return new moodle_url($this->page
->url
, array('bui_moveid' => $this->movingblock
,
327 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
331 * Determine whether a region contains anything. (Either any real blocks, or
332 * the add new block UI.)
334 * (You may wonder why the $output parameter is required. Unfortunately,
335 * because of the way that blocks work, the only reliable way to find out
336 * if a block will be visible is to get the content for output, and to
337 * get the content, you need a renderer. Fortunately, this is not a
338 * performance problem, because we cache the output that is generated, and
339 * in almost every case where we call region_has_content, we are about to
340 * output the blocks anyway, so we are not doing wasted effort.)
342 * @param string $region a block region that exists on this page.
343 * @param object $output a core_renderer. normally the global $OUTPUT.
344 * @return boolean Whether there is anything in this region.
346 public function region_has_content($region, $output) {
348 if (!$this->is_known_region($region)) {
351 $this->check_is_loaded();
352 $this->ensure_content_created($region, $output);
353 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
354 // Mark Nielsen's patch - part 1
355 if ($this->page
->user_is_editing() && $this->page
->user_can_edit_blocks() && $this->movingblock
) {
356 // If editing is on, we need all the block regions visible, for the
360 return !empty($this->visibleblockcontent
[$region]) ||
!empty($this->extracontent
[$region]);
364 * Get an array of all of the installed blocks.
366 * @return array contents of the block table.
368 public function get_installed_blocks() {
370 if (is_null($this->allblocks
)) {
371 $this->allblocks
= $DB->get_records('block');
373 return $this->allblocks
;
376 /// Setter methods =============================================================
379 * Add a region to a page
381 * @param string $region add a named region where blocks may appear on the
382 * current page. This is an internal name, like 'side-pre', not a string to
385 public function add_region($region) {
386 $this->check_not_yet_loaded();
387 $this->regions
[$region] = 1;
391 * Add an array of regions
394 * @param array $regions this utility method calls add_region for each array element.
396 public function add_regions($regions) {
397 foreach ($regions as $region) {
398 $this->add_region($region);
403 * Set the default region for new blocks on the page
405 * @param string $defaultregion the internal names of the region where new
406 * blocks should be added by default, and where any blocks from an
407 * unrecognised region are shown.
409 public function set_default_region($defaultregion) {
410 $this->check_not_yet_loaded();
411 if ($defaultregion) {
412 $this->check_region_is_known($defaultregion);
414 $this->defaultregion
= $defaultregion;
418 * Add something that looks like a block, but which isn't an actual block_instance,
421 * @param block_contents $bc the content of the block-like thing.
422 * @param string $region a block region that exists on this page.
424 public function add_fake_block($bc, $region) {
425 $this->page
->initialise_theme_and_output();
426 if (!$this->is_known_region($region)) {
427 $region = $this->get_default_region();
429 if (array_key_exists($region, $this->visibleblockcontent
)) {
430 throw new coding_exception('block_manager has already prepared the blocks in region ' .
431 $region . 'for output. It is too late to add a fake block.');
433 $this->extracontent
[$region][] = $bc;
437 * When the block_manager class was created, the {@link add_fake_block()}
438 * was called add_pretend_block, which is inconsisted with
439 * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
440 * was renamed to add_fake_block. Please update your code.
441 * @param block_contents $bc the content of the block-like thing.
442 * @param string $region a block region that exists on this page.
444 public function add_pretend_block($bc, $region) {
445 debugging(DEBUG_DEVELOPER
, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
446 $this->add_fake_block($bc, $region);
450 * Checks to see whether all of the blocks within the given region are docked
452 * @see region_uses_dock
453 * @param string $region
454 * @return bool True if all of the blocks within that region are docked
456 public function region_completely_docked($region, $output) {
458 // If theme doesn't allow docking or allowblockstodock is not set, then return.
459 if (!$this->page
->theme
->enable_dock ||
empty($CFG->allowblockstodock
)) {
463 // Do not dock the region when the user attemps to move a block.
464 if ($this->movingblock
) {
468 $this->check_is_loaded();
469 $this->ensure_content_created($region, $output);
470 foreach($this->visibleblockcontent
[$region] as $instance) {
471 if (!empty($instance->content
) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
479 * Checks to see whether any of the blocks within the given regions are docked
481 * @see region_completely_docked
482 * @param array|string $regions array of regions (or single region)
483 * @return bool True if any of the blocks within that region are docked
485 public function region_uses_dock($regions, $output) {
486 if (!$this->page
->theme
->enable_dock
) {
489 $this->check_is_loaded();
490 foreach((array)$regions as $region) {
491 $this->ensure_content_created($region, $output);
492 foreach($this->visibleblockcontent
[$region] as $instance) {
493 if(!empty($instance->content
) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
501 /// Actions ====================================================================
504 * This method actually loads the blocks for our page from the database.
506 * @param boolean|null $includeinvisible
507 * null (default) - load hidden blocks if $this->page->user_is_editing();
508 * true - load hidden blocks.
509 * false - don't load hidden blocks.
511 public function load_blocks($includeinvisible = null) {
514 if (!is_null($this->birecordsbyregion
)) {
519 if ($CFG->version
< 2009050619) {
520 // Upgrade/install not complete. Don't try too show any blocks.
521 $this->birecordsbyregion
= array();
525 // Ensure we have been initialised.
526 if (is_null($this->defaultregion
)) {
527 $this->page
->initialise_theme_and_output();
528 // If there are still no block regions, then there are no blocks on this page.
529 if (empty($this->regions
)) {
530 $this->birecordsbyregion
= array();
535 // Check if we need to load normal blocks
536 if ($this->fakeblocksonly
) {
537 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
541 if (is_null($includeinvisible)) {
542 $includeinvisible = $this->page
->user_is_editing();
544 if ($includeinvisible) {
547 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
550 $context = $this->page
->context
;
551 $contexttest = 'bi.parentcontextid = :contextid2';
552 $parentcontextparams = array();
553 $parentcontextids = get_parent_contexts($context);
554 if ($parentcontextids) {
555 list($parentcontexttest, $parentcontextparams) =
556 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
, 'parentcontext');
557 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
560 $pagetypepatterns = matching_page_type_patterns($this->page
->pagetype
);
561 list($pagetypepatterntest, $pagetypepatternparams) =
562 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
, 'pagetypepatterntest');
564 list($ccselect, $ccjoin) = context_instance_preload_sql('bi.id', CONTEXT_BLOCK
, 'ctx');
567 'subpage1' => $this->page
->subpage
,
568 'subpage2' => $this->page
->subpage
,
569 'contextid1' => $context->id
,
570 'contextid2' => $context->id
,
571 'pagetype' => $this->page
->pagetype
,
573 if ($this->page
->subpage
=== '') {
574 $params['subpage1'] = $DB->sql_empty();
575 $params['subpage2'] = $DB->sql_empty();
579 bp.id AS blockpositionid,
582 bi.showinsubcontexts,
587 COALESCE(bp.visible, 1) AS visible,
588 COALESCE(bp.region, bi.defaultregion) AS region,
589 COALESCE(bp.weight, bi.defaultweight) AS weight,
593 FROM {block_instances} bi
594 JOIN {block} b ON bi.blockname = b.name
595 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
596 AND bp.contextid = :contextid1
597 AND bp.pagetype = :pagetype
598 AND bp.subpage = :subpage1
603 AND bi.pagetypepattern $pagetypepatterntest
604 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
609 COALESCE(bp.region, bi.defaultregion),
610 COALESCE(bp.weight, bi.defaultweight),
612 $blockinstances = $DB->get_recordset_sql($sql, $params +
$parentcontextparams +
$pagetypepatternparams);
614 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
616 foreach ($blockinstances as $bi) {
617 context_instance_preload($bi);
618 if ($this->is_known_region($bi->region
)) {
619 $this->birecordsbyregion
[$bi->region
][] = $bi;
625 // Pages don't necessarily have a defaultregion. The one time this can
626 // happen is when there are no theme block regions, but the script itself
627 // has a block region in the main content area.
628 if (!empty($this->defaultregion
)) {
629 $this->birecordsbyregion
[$this->defaultregion
] =
630 array_merge($this->birecordsbyregion
[$this->defaultregion
], $unknown);
635 * Add a block to the current page, or related pages. The block is added to
636 * context $this->page->contextid. If $pagetypepattern $subpagepattern
638 * @param string $blockname The type of block to add.
639 * @param string $region the block region on this page to add the block to.
640 * @param integer $weight determines the order where this block appears in the region.
641 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
642 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
643 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
645 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
647 // Allow invisible blocks because this is used when adding default page blocks, which
648 // might include invisible ones if the user makes some default blocks invisible
649 $this->check_known_block_type($blockname, true);
650 $this->check_region_is_known($region);
652 if (empty($pagetypepattern)) {
653 $pagetypepattern = $this->page
->pagetype
;
656 $blockinstance = new stdClass
;
657 $blockinstance->blockname
= $blockname;
658 $blockinstance->parentcontextid
= $this->page
->context
->id
;
659 $blockinstance->showinsubcontexts
= !empty($showinsubcontexts);
660 $blockinstance->pagetypepattern
= $pagetypepattern;
661 $blockinstance->subpagepattern
= $subpagepattern;
662 $blockinstance->defaultregion
= $region;
663 $blockinstance->defaultweight
= $weight;
664 $blockinstance->configdata
= '';
665 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
667 // Ensure the block context is created.
668 get_context_instance(CONTEXT_BLOCK
, $blockinstance->id
);
670 // If the new instance was created, allow it to do additional setup
671 if ($block = block_instance($blockname, $blockinstance)) {
672 $block->instance_create();
676 public function add_block_at_end_of_default_region($blockname) {
677 $defaulregion = $this->get_default_region();
679 $lastcurrentblock = end($this->birecordsbyregion
[$defaulregion]);
680 if ($lastcurrentblock) {
681 $weight = $lastcurrentblock->weight +
1;
686 if ($this->page
->subpage
) {
687 $subpage = $this->page
->subpage
;
692 // Special case. Course view page type include the course format, but we
693 // want to add the block non-format-specifically.
694 $pagetypepattern = $this->page
->pagetype
;
695 if (strpos($pagetypepattern, 'course-view') === 0) {
696 $pagetypepattern = 'course-view-*';
699 // We should end using this for ALL the blocks, making always the 1st option
700 // the default one to be used. Until then, this is one hack to avoid the
701 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
702 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
703 // (the FIRST $pagetypepattern will be set)
705 // We are applying it to all blocks created in mod pages for now and only if the
706 // default pagetype is not one of the available options
707 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
708 $pagetypelist = generate_page_type_patterns($this->page
->pagetype
, null, $this->page
->context
);
709 // Only go for the first if the pagetype is not a valid option
710 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
711 $pagetypepattern = key($pagetypelist);
714 // Surely other pages like course-report will need this too, they just are not important
715 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
717 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
721 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
723 * @param array $blocks array with array keys the region names, and values an array of block names.
724 * @param string $pagetypepattern optional. Passed to @see add_block()
725 * @param string $subpagepattern optional. Passed to @see add_block()
727 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
728 $this->add_regions(array_keys($blocks));
729 foreach ($blocks as $region => $regionblocks) {
731 foreach ($regionblocks as $blockname) {
732 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
739 * Move a block to a new position on this page.
741 * If this block cannot appear on any other pages, then we change defaultposition/weight
742 * in the block_instances table. Otherwise we just set the position on this page.
744 * @param $blockinstanceid the block instance id.
745 * @param $newregion the new region name.
746 * @param $newweight the new weight.
748 public function reposition_block($blockinstanceid, $newregion, $newweight) {
751 $this->check_region_is_known($newregion);
752 $inst = $this->find_instance($blockinstanceid);
754 $bi = $inst->instance
;
755 if ($bi->weight
== $bi->defaultweight
&& $bi->region
== $bi->defaultregion
&&
756 !$bi->showinsubcontexts
&& strpos($bi->pagetypepattern
, '*') === false &&
757 (!$this->page
->subpage ||
$bi->subpagepattern
)) {
759 // Set default position
760 $newbi = new stdClass
;
761 $newbi->id
= $bi->id
;
762 $newbi->defaultregion
= $newregion;
763 $newbi->defaultweight
= $newweight;
764 $DB->update_record('block_instances', $newbi);
766 if ($bi->blockpositionid
) {
768 $bp->id
= $bi->blockpositionid
;
769 $bp->region
= $newregion;
770 $bp->weight
= $newweight;
771 $DB->update_record('block_positions', $bp);
775 // Just set position on this page.
777 $bp->region
= $newregion;
778 $bp->weight
= $newweight;
780 if ($bi->blockpositionid
) {
781 $bp->id
= $bi->blockpositionid
;
782 $DB->update_record('block_positions', $bp);
785 $bp->blockinstanceid
= $bi->id
;
786 $bp->contextid
= $this->page
->context
->id
;
787 $bp->pagetype
= $this->page
->pagetype
;
788 if ($this->page
->subpage
) {
789 $bp->subpage
= $this->page
->subpage
;
793 $bp->visible
= $bi->visible
;
794 $DB->insert_record('block_positions', $bp);
800 * Find a given block by its instance id
802 * @param integer $instanceid
805 public function find_instance($instanceid) {
806 foreach ($this->regions
as $region => $notused) {
807 $this->ensure_instances_exist($region);
808 foreach($this->blockinstances
[$region] as $instance) {
809 if ($instance->instance
->id
== $instanceid) {
814 throw new block_not_on_page_exception($instanceid, $this->page
);
817 /// Inner workings =============================================================
820 * Check whether the page blocks have been loaded yet
822 * @return void Throws coding exception if already loaded
824 protected function check_not_yet_loaded() {
825 if (!is_null($this->birecordsbyregion
)) {
826 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.');
831 * Check whether the page blocks have been loaded yet
833 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
835 * @return void Throws coding exception if already loaded
837 protected function check_is_loaded() {
838 if (is_null($this->birecordsbyregion
)) {
839 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
844 * Check if a block type is known and usable
846 * @param string $blockname The block type name to search for
847 * @param bool $includeinvisible Include disabled block types in the initial pass
848 * @return void Coding Exception thrown if unknown or not enabled
850 protected function check_known_block_type($blockname, $includeinvisible = false) {
851 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
852 if ($this->is_known_block_type($blockname, true)) {
853 throw new coding_exception('Unknown block type ' . $blockname);
855 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
861 * Check if a region is known by its name
863 * @param string $region
864 * @return void Coding Exception thrown if the region is not known
866 protected function check_region_is_known($region) {
867 if (!$this->is_known_region($region)) {
868 throw new coding_exception('Trying to reference an unknown block region ' . $region);
873 * Returns an array of region names as keys and nested arrays for values
875 * @return array an array where the array keys are the region names, and the array
876 * values are empty arrays.
878 protected function prepare_per_region_arrays() {
880 foreach ($this->regions
as $region => $notused) {
881 $result[$region] = array();
887 * Create a set of new block instance from a record array
889 * @param array $birecords An array of block instance records
890 * @return array An array of instantiated block_instance objects
892 protected function create_block_instances($birecords) {
894 foreach ($birecords as $record) {
895 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
896 $results[] = $blockobject;
903 * Create all the block instances for all the blocks that were loaded by
904 * load_blocks. This is used, for example, to ensure that all blocks get a
905 * chance to initialise themselves via the {@link block_base::specialize()}
906 * method, before any output is done.
908 public function create_all_block_instances() {
909 foreach ($this->get_regions() as $region) {
910 $this->ensure_instances_exist($region);
915 * Return an array of content objects from a set of block instances
917 * @param array $instances An array of block instances
918 * @param renderer_base The renderer to use.
919 * @param string $region the region name.
920 * @return array An array of block_content (and possibly block_move_target) objects.
922 protected function create_block_contents($instances, $output, $region) {
927 if ($this->movingblock
) {
928 $first = reset($instances);
930 $lastweight = $first->instance
->weight
- 2;
933 $strmoveblockhere = get_string('moveblockhere', 'block');
936 foreach ($instances as $instance) {
937 $content = $instance->get_content_for_output($output);
938 if (empty($content)) {
942 if ($this->movingblock
&& $lastweight != $instance->instance
->weight
&&
943 $content->blockinstanceid
!= $this->movingblock
&& $lastblock != $this->movingblock
) {
944 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, ($lastweight +
$instance->instance
->weight
)/2));
947 if ($content->blockinstanceid
== $this->movingblock
) {
948 $content->add_class('beingmoved');
949 $content->annotation
.= get_string('movingthisblockcancel', 'block',
950 html_writer
::link($this->page
->url
, get_string('cancel')));
953 $results[] = $content;
954 $lastweight = $instance->instance
->weight
;
955 $lastblock = $instance->instance
->id
;
958 if ($this->movingblock
&& $lastblock != $this->movingblock
) {
959 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight +
1));
965 * Ensure block instances exist for a given region
967 * @param string $region Check for bi's with the instance with this name
969 protected function ensure_instances_exist($region) {
970 $this->check_region_is_known($region);
971 if (!array_key_exists($region, $this->blockinstances
)) {
972 $this->blockinstances
[$region] =
973 $this->create_block_instances($this->birecordsbyregion
[$region]);
978 * Ensure that there is some content within the given region
980 * @param string $region The name of the region to check
982 protected function ensure_content_created($region, $output) {
983 $this->ensure_instances_exist($region);
984 if (!array_key_exists($region, $this->visibleblockcontent
)) {
986 if (array_key_exists($region, $this->extracontent
)) {
987 $contents = $this->extracontent
[$region];
989 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances
[$region], $output, $region));
990 if ($region == $this->defaultregion
) {
991 $addblockui = block_add_block_ui($this->page
, $output);
993 $contents[] = $addblockui;
996 $this->visibleblockcontent
[$region] = $contents;
1000 /// Process actions from the URL ===============================================
1003 * Get the appropriate list of editing icons for a block. This is used
1004 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1006 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1007 * @return an array in the format for {@link block_contents::$controls}
1009 public function edit_controls($block) {
1012 if (!isset($CFG->undeletableblocktypes
) ||
(!is_array($CFG->undeletableblocktypes
) && !is_string($CFG->undeletableblocktypes
))) {
1013 $undeletableblocktypes = array('navigation','settings');
1014 } else if (is_string($CFG->undeletableblocktypes
)) {
1015 $undeletableblocktypes = explode(',', $CFG->undeletableblocktypes
);
1017 $undeletableblocktypes = $CFG->undeletableblocktypes
;
1020 $controls = array();
1021 $actionurl = $this->page
->url
->out(false, array('sesskey'=> sesskey()));
1023 if ($this->page
->user_can_edit_blocks()) {
1025 $controls[] = array('url' => $actionurl . '&bui_moveid=' . $block->instance
->id
,
1026 'icon' => 't/move', 'caption' => get_string('moveblock', 'block', $block->title
),
1027 'class' => 'editing_move');
1030 if ($this->page
->user_can_edit_blocks() ||
$block->user_can_edit()) {
1031 // Edit config icon - always show - needed for positioning UI.
1032 $controls[] = array('url' => $actionurl . '&bui_editid=' . $block->instance
->id
,
1033 'icon' => 't/edit', 'caption' => get_string('configureblock', 'block', $block->title
),
1034 'class' => 'editing_edit');
1037 if ($this->page
->user_can_edit_blocks() && $block->user_can_edit() && $block->user_can_addto($this->page
)) {
1038 if (!in_array($block->instance
->blockname
, $undeletableblocktypes)
1039 ||
!in_array($block->instance
->pagetypepattern
, array('*', 'site-index'))
1040 ||
$block->instance
->parentcontextid
!= SITEID
) {
1042 $controls[] = array('url' => $actionurl . '&bui_deleteid=' . $block->instance
->id
,
1043 'icon' => 't/delete', 'caption' => get_string('deleteblock', 'block', $block->title
),
1044 'class' => 'editing_delete');
1048 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1050 if ($block->instance
->visible
) {
1051 $controls[] = array('url' => $actionurl . '&bui_hideid=' . $block->instance
->id
,
1052 'icon' => 't/hide', 'caption' => get_string('hideblock', 'block', $block->title
),
1053 'class' => 'editing_hide');
1055 $controls[] = array('url' => $actionurl . '&bui_showid=' . $block->instance
->id
,
1056 'icon' => 't/show', 'caption' => get_string('showblock', 'block', $block->title
),
1057 'class' => 'editing_show');
1061 // Assign roles icon.
1062 if (has_capability('moodle/role:assign', $block->context
)) {
1063 //TODO: please note it is sloppy to pass urls through page parameters!!
1064 // it is shortened because some web servers (e.g. IIS by default) give
1065 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1066 $return = $this->page
->url
->out(false);
1067 $return = str_replace($CFG->wwwroot
. '/', '', $return);
1069 $controls[] = array('url' => $CFG->wwwroot
. '/' . $CFG->admin
.
1070 '/roles/assign.php?contextid=' . $block->context
->id
. '&returnurl=' . urlencode($return),
1071 'icon' => 'i/roles', 'caption' => get_string('assignrolesinblock', 'block', $block->title
),
1072 'class' => 'editing_roles');
1079 * Process any block actions that were specified in the URL.
1081 * @return boolean true if anything was done. False if not.
1083 public function process_url_actions() {
1084 if (!$this->page
->user_is_editing()) {
1087 return $this->process_url_add() ||
$this->process_url_delete() ||
1088 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1089 $this->process_url_move();
1093 * Handle adding a block.
1094 * @return boolean true if anything was done. False if not.
1096 public function process_url_add() {
1097 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1104 if (!$this->page
->user_can_edit_blocks()) {
1105 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1108 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1109 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1112 $this->add_block_at_end_of_default_region($blocktype);
1114 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1115 $this->page
->ensure_param_not_in_url('bui_addblock');
1121 * Handle deleting a block.
1122 * @return boolean true if anything was done. False if not.
1124 public function process_url_delete() {
1125 global $CFG, $PAGE, $OUTPUT;
1127 $blockid = optional_param('bui_deleteid', null, PARAM_INT
);
1128 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT
);
1135 $block = $this->page
->blocks
->find_instance($blockid);
1136 if (!$block->user_can_edit() ||
!$this->page
->user_can_edit_blocks() ||
!$block->user_can_addto($this->page
)) {
1137 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1140 if (!$confirmdelete) {
1141 $deletepage = new moodle_page();
1142 $deletepage->set_pagelayout('admin');
1143 $deletepage->set_course($this->page
->course
);
1144 $deletepage->set_context($this->page
->context
);
1145 if ($this->page
->cm
) {
1146 $deletepage->set_cm($this->page
->cm
);
1149 $deleteurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1150 $deleteurlparams = $this->page
->url
->params();
1151 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1152 $deletepage->set_block_actions_done();
1153 // At this point we are either going to redirect, or display the form, so
1154 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1155 $PAGE = $deletepage;
1156 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1157 $output = $deletepage->get_renderer('core');
1161 $blocktitle = $block->get_title();
1162 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1163 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1165 // If the block is being shown in sub contexts display a warning.
1166 if ($block->instance
->showinsubcontexts
== 1) {
1167 $parentcontext = context
::instance_by_id($block->instance
->parentcontextid
);
1168 $systemcontext = context_system
::instance();
1169 $messagestring = new stdClass();
1170 $messagestring->location
= $parentcontext->get_context_name();
1172 // Checking for blocks that may have visibility on the front page and pages added on that.
1173 if ($parentcontext->id
!= $systemcontext->id
&& is_inside_frontpage($parentcontext)) {
1174 $messagestring->pagetype
= get_string('showonfrontpageandsubs', 'block');
1176 $pagetypes = generate_page_type_patterns($this->page
->pagetype
, $parentcontext);
1177 $messagestring->pagetype
= $block->instance
->pagetypepattern
;
1178 if (isset($pagetypes[$block->instance
->pagetypepattern
])) {
1179 $messagestring->pagetype
= $pagetypes[$block->instance
->pagetypepattern
];
1183 $message = get_string('deleteblockwarning', 'block', $messagestring);
1186 $PAGE->navbar
->add($strdeletecheck);
1187 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1188 $PAGE->set_heading($site->fullname
);
1189 echo $OUTPUT->header();
1190 $confirmurl = new moodle_url($deletepage->url
, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance
->id
, 'bui_confirm' => 1));
1191 $cancelurl = new moodle_url($deletepage->url
);
1192 $yesbutton = new single_button($confirmurl, get_string('yes'));
1193 $nobutton = new single_button($cancelurl, get_string('no'));
1194 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1195 echo $OUTPUT->footer();
1196 // Make sure that nothing else happens after we have displayed this form.
1199 blocks_delete_instance($block->instance
);
1200 // bui_deleteid and bui_confirm should not be in the PAGE url.
1201 $this->page
->ensure_param_not_in_url('bui_deleteid');
1202 $this->page
->ensure_param_not_in_url('bui_confirm');
1208 * Handle showing or hiding a block.
1209 * @return boolean true if anything was done. False if not.
1211 public function process_url_show_hide() {
1212 if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER
)) {
1214 } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER
)) {
1222 $block = $this->page
->blocks
->find_instance($blockid);
1224 if (!$this->page
->user_can_edit_blocks()) {
1225 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1226 } else if (!$block->instance_can_be_hidden()) {
1230 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1232 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1233 $this->page
->ensure_param_not_in_url('bui_hideid');
1234 $this->page
->ensure_param_not_in_url('bui_showid');
1240 * Handle showing/processing the submission from the block editing form.
1241 * @return boolean true if the form was submitted and the new config saved. Does not
1242 * return if the editing form was displayed. False otherwise.
1244 public function process_url_edit() {
1245 global $CFG, $DB, $PAGE, $OUTPUT;
1247 $blockid = optional_param('bui_editid', null, PARAM_INTEGER
);
1253 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1255 $block = $this->find_instance($blockid);
1257 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1258 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1261 $editpage = new moodle_page();
1262 $editpage->set_pagelayout('admin');
1263 $editpage->set_course($this->page
->course
);
1264 //$editpage->set_context($block->context);
1265 $editpage->set_context($this->page
->context
);
1266 if ($this->page
->cm
) {
1267 $editpage->set_cm($this->page
->cm
);
1269 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1270 $editurlparams = $this->page
->url
->params();
1271 $editurlparams['bui_editid'] = $blockid;
1272 $editpage->set_url($editurlbase, $editurlparams);
1273 $editpage->set_block_actions_done();
1274 // At this point we are either going to redirect, or display the form, so
1275 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1277 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1278 $output = $editpage->get_renderer('core');
1281 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1282 if (is_readable($formfile)) {
1283 require_once($formfile);
1284 $classname = 'block_' . $block->name() . '_edit_form';
1285 if (!class_exists($classname)) {
1286 $classname = 'block_edit_form';
1289 $classname = 'block_edit_form';
1292 $mform = new $classname($editpage->url
, $block, $this->page
);
1293 $mform->set_data($block->instance
);
1295 if ($mform->is_cancelled()) {
1296 redirect($this->page
->url
);
1298 } else if ($data = $mform->get_data()) {
1300 $bi->id
= $block->instance
->id
;
1302 // This may get overwritten by the special case handling below.
1303 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1304 $bi->showinsubcontexts
= (bool) $data->bui_contexts
;
1305 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1306 $bi->subpagepattern
= null;
1308 $bi->subpagepattern
= $data->bui_subpagepattern
;
1311 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1312 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1313 $parentcontext = get_context_instance_by_id($data->bui_parentcontextid
);
1315 // Updating stickiness and contexts. See MDL-21375 for details.
1316 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1318 // Explicitly set the default context
1319 $bi->parentcontextid
= $parentcontext->id
;
1321 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1323 // The interface here is a special case because the pagetype pattern is
1324 // totally derived from the context menu. Here are the excpetions. MDL-30340
1326 switch ($data->bui_contexts
) {
1327 case BUI_CONTEXTS_ENTIRE_SITE
:
1328 // The user wants to show the block across the entire site
1329 $bi->parentcontextid
= $systemcontext->id
;
1330 $bi->showinsubcontexts
= true;
1331 $bi->pagetypepattern
= '*';
1333 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1334 // The user wants the block shown on the front page and all subcontexts
1335 $bi->parentcontextid
= $frontpagecontext->id
;
1336 $bi->showinsubcontexts
= true;
1337 $bi->pagetypepattern
= '*';
1339 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1340 // The user want to show the front page on the frontpage only
1341 $bi->parentcontextid
= $frontpagecontext->id
;
1342 $bi->showinsubcontexts
= false;
1343 $bi->pagetypepattern
= 'site-index';
1344 // This is the only relevant page type anyway but we'll set it explicitly just
1345 // in case the front page grows site-index-* subpages of its own later
1351 $bits = explode('-', $bi->pagetypepattern
);
1352 // hacks for some contexts
1353 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1354 // For course context
1355 // is page type pattern is mod-*, change showinsubcontext to 1
1356 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1357 $bi->showinsubcontexts
= 1;
1359 $bi->showinsubcontexts
= 0;
1361 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1363 // subpagepattern should be null
1364 if ($bits[0] == 'user' or $bits[0] == 'my') {
1365 // we don't need subpagepattern in usercontext
1366 $bi->subpagepattern
= null;
1370 $bi->defaultregion
= $data->bui_defaultregion
;
1371 $bi->defaultweight
= $data->bui_defaultweight
;
1372 $DB->update_record('block_instances', $bi);
1374 if (!empty($block->config
)) {
1375 $config = clone($block->config
);
1377 $config = new stdClass
;
1379 foreach ($data as $configfield => $value) {
1380 if (strpos($configfield, 'config_') !== 0) {
1383 $field = substr($configfield, 7);
1384 $config->$field = $value;
1386 $block->instance_config_save($config);
1389 $bp->visible
= $data->bui_visible
;
1390 $bp->region
= $data->bui_region
;
1391 $bp->weight
= $data->bui_weight
;
1392 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1393 $data->bui_weight
!= $data->bui_defaultweight
;
1395 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1396 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1398 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1399 $bp->id
= $block->instance
->blockpositionid
;
1400 $DB->update_record('block_positions', $bp);
1402 } else if ($needbprecord) {
1403 $bp->blockinstanceid
= $block->instance
->id
;
1404 $bp->contextid
= $this->page
->context
->id
;
1405 $bp->pagetype
= $this->page
->pagetype
;
1406 if ($this->page
->subpage
) {
1407 $bp->subpage
= $this->page
->subpage
;
1411 $DB->insert_record('block_positions', $bp);
1414 redirect($this->page
->url
);
1417 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1418 $editpage->set_title($strheading);
1419 $editpage->set_heading($strheading);
1420 $bits = explode('-', $this->page
->pagetype
);
1421 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1422 // better navbar for tag pages
1423 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1424 $tag = tag_get('id', $this->page
->subpage
, '*');
1425 // tag search page doesn't have subpageid
1427 $editpage->navbar
->add($tag->name
, new moodle_url('/tag/index.php', array('id'=>$tag->id
)));
1430 $editpage->navbar
->add($block->get_title());
1431 $editpage->navbar
->add(get_string('configuration'));
1432 echo $output->header();
1433 echo $output->heading($strheading, 2);
1435 echo $output->footer();
1441 * Handle showing/processing the submission from the block editing form.
1442 * @return boolean true if the form was submitted and the new config saved. Does not
1443 * return if the editing form was displayed. False otherwise.
1445 public function process_url_move() {
1446 global $CFG, $DB, $PAGE;
1448 $blockid = optional_param('bui_moveid', null, PARAM_INTEGER
);
1455 $block = $this->find_instance($blockid);
1457 if (!$this->page
->user_can_edit_blocks()) {
1458 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1461 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1462 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1463 if (!$newregion ||
is_null($newweight)) {
1464 // Don't have a valid target position yet, must be just starting the move.
1465 $this->movingblock
= $blockid;
1466 $this->page
->ensure_param_not_in_url('bui_moveid');
1470 if (!$this->is_known_region($newregion)) {
1471 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1474 // Move this block. This may involve moving other nearby blocks.
1475 $blocks = $this->birecordsbyregion
[$newregion];
1477 $maxweight = self
::MAX_WEIGHT
;
1478 $minweight = -self
::MAX_WEIGHT
;
1480 // Initialise the used weights and spareweights array with the default values
1481 $spareweights = array();
1482 $usedweights = array();
1483 for ($i = $minweight; $i <= $maxweight; $i++
) {
1484 $spareweights[$i] = $i;
1485 $usedweights[$i] = array();
1488 // Check each block and sort out where we have used weights
1489 foreach ($blocks as $bi) {
1490 if ($bi->weight
> $maxweight) {
1491 // If this statement is true then the blocks weight is more than the
1492 // current maximum. To ensure that we can get the best block position
1493 // we will initialise elements within the usedweights and spareweights
1494 // arrays between the blocks weight (which will then be the new max) and
1496 $parseweight = $bi->weight
;
1497 while (!array_key_exists($parseweight, $usedweights)) {
1498 $usedweights[$parseweight] = array();
1499 $spareweights[$parseweight] = $parseweight;
1502 $maxweight = $bi->weight
;
1503 } else if ($bi->weight
< $minweight) {
1504 // As above except this time the blocks weight is LESS than the
1505 // the current minimum, so we will initialise the array from the
1506 // blocks weight (new minimum) to the current minimum
1507 $parseweight = $bi->weight
;
1508 while (!array_key_exists($parseweight, $usedweights)) {
1509 $usedweights[$parseweight] = array();
1510 $spareweights[$parseweight] = $parseweight;
1513 $minweight = $bi->weight
;
1515 if ($bi->id
!= $block->instance
->id
) {
1516 unset($spareweights[$bi->weight
]);
1517 $usedweights[$bi->weight
][] = $bi->id
;
1521 // First we find the nearest gap in the list of weights.
1522 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1524 foreach ($spareweights as $spareweight) {
1525 if (abs($newweight - $spareweight) < $bestdistance) {
1526 $bestdistance = abs($newweight - $spareweight);
1527 $bestgap = $spareweight;
1531 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1532 if (is_null($bestgap)) {
1533 $bestgap = self
::MAX_WEIGHT +
1;
1534 while (!empty($usedweights[$bestgap])) {
1539 // Now we know the gap we are aiming for, so move all the blocks along.
1540 if ($bestgap < $newweight) {
1541 $newweight = floor($newweight);
1542 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1543 foreach ($usedweights[$weight] as $biid) {
1544 $this->reposition_block($biid, $newregion, $weight - 1);
1547 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1549 $newweight = ceil($newweight);
1550 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1551 if (array_key_exists($weight, $usedweights)) {
1552 foreach ($usedweights[$weight] as $biid) {
1553 $this->reposition_block($biid, $newregion, $weight +
1);
1557 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1560 $this->page
->ensure_param_not_in_url('bui_moveid');
1561 $this->page
->ensure_param_not_in_url('bui_newregion');
1562 $this->page
->ensure_param_not_in_url('bui_newweight');
1567 * Turns the display of normal blocks either on or off.
1569 * @param bool $setting
1571 public function show_only_fake_blocks($setting = true) {
1572 $this->fakeblocksonly
= $setting;
1576 /// Helper functions for working with block classes ============================
1579 * Call a class method (one that does not require a block instance) on a block class.
1581 * @param string $blockname the name of the block.
1582 * @param string $method the method name.
1583 * @param array $param parameters to pass to the method.
1584 * @return mixed whatever the method returns.
1586 function block_method_result($blockname, $method, $param = NULL) {
1587 if(!block_load_class($blockname)) {
1590 return call_user_func(array('block_'.$blockname, $method), $param);
1594 * Creates a new instance of the specified block class.
1596 * @param string $blockname the name of the block.
1597 * @param $instance block_instances DB table row (optional).
1598 * @param moodle_page $page the page this block is appearing on.
1599 * @return block_base the requested block instance.
1601 function block_instance($blockname, $instance = NULL, $page = NULL) {
1602 if(!block_load_class($blockname)) {
1605 $classname = 'block_'.$blockname;
1606 $retval = new $classname;
1607 if($instance !== NULL) {
1608 if (is_null($page)) {
1612 $retval->_load_instance($instance, $page);
1618 * Load the block class for a particular type of block.
1620 * @param string $blockname the name of the block.
1621 * @return boolean success or failure.
1623 function block_load_class($blockname) {
1626 if(empty($blockname)) {
1630 $classname = 'block_'.$blockname;
1632 if(class_exists($classname)) {
1636 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1638 if (file_exists($blockpath)) {
1639 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1640 include_once($blockpath);
1642 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1646 return class_exists($classname);
1650 * Given a specific page type, return all the page type patterns that might
1653 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1654 * @return array an array of all the page type patterns that might match this page type.
1656 function matching_page_type_patterns($pagetype) {
1657 $patterns = array($pagetype);
1658 $bits = explode('-', $pagetype);
1659 if (count($bits) == 3 && $bits[0] == 'mod') {
1660 if ($bits[2] == 'view') {
1661 $patterns[] = 'mod-*-view';
1662 } else if ($bits[2] == 'index') {
1663 $patterns[] = 'mod-*-index';
1666 while (count($bits) > 0) {
1667 $patterns[] = implode('-', $bits) . '-*';
1675 * Given a specific page type, parent context and currect context, return all the page type patterns
1676 * that might be used by this block.
1678 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1679 * @param stdClass $parentcontext Block's parent context
1680 * @param stdClass $currentcontext Current context of block
1681 * @return array an array of all the page type patterns that might match this page type.
1683 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1686 $bits = explode('-', $pagetype);
1688 $core = get_core_subsystems();
1689 $plugins = get_plugin_types();
1691 //progressively strip pieces off the page type looking for a match
1692 $componentarray = null;
1693 for ($i = count($bits); $i > 0; $i--) {
1694 $possiblecomponentarray = array_slice($bits, 0, $i);
1695 $possiblecomponent = implode('', $possiblecomponentarray);
1697 // Check to see if the component is a core component
1698 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1699 $libfile = $CFG->dirroot
.'/'.$core[$possiblecomponent].'/lib.php';
1700 if (file_exists($libfile)) {
1701 require_once($libfile);
1702 $function = $possiblecomponent.'_page_type_list';
1703 if (function_exists($function)) {
1704 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1711 //check the plugin directory and look for a callback
1712 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1714 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1715 if (count($bits) > $i) {
1716 $pluginname = $bits[$i];
1717 $directory = get_plugin_directory($possiblecomponent, $pluginname);
1718 if (!empty($directory)){
1719 $libfile = $directory.'/lib.php';
1720 if (file_exists($libfile)) {
1721 require_once($libfile);
1722 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1723 if (!function_exists($function)) {
1724 $function = $pluginname.'_page_type_list';
1726 if (function_exists($function)) {
1727 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1735 //we'll only get to here if we still don't have any patterns
1736 //the plugin type may have a callback
1737 $directory = get_plugin_directory($possiblecomponent, null);
1738 if (!empty($directory)){
1739 $libfile = $directory.'/lib.php';
1740 if (file_exists($libfile)) {
1741 require_once($libfile);
1742 $function = $possiblecomponent.'_page_type_list';
1743 if (function_exists($function)) {
1744 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1753 if (empty($patterns)) {
1754 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1757 // Ensure that the * pattern is always available if editing block 'at distance', so
1758 // we always can 'bring back' it to the original context. MDL-30340
1759 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
1760 // TODO: We could change the string here, showing its 'bring back' meaning
1761 $patterns['*'] = get_string('page-x', 'pagetype');
1768 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1770 * @param string $pagetype
1771 * @param stdClass $parentcontext
1772 * @param stdClass $currentcontext
1775 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1776 // Generate page type patterns based on current page type if
1777 // callbacks haven't been defined
1778 $patterns = array($pagetype => $pagetype);
1779 $bits = explode('-', $pagetype);
1780 while (count($bits) > 0) {
1781 $pattern = implode('-', $bits) . '-*';
1782 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1783 // guessing page type description
1784 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1785 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1787 $patterns[$pattern] = $pattern;
1791 $patterns['*'] = get_string('page-x', 'pagetype');
1796 * Generates the page type list for the my moodle page
1798 * @param string $pagetype
1799 * @param stdClass $parentcontext
1800 * @param stdClass $currentcontext
1803 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1804 return array('my-index' => get_string('page-my-index', 'pagetype'));
1808 * Generates the page type list for a module by either locating and using the modules callback
1809 * or by generating a default list.
1811 * @param string $pagetype
1812 * @param stdClass $parentcontext
1813 * @param stdClass $currentcontext
1816 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1817 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1818 if (empty($patterns)) {
1819 // if modules don't have callbacks
1820 // generate two default page type patterns for modules only
1821 $bits = explode('-', $pagetype);
1822 $patterns = array($pagetype => $pagetype);
1823 if ($bits[2] == 'view') {
1824 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1825 } else if ($bits[2] == 'index') {
1826 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1831 /// Functions update the blocks if required by the request parameters ==========
1834 * Return a {@link block_contents} representing the add a new block UI, if
1835 * this user is allowed to see it.
1837 * @return block_contents an appropriate block_contents, or null if the user
1838 * cannot add any blocks here.
1840 function block_add_block_ui($page, $output) {
1841 global $CFG, $OUTPUT;
1842 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
1846 $bc = new block_contents();
1847 $bc->title
= get_string('addblock');
1848 $bc->add_class('block_adminblock');
1850 $missingblocks = $page->blocks
->get_addable_blocks();
1851 if (empty($missingblocks)) {
1852 $bc->content
= get_string('noblockstoaddhere');
1857 foreach ($missingblocks as $block) {
1858 $blockobject = block_instance($block->name
);
1859 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1860 $menu[$block->name
] = $blockobject->get_title();
1863 collatorlib
::asort($menu);
1865 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
1866 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1867 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1868 $bc->content
= $OUTPUT->render($select);
1872 // Functions that have been deprecated by block_manager =======================
1875 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1877 * This function returns an array with the IDs of any blocks that you can add to your page.
1878 * Parameters are passed by reference for speed; they are not modified at all.
1880 * @param $page the page object.
1881 * @param $blockmanager Not used.
1882 * @return array of block type ids.
1884 function blocks_get_missing(&$page, &$blockmanager) {
1885 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER
);
1886 $blocks = $page->blocks
->get_addable_blocks();
1888 foreach ($blocks as $block) {
1889 $ids[] = $block->id
;
1895 * Actually delete from the database any blocks that are currently on this page,
1896 * but which should not be there according to blocks_name_allowed_in_format.
1898 * @todo Write/Fix this function. Currently returns immediately
1901 function blocks_remove_inappropriate($course) {
1905 $blockmanager = blocks_get_by_page($page);
1907 if (empty($blockmanager)) {
1911 if (($pageformat = $page->pagetype) == NULL) {
1915 foreach($blockmanager as $region) {
1916 foreach($region as $instance) {
1917 $block = blocks_get_record($instance->blockid);
1918 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1919 blocks_delete_instance($instance->instance);
1926 * Check that a given name is in a permittable format
1928 * @param string $name
1929 * @param string $pageformat
1932 function blocks_name_allowed_in_format($name, $pageformat) {
1935 if (!$bi = block_instance($name)) {
1939 $formats = $bi->applicable_formats();
1943 foreach ($formats as $format => $allowed) {
1944 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1945 $depth = substr_count($format, '-');
1946 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1951 if ($accept === NULL) {
1952 $accept = !empty($formats['all']);
1958 * Delete a block, and associated data.
1960 * @param object $instance a row from the block_instances table
1961 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
1962 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
1964 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
1967 if ($block = block_instance($instance->blockname
, $instance)) {
1968 $block->instance_delete();
1970 delete_context(CONTEXT_BLOCK
, $instance->id
);
1972 if (!$skipblockstables) {
1973 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
1974 $DB->delete_records('block_instances', array('id' => $instance->id
));
1975 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
1980 * Delete all the blocks that belong to a particular context.
1982 * @param int $contextid the context id.
1984 function blocks_delete_all_for_context($contextid) {
1986 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
1987 foreach ($instances as $instance) {
1988 blocks_delete_instance($instance, true);
1990 $instances->close();
1991 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
1992 $DB->delete_records('block_positions', array('contextid' => $contextid));
1996 * Set a block to be visible or hidden on a particular page.
1998 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
1999 * block_positions table as return by block_manager.
2000 * @param moodle_page $page the back to set the visibility with respect to.
2001 * @param integer $newvisibility 1 for visible, 0 for hidden.
2003 function blocks_set_visibility($instance, $page, $newvisibility) {
2005 if (!empty($instance->blockpositionid
)) {
2006 // Already have local information on this page.
2007 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
2011 // Create a new block_positions record.
2013 $bp->blockinstanceid
= $instance->id
;
2014 $bp->contextid
= $page->context
->id
;
2015 $bp->pagetype
= $page->pagetype
;
2016 if ($page->subpage
) {
2017 $bp->subpage
= $page->subpage
;
2019 $bp->visible
= $newvisibility;
2020 $bp->region
= $instance->defaultregion
;
2021 $bp->weight
= $instance->defaultweight
;
2022 $DB->insert_record('block_positions', $bp);
2026 * @deprecated since 2.0
2027 * Delete all the blocks from a particular page.
2029 * @param string $pagetype the page type.
2030 * @param integer $pageid the page id.
2031 * @return bool success or failure.
2033 function blocks_delete_all_on_page($pagetype, $pageid) {
2036 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
2037 'This function cannot work any more. Doing nothing. ' .
2038 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER
);
2043 * Dispite what this function is called, it seems to be mostly used to populate
2044 * the default blocks when a new course (or whatever) is created.
2046 * @deprecated since 2.0
2048 * @param object $page the page to add default blocks to.
2049 * @return boolean success or failure.
2051 function blocks_repopulate_page($page) {
2054 debugging('Call to deprecated function blocks_repopulate_page. ' .
2055 'Use a more specific method like blocks_add_default_course_blocks, ' .
2056 'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER
);
2058 /// If the site override has been defined, it is the only valid one.
2059 if (!empty($CFG->defaultblocks_override
)) {
2060 $blocknames = $CFG->defaultblocks_override
;
2062 $blocknames = $page->blocks_get_default();
2065 $blocks = blocks_parse_default_blocks_list($blocknames);
2066 $page->blocks
->add_blocks($blocks);
2072 * Get the block record for a particular blockid - that is, a particular type os block.
2074 * @param $int blockid block type id. If null, an array of all block types is returned.
2075 * @param bool $notusedanymore No longer used.
2076 * @return array|object row from block table, or all rows.
2078 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2080 $blocks = $PAGE->blocks
->get_installed_blocks();
2081 if ($blockid === NULL) {
2083 } else if (isset($blocks[$blockid])) {
2084 return $blocks[$blockid];
2091 * Find a given block by its blockid within a provide array
2093 * @param int $blockid
2094 * @param array $blocksarray
2095 * @return bool|object Instance if found else false
2097 function blocks_find_block($blockid, $blocksarray) {
2098 if (empty($blocksarray)) {
2101 foreach($blocksarray as $blockgroup) {
2102 if (empty($blockgroup)) {
2105 foreach($blockgroup as $instance) {
2106 if($instance->blockid
== $blockid) {
2114 // Functions for programatically adding default blocks to pages ================
2117 * Parse a list of default blocks. See config-dist for a description of the format.
2119 * @param string $blocksstr
2122 function blocks_parse_default_blocks_list($blocksstr) {
2124 $bits = explode(':', $blocksstr);
2125 if (!empty($bits)) {
2126 $leftbits = trim(array_shift($bits));
2127 if ($leftbits != '') {
2128 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2131 if (!empty($bits)) {
2132 $rightbits =trim(array_shift($bits));
2133 if ($rightbits != '') {
2134 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2141 * @return array the blocks that should be added to the site course by default.
2143 function blocks_get_default_site_course_blocks() {
2146 if (!empty($CFG->defaultblocks_site
)) {
2147 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2150 BLOCK_POS_LEFT
=> array('site_main_menu'),
2151 BLOCK_POS_RIGHT
=> array('course_summary', 'calendar_month')
2157 * Add the default blocks to a course.
2159 * @param object $course a course object.
2161 function blocks_add_default_course_blocks($course) {
2164 if (!empty($CFG->defaultblocks_override
)) {
2165 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2167 } else if ($course->id
== SITEID
) {
2168 $blocknames = blocks_get_default_site_course_blocks();
2171 $defaultblocks = 'defaultblocks_' . $course->format
;
2172 if (!empty($CFG->$defaultblocks)) {
2173 $blocknames = blocks_parse_default_blocks_list($CFG->$defaultblocks);
2176 $formatconfig = $CFG->dirroot
.'/course/format/'.$course->format
.'/config.php';
2177 $format = array(); // initialize array in external file
2178 if (is_readable($formatconfig)) {
2179 include($formatconfig);
2181 if (!empty($format['defaultblocks'])) {
2182 $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']);
2184 } else if (!empty($CFG->defaultblocks
)){
2185 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks
);
2188 $blocknames = array(
2189 BLOCK_POS_LEFT
=> array(),
2190 BLOCK_POS_RIGHT
=> array('search_forums', 'news_items', 'calendar_upcoming', 'recent_activity')
2196 if ($course->id
== SITEID
) {
2197 $pagetypepattern = 'site-index';
2199 $pagetypepattern = 'course-view-*';
2201 $page = new moodle_page();
2202 $page->set_course($course);
2203 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2207 * Add the default system-context blocks. E.g. the admin tree.
2209 function blocks_add_default_system_blocks() {
2212 $page = new moodle_page();
2213 $page->set_context(get_context_instance(CONTEXT_SYSTEM
));
2214 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('navigation', 'settings')), '*', null, true);
2215 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2217 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2218 $subpagepattern = $defaultmypage->id
;
2220 $subpagepattern = null;
2223 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);