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 $unaddableblocks = self
::get_undeletable_block_types();
228 $pageformat = $this->page
->pagetype
;
229 foreach($allblocks as $block) {
230 if (!$bi = block_instance($block->name
)) {
233 if ($block->visible
&& !in_array($block->name
, $unaddableblocks) &&
234 ($bi->instance_allow_multiple() ||
!$this->is_block_present($block->name
)) &&
235 blocks_name_allowed_in_format($block->name
, $pageformat) &&
236 $bi->user_can_addto($this->page
)) {
237 $this->addableblocks
[$block->name
] = $block;
241 return $this->addableblocks
;
245 * Given a block name, find out of any of them are currently present in the page
247 * @param string $blockname - the basic name of a block (eg "navigation")
248 * @return boolean - is there one of these blocks in the current page?
250 public function is_block_present($blockname) {
251 if (empty($this->blockinstances
)) {
255 foreach ($this->blockinstances
as $region) {
256 foreach ($region as $instance) {
257 if (empty($instance->instance
->blockname
)) {
260 if ($instance->instance
->blockname
== $blockname) {
269 * Find out if a block type is known by the system
271 * @param string $blockname the name of the type of block.
272 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
273 * @return boolean true if this block in installed.
275 public function is_known_block_type($blockname, $includeinvisible = false) {
276 $blocks = $this->get_installed_blocks();
277 foreach ($blocks as $block) {
278 if ($block->name
== $blockname && ($includeinvisible ||
$block->visible
)) {
286 * Find out if a region exists on a page
288 * @param string $region a region name
289 * @return boolean true if this region exists on this page.
291 public function is_known_region($region) {
292 return array_key_exists($region, $this->regions
);
296 * Get an array of all blocks within a given region
298 * @param string $region a block region that exists on this page.
299 * @return array of block instances.
301 public function get_blocks_for_region($region) {
302 $this->check_is_loaded();
303 $this->ensure_instances_exist($region);
304 return $this->blockinstances
[$region];
308 * Returns an array of block content objects that exist in a region
310 * @param string $region a block region that exists on this page.
311 * @return array of block block_contents objects for all the blocks in a region.
313 public function get_content_for_region($region, $output) {
314 $this->check_is_loaded();
315 $this->ensure_content_created($region, $output);
316 return $this->visibleblockcontent
[$region];
320 * Helper method used by get_content_for_region.
321 * @param string $region region name
322 * @param float $weight weight. May be fractional, since you may want to move a block
323 * between ones with weight 2 and 3, say ($weight would be 2.5).
324 * @return string URL for moving block $this->movingblock to this position.
326 protected function get_move_target_url($region, $weight) {
327 return new moodle_url($this->page
->url
, array('bui_moveid' => $this->movingblock
,
328 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
332 * Determine whether a region contains anything. (Either any real blocks, or
333 * the add new block UI.)
335 * (You may wonder why the $output parameter is required. Unfortunately,
336 * because of the way that blocks work, the only reliable way to find out
337 * if a block will be visible is to get the content for output, and to
338 * get the content, you need a renderer. Fortunately, this is not a
339 * performance problem, because we cache the output that is generated, and
340 * in almost every case where we call region_has_content, we are about to
341 * output the blocks anyway, so we are not doing wasted effort.)
343 * @param string $region a block region that exists on this page.
344 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
345 * @return boolean Whether there is anything in this region.
347 public function region_has_content($region, $output) {
349 if (!$this->is_known_region($region)) {
352 $this->check_is_loaded();
353 $this->ensure_content_created($region, $output);
354 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
355 // Mark Nielsen's patch - part 1
356 if ($this->page
->user_is_editing() && $this->page
->user_can_edit_blocks() && $this->movingblock
) {
357 // If editing is on, we need all the block regions visible, for the
361 return !empty($this->visibleblockcontent
[$region]) ||
!empty($this->extracontent
[$region]);
365 * Get an array of all of the installed blocks.
367 * @return array contents of the block table.
369 public function get_installed_blocks() {
371 if (is_null($this->allblocks
)) {
372 $this->allblocks
= $DB->get_records('block');
374 return $this->allblocks
;
378 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
380 public static function get_undeletable_block_types() {
383 if (!isset($CFG->undeletableblocktypes
) ||
(!is_array($CFG->undeletableblocktypes
) && !is_string($CFG->undeletableblocktypes
))) {
384 return array('navigation','settings');
385 } else if (is_string($CFG->undeletableblocktypes
)) {
386 return explode(',', $CFG->undeletableblocktypes
);
388 return $CFG->undeletableblocktypes
;
392 /// Setter methods =============================================================
395 * Add a region to a page
397 * @param string $region add a named region where blocks may appear on the
398 * current page. This is an internal name, like 'side-pre', not a string to
401 public function add_region($region) {
402 $this->check_not_yet_loaded();
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) {
413 foreach ($regions as $region) {
414 $this->add_region($region);
419 * Set the default region for new blocks on the page
421 * @param string $defaultregion the internal names of the region where new
422 * blocks should be added by default, and where any blocks from an
423 * unrecognised region are shown.
425 public function set_default_region($defaultregion) {
426 $this->check_not_yet_loaded();
427 if ($defaultregion) {
428 $this->check_region_is_known($defaultregion);
430 $this->defaultregion
= $defaultregion;
434 * Add something that looks like a block, but which isn't an actual block_instance,
437 * @param block_contents $bc the content of the block-like thing.
438 * @param string $region a block region that exists on this page.
440 public function add_fake_block($bc, $region) {
441 $this->page
->initialise_theme_and_output();
442 if (!$this->is_known_region($region)) {
443 $region = $this->get_default_region();
445 if (array_key_exists($region, $this->visibleblockcontent
)) {
446 throw new coding_exception('block_manager has already prepared the blocks in region ' .
447 $region . 'for output. It is too late to add a fake block.');
449 if (!isset($bc->attributes
['data-block'])) {
450 $bc->attributes
['data-block'] = '_fake';
452 $this->extracontent
[$region][] = $bc;
456 * When the block_manager class was created, the {@link add_fake_block()}
457 * was called add_pretend_block, which is inconsisted with
458 * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
459 * was renamed to add_fake_block. Please update your code.
460 * @param block_contents $bc the content of the block-like thing.
461 * @param string $region a block region that exists on this page.
463 public function add_pretend_block($bc, $region) {
464 debugging(DEBUG_DEVELOPER
, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
465 $this->add_fake_block($bc, $region);
469 * Checks to see whether all of the blocks within the given region are docked
471 * @see region_uses_dock
472 * @param string $region
473 * @return bool True if all of the blocks within that region are docked
475 public function region_completely_docked($region, $output) {
477 // If theme doesn't allow docking or allowblockstodock is not set, then return.
478 if (!$this->page
->theme
->enable_dock ||
empty($CFG->allowblockstodock
)) {
482 // Do not dock the region when the user attemps to move a block.
483 if ($this->movingblock
) {
487 $this->check_is_loaded();
488 $this->ensure_content_created($region, $output);
489 foreach($this->visibleblockcontent
[$region] as $instance) {
490 if (!empty($instance->content
) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
498 * Checks to see whether any of the blocks within the given regions are docked
500 * @see region_completely_docked
501 * @param array|string $regions array of regions (or single region)
502 * @return bool True if any of the blocks within that region are docked
504 public function region_uses_dock($regions, $output) {
505 if (!$this->page
->theme
->enable_dock
) {
508 $this->check_is_loaded();
509 foreach((array)$regions as $region) {
510 $this->ensure_content_created($region, $output);
511 foreach($this->visibleblockcontent
[$region] as $instance) {
512 if(!empty($instance->content
) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
520 /// Actions ====================================================================
523 * This method actually loads the blocks for our page from the database.
525 * @param boolean|null $includeinvisible
526 * null (default) - load hidden blocks if $this->page->user_is_editing();
527 * true - load hidden blocks.
528 * false - don't load hidden blocks.
530 public function load_blocks($includeinvisible = null) {
533 if (!is_null($this->birecordsbyregion
)) {
538 if ($CFG->version
< 2009050619) {
539 // Upgrade/install not complete. Don't try too show any blocks.
540 $this->birecordsbyregion
= array();
544 // Ensure we have been initialised.
545 if (is_null($this->defaultregion
)) {
546 $this->page
->initialise_theme_and_output();
547 // If there are still no block regions, then there are no blocks on this page.
548 if (empty($this->regions
)) {
549 $this->birecordsbyregion
= array();
554 // Check if we need to load normal blocks
555 if ($this->fakeblocksonly
) {
556 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
560 if (is_null($includeinvisible)) {
561 $includeinvisible = $this->page
->user_is_editing();
563 if ($includeinvisible) {
566 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
569 $context = $this->page
->context
;
570 $contexttest = 'bi.parentcontextid = :contextid2';
571 $parentcontextparams = array();
572 $parentcontextids = $context->get_parent_context_ids();
573 if ($parentcontextids) {
574 list($parentcontexttest, $parentcontextparams) =
575 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
, 'parentcontext');
576 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
579 $pagetypepatterns = matching_page_type_patterns($this->page
->pagetype
);
580 list($pagetypepatterntest, $pagetypepatternparams) =
581 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
, 'pagetypepatterntest');
583 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
584 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
587 'contextlevel' => CONTEXT_BLOCK
,
588 'subpage1' => $this->page
->subpage
,
589 'subpage2' => $this->page
->subpage
,
590 'contextid1' => $context->id
,
591 'contextid2' => $context->id
,
592 'pagetype' => $this->page
->pagetype
,
594 if ($this->page
->subpage
=== '') {
595 $params['subpage1'] = '';
596 $params['subpage2'] = '';
600 bp.id AS blockpositionid,
603 bi.showinsubcontexts,
608 COALESCE(bp.visible, 1) AS visible,
609 COALESCE(bp.region, bi.defaultregion) AS region,
610 COALESCE(bp.weight, bi.defaultweight) AS weight,
614 FROM {block_instances} bi
615 JOIN {block} b ON bi.blockname = b.name
616 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
617 AND bp.contextid = :contextid1
618 AND bp.pagetype = :pagetype
619 AND bp.subpage = :subpage1
624 AND bi.pagetypepattern $pagetypepatterntest
625 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
630 COALESCE(bp.region, bi.defaultregion),
631 COALESCE(bp.weight, bi.defaultweight),
633 $blockinstances = $DB->get_recordset_sql($sql, $params +
$parentcontextparams +
$pagetypepatternparams);
635 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
637 foreach ($blockinstances as $bi) {
638 context_helper
::preload_from_record($bi);
639 if ($this->is_known_region($bi->region
)) {
640 $this->birecordsbyregion
[$bi->region
][] = $bi;
646 // Pages don't necessarily have a defaultregion. The one time this can
647 // happen is when there are no theme block regions, but the script itself
648 // has a block region in the main content area.
649 if (!empty($this->defaultregion
)) {
650 $this->birecordsbyregion
[$this->defaultregion
] =
651 array_merge($this->birecordsbyregion
[$this->defaultregion
], $unknown);
656 * Add a block to the current page, or related pages. The block is added to
657 * context $this->page->contextid. If $pagetypepattern $subpagepattern
659 * @param string $blockname The type of block to add.
660 * @param string $region the block region on this page to add the block to.
661 * @param integer $weight determines the order where this block appears in the region.
662 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
663 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
664 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
666 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
668 // Allow invisible blocks because this is used when adding default page blocks, which
669 // might include invisible ones if the user makes some default blocks invisible
670 $this->check_known_block_type($blockname, true);
671 $this->check_region_is_known($region);
673 if (empty($pagetypepattern)) {
674 $pagetypepattern = $this->page
->pagetype
;
677 $blockinstance = new stdClass
;
678 $blockinstance->blockname
= $blockname;
679 $blockinstance->parentcontextid
= $this->page
->context
->id
;
680 $blockinstance->showinsubcontexts
= !empty($showinsubcontexts);
681 $blockinstance->pagetypepattern
= $pagetypepattern;
682 $blockinstance->subpagepattern
= $subpagepattern;
683 $blockinstance->defaultregion
= $region;
684 $blockinstance->defaultweight
= $weight;
685 $blockinstance->configdata
= '';
686 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
688 // Ensure the block context is created.
689 context_block
::instance($blockinstance->id
);
691 // If the new instance was created, allow it to do additional setup
692 if ($block = block_instance($blockname, $blockinstance)) {
693 $block->instance_create();
697 public function add_block_at_end_of_default_region($blockname) {
698 $defaulregion = $this->get_default_region();
700 $lastcurrentblock = end($this->birecordsbyregion
[$defaulregion]);
701 if ($lastcurrentblock) {
702 $weight = $lastcurrentblock->weight +
1;
707 if ($this->page
->subpage
) {
708 $subpage = $this->page
->subpage
;
713 // Special case. Course view page type include the course format, but we
714 // want to add the block non-format-specifically.
715 $pagetypepattern = $this->page
->pagetype
;
716 if (strpos($pagetypepattern, 'course-view') === 0) {
717 $pagetypepattern = 'course-view-*';
720 // We should end using this for ALL the blocks, making always the 1st option
721 // the default one to be used. Until then, this is one hack to avoid the
722 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
723 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
724 // (the FIRST $pagetypepattern will be set)
726 // We are applying it to all blocks created in mod pages for now and only if the
727 // default pagetype is not one of the available options
728 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
729 $pagetypelist = generate_page_type_patterns($this->page
->pagetype
, null, $this->page
->context
);
730 // Only go for the first if the pagetype is not a valid option
731 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
732 $pagetypepattern = key($pagetypelist);
735 // Surely other pages like course-report will need this too, they just are not important
736 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
738 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
742 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
744 * @param array $blocks array with array keys the region names, and values an array of block names.
745 * @param string $pagetypepattern optional. Passed to @see add_block()
746 * @param string $subpagepattern optional. Passed to @see add_block()
748 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
749 $this->add_regions(array_keys($blocks));
750 foreach ($blocks as $region => $regionblocks) {
752 foreach ($regionblocks as $blockname) {
753 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
760 * Move a block to a new position on this page.
762 * If this block cannot appear on any other pages, then we change defaultposition/weight
763 * in the block_instances table. Otherwise we just set the position on this page.
765 * @param $blockinstanceid the block instance id.
766 * @param $newregion the new region name.
767 * @param $newweight the new weight.
769 public function reposition_block($blockinstanceid, $newregion, $newweight) {
772 $this->check_region_is_known($newregion);
773 $inst = $this->find_instance($blockinstanceid);
775 $bi = $inst->instance
;
776 if ($bi->weight
== $bi->defaultweight
&& $bi->region
== $bi->defaultregion
&&
777 !$bi->showinsubcontexts
&& strpos($bi->pagetypepattern
, '*') === false &&
778 (!$this->page
->subpage ||
$bi->subpagepattern
)) {
780 // Set default position
781 $newbi = new stdClass
;
782 $newbi->id
= $bi->id
;
783 $newbi->defaultregion
= $newregion;
784 $newbi->defaultweight
= $newweight;
785 $DB->update_record('block_instances', $newbi);
787 if ($bi->blockpositionid
) {
789 $bp->id
= $bi->blockpositionid
;
790 $bp->region
= $newregion;
791 $bp->weight
= $newweight;
792 $DB->update_record('block_positions', $bp);
796 // Just set position on this page.
798 $bp->region
= $newregion;
799 $bp->weight
= $newweight;
801 if ($bi->blockpositionid
) {
802 $bp->id
= $bi->blockpositionid
;
803 $DB->update_record('block_positions', $bp);
806 $bp->blockinstanceid
= $bi->id
;
807 $bp->contextid
= $this->page
->context
->id
;
808 $bp->pagetype
= $this->page
->pagetype
;
809 if ($this->page
->subpage
) {
810 $bp->subpage
= $this->page
->subpage
;
814 $bp->visible
= $bi->visible
;
815 $DB->insert_record('block_positions', $bp);
821 * Find a given block by its instance id
823 * @param integer $instanceid
826 public function find_instance($instanceid) {
827 foreach ($this->regions
as $region => $notused) {
828 $this->ensure_instances_exist($region);
829 foreach($this->blockinstances
[$region] as $instance) {
830 if ($instance->instance
->id
== $instanceid) {
835 throw new block_not_on_page_exception($instanceid, $this->page
);
838 /// Inner workings =============================================================
841 * Check whether the page blocks have been loaded yet
843 * @return void Throws coding exception if already loaded
845 protected function check_not_yet_loaded() {
846 if (!is_null($this->birecordsbyregion
)) {
847 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.');
852 * Check whether the page blocks have been loaded yet
854 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
856 * @return void Throws coding exception if already loaded
858 protected function check_is_loaded() {
859 if (is_null($this->birecordsbyregion
)) {
860 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
865 * Check if a block type is known and usable
867 * @param string $blockname The block type name to search for
868 * @param bool $includeinvisible Include disabled block types in the initial pass
869 * @return void Coding Exception thrown if unknown or not enabled
871 protected function check_known_block_type($blockname, $includeinvisible = false) {
872 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
873 if ($this->is_known_block_type($blockname, true)) {
874 throw new coding_exception('Unknown block type ' . $blockname);
876 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
882 * Check if a region is known by its name
884 * @param string $region
885 * @return void Coding Exception thrown if the region is not known
887 protected function check_region_is_known($region) {
888 if (!$this->is_known_region($region)) {
889 throw new coding_exception('Trying to reference an unknown block region ' . $region);
894 * Returns an array of region names as keys and nested arrays for values
896 * @return array an array where the array keys are the region names, and the array
897 * values are empty arrays.
899 protected function prepare_per_region_arrays() {
901 foreach ($this->regions
as $region => $notused) {
902 $result[$region] = array();
908 * Create a set of new block instance from a record array
910 * @param array $birecords An array of block instance records
911 * @return array An array of instantiated block_instance objects
913 protected function create_block_instances($birecords) {
915 foreach ($birecords as $record) {
916 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
917 $results[] = $blockobject;
924 * Create all the block instances for all the blocks that were loaded by
925 * load_blocks. This is used, for example, to ensure that all blocks get a
926 * chance to initialise themselves via the {@link block_base::specialize()}
927 * method, before any output is done.
929 public function create_all_block_instances() {
930 foreach ($this->get_regions() as $region) {
931 $this->ensure_instances_exist($region);
936 * Return an array of content objects from a set of block instances
938 * @param array $instances An array of block instances
939 * @param renderer_base The renderer to use.
940 * @param string $region the region name.
941 * @return array An array of block_content (and possibly block_move_target) objects.
943 protected function create_block_contents($instances, $output, $region) {
948 if ($this->movingblock
) {
949 $first = reset($instances);
951 $lastweight = $first->instance
->weight
- 2;
955 foreach ($instances as $instance) {
956 $content = $instance->get_content_for_output($output);
957 if (empty($content)) {
961 if ($this->movingblock
&& $lastweight != $instance->instance
->weight
&&
962 $content->blockinstanceid
!= $this->movingblock
&& $lastblock != $this->movingblock
) {
963 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight +
$instance->instance
->weight
)/2));
966 if ($content->blockinstanceid
== $this->movingblock
) {
967 $content->add_class('beingmoved');
968 $content->annotation
.= get_string('movingthisblockcancel', 'block',
969 html_writer
::link($this->page
->url
, get_string('cancel')));
972 $results[] = $content;
973 $lastweight = $instance->instance
->weight
;
974 $lastblock = $instance->instance
->id
;
977 if ($this->movingblock
&& $lastblock != $this->movingblock
) {
978 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight +
1));
984 * Ensure block instances exist for a given region
986 * @param string $region Check for bi's with the instance with this name
988 protected function ensure_instances_exist($region) {
989 $this->check_region_is_known($region);
990 if (!array_key_exists($region, $this->blockinstances
)) {
991 $this->blockinstances
[$region] =
992 $this->create_block_instances($this->birecordsbyregion
[$region]);
997 * Ensure that there is some content within the given region
999 * @param string $region The name of the region to check
1001 public function ensure_content_created($region, $output) {
1002 $this->ensure_instances_exist($region);
1003 if (!array_key_exists($region, $this->visibleblockcontent
)) {
1004 $contents = array();
1005 if (array_key_exists($region, $this->extracontent
)) {
1006 $contents = $this->extracontent
[$region];
1008 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances
[$region], $output, $region));
1009 if ($region == $this->defaultregion
) {
1010 $addblockui = block_add_block_ui($this->page
, $output);
1012 $contents[] = $addblockui;
1015 $this->visibleblockcontent
[$region] = $contents;
1019 /// Process actions from the URL ===============================================
1022 * Get the appropriate list of editing icons for a block. This is used
1023 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1025 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1026 * @return an array in the format for {@link block_contents::$controls}
1028 public function edit_controls($block) {
1031 $controls = array();
1032 $actionurl = $this->page
->url
->out(false, array('sesskey'=> sesskey()));
1033 $blocktitle = $block->title
;
1034 if (empty($blocktitle)) {
1035 $blocktitle = $block->arialabel
;
1038 if ($this->page
->user_can_edit_blocks()) {
1040 $str = new lang_string('moveblock', 'block', $blocktitle);
1041 $controls[] = new action_menu_link_primary(
1042 new moodle_url($actionurl, array('bui_moveid' => $block->instance
->id
)),
1043 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1045 array('class' => 'editing_move')
1050 if ($this->page
->user_can_edit_blocks() ||
$block->user_can_edit()) {
1051 // Edit config icon - always show - needed for positioning UI.
1052 $str = new lang_string('configureblock', 'block', $blocktitle);
1053 $controls[] = new action_menu_link_secondary(
1054 new moodle_url($actionurl, array('bui_editid' => $block->instance
->id
)),
1055 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1057 array('class' => 'editing_edit')
1062 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1064 if ($block->instance
->visible
) {
1065 $str = new lang_string('hideblock', 'block', $blocktitle);
1066 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance
->id
));
1067 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1068 $attributes = array('class' => 'editing_hide');
1070 $str = new lang_string('showblock', 'block', $blocktitle);
1071 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance
->id
));
1072 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1073 $attributes = array('class' => 'editing_show');
1075 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1078 // Assign roles icon.
1079 if (has_capability('moodle/role:assign', $block->context
)) {
1080 //TODO: please note it is sloppy to pass urls through page parameters!!
1081 // it is shortened because some web servers (e.g. IIS by default) give
1082 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1083 $return = $this->page
->url
->out(false);
1084 $return = str_replace($CFG->wwwroot
. '/', '', $return);
1086 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context
->id
,
1087 'returnurl'=>$return));
1089 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1090 $controls[] = new action_menu_link_secondary(
1092 new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1094 array('class' => 'editing_roles')
1098 if ($this->user_can_delete_block($block)) {
1100 $str = new lang_string('deleteblock', 'block', $blocktitle);
1101 $controls[] = new action_menu_link_secondary(
1102 new moodle_url($actionurl, array('bui_deleteid' => $block->instance
->id
)),
1103 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1105 array('class' => 'editing_delete')
1113 * @param block_base $block a block that appears on this page.
1114 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1116 protected function user_can_delete_block($block) {
1117 return $this->page
->user_can_edit_blocks() && $block->user_can_edit() &&
1118 $block->user_can_addto($this->page
) &&
1119 !in_array($block->instance
->blockname
, self
::get_undeletable_block_types());
1123 * Process any block actions that were specified in the URL.
1125 * @return boolean true if anything was done. False if not.
1127 public function process_url_actions() {
1128 if (!$this->page
->user_is_editing()) {
1131 return $this->process_url_add() ||
$this->process_url_delete() ||
1132 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1133 $this->process_url_move();
1137 * Handle adding a block.
1138 * @return boolean true if anything was done. False if not.
1140 public function process_url_add() {
1141 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1148 if (!$this->page
->user_can_edit_blocks()) {
1149 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1152 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1153 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1156 $this->add_block_at_end_of_default_region($blocktype);
1158 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1159 $this->page
->ensure_param_not_in_url('bui_addblock');
1165 * Handle deleting a block.
1166 * @return boolean true if anything was done. False if not.
1168 public function process_url_delete() {
1169 global $CFG, $PAGE, $OUTPUT;
1171 $blockid = optional_param('bui_deleteid', null, PARAM_INT
);
1172 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT
);
1179 $block = $this->page
->blocks
->find_instance($blockid);
1180 if (!$this->user_can_delete_block($block)) {
1181 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1184 if (!$confirmdelete) {
1185 $deletepage = new moodle_page();
1186 $deletepage->set_pagelayout('admin');
1187 $deletepage->set_course($this->page
->course
);
1188 $deletepage->set_context($this->page
->context
);
1189 if ($this->page
->cm
) {
1190 $deletepage->set_cm($this->page
->cm
);
1193 $deleteurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1194 $deleteurlparams = $this->page
->url
->params();
1195 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1196 $deletepage->set_block_actions_done();
1197 // At this point we are either going to redirect, or display the form, so
1198 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1199 $PAGE = $deletepage;
1200 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1201 $output = $deletepage->get_renderer('core');
1205 $blocktitle = $block->get_title();
1206 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1207 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1209 // If the block is being shown in sub contexts display a warning.
1210 if ($block->instance
->showinsubcontexts
== 1) {
1211 $parentcontext = context
::instance_by_id($block->instance
->parentcontextid
);
1212 $systemcontext = context_system
::instance();
1213 $messagestring = new stdClass();
1214 $messagestring->location
= $parentcontext->get_context_name();
1216 // Checking for blocks that may have visibility on the front page and pages added on that.
1217 if ($parentcontext->id
!= $systemcontext->id
&& is_inside_frontpage($parentcontext)) {
1218 $messagestring->pagetype
= get_string('showonfrontpageandsubs', 'block');
1220 $pagetypes = generate_page_type_patterns($this->page
->pagetype
, $parentcontext);
1221 $messagestring->pagetype
= $block->instance
->pagetypepattern
;
1222 if (isset($pagetypes[$block->instance
->pagetypepattern
])) {
1223 $messagestring->pagetype
= $pagetypes[$block->instance
->pagetypepattern
];
1227 $message = get_string('deleteblockwarning', 'block', $messagestring);
1230 $PAGE->navbar
->add($strdeletecheck);
1231 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1232 $PAGE->set_heading($site->fullname
);
1233 echo $OUTPUT->header();
1234 $confirmurl = new moodle_url($deletepage->url
, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance
->id
, 'bui_confirm' => 1));
1235 $cancelurl = new moodle_url($deletepage->url
);
1236 $yesbutton = new single_button($confirmurl, get_string('yes'));
1237 $nobutton = new single_button($cancelurl, get_string('no'));
1238 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1239 echo $OUTPUT->footer();
1240 // Make sure that nothing else happens after we have displayed this form.
1243 blocks_delete_instance($block->instance
);
1244 // bui_deleteid and bui_confirm should not be in the PAGE url.
1245 $this->page
->ensure_param_not_in_url('bui_deleteid');
1246 $this->page
->ensure_param_not_in_url('bui_confirm');
1252 * Handle showing or hiding a block.
1253 * @return boolean true if anything was done. False if not.
1255 public function process_url_show_hide() {
1256 if ($blockid = optional_param('bui_hideid', null, PARAM_INT
)) {
1258 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT
)) {
1266 $block = $this->page
->blocks
->find_instance($blockid);
1268 if (!$this->page
->user_can_edit_blocks()) {
1269 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1270 } else if (!$block->instance_can_be_hidden()) {
1274 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1276 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1277 $this->page
->ensure_param_not_in_url('bui_hideid');
1278 $this->page
->ensure_param_not_in_url('bui_showid');
1284 * Handle showing/processing the submission from the block editing form.
1285 * @return boolean true if the form was submitted and the new config saved. Does not
1286 * return if the editing form was displayed. False otherwise.
1288 public function process_url_edit() {
1289 global $CFG, $DB, $PAGE, $OUTPUT;
1291 $blockid = optional_param('bui_editid', null, PARAM_INT
);
1297 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1299 $block = $this->find_instance($blockid);
1301 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1302 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1305 $editpage = new moodle_page();
1306 $editpage->set_pagelayout('admin');
1307 $editpage->set_course($this->page
->course
);
1308 //$editpage->set_context($block->context);
1309 $editpage->set_context($this->page
->context
);
1310 if ($this->page
->cm
) {
1311 $editpage->set_cm($this->page
->cm
);
1313 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1314 $editurlparams = $this->page
->url
->params();
1315 $editurlparams['bui_editid'] = $blockid;
1316 $editpage->set_url($editurlbase, $editurlparams);
1317 $editpage->set_block_actions_done();
1318 // At this point we are either going to redirect, or display the form, so
1319 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1321 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1322 $output = $editpage->get_renderer('core');
1325 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1326 if (is_readable($formfile)) {
1327 require_once($formfile);
1328 $classname = 'block_' . $block->name() . '_edit_form';
1329 if (!class_exists($classname)) {
1330 $classname = 'block_edit_form';
1333 $classname = 'block_edit_form';
1336 $mform = new $classname($editpage->url
, $block, $this->page
);
1337 $mform->set_data($block->instance
);
1339 if ($mform->is_cancelled()) {
1340 redirect($this->page
->url
);
1342 } else if ($data = $mform->get_data()) {
1344 $bi->id
= $block->instance
->id
;
1346 // This may get overwritten by the special case handling below.
1347 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1348 $bi->showinsubcontexts
= (bool) $data->bui_contexts
;
1349 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1350 $bi->subpagepattern
= null;
1352 $bi->subpagepattern
= $data->bui_subpagepattern
;
1355 $systemcontext = context_system
::instance();
1356 $frontpagecontext = context_course
::instance(SITEID
);
1357 $parentcontext = context
::instance_by_id($data->bui_parentcontextid
);
1359 // Updating stickiness and contexts. See MDL-21375 for details.
1360 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1362 // Explicitly set the default context
1363 $bi->parentcontextid
= $parentcontext->id
;
1365 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1367 // The interface here is a special case because the pagetype pattern is
1368 // totally derived from the context menu. Here are the excpetions. MDL-30340
1370 switch ($data->bui_contexts
) {
1371 case BUI_CONTEXTS_ENTIRE_SITE
:
1372 // The user wants to show the block across the entire site
1373 $bi->parentcontextid
= $systemcontext->id
;
1374 $bi->showinsubcontexts
= true;
1375 $bi->pagetypepattern
= '*';
1377 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1378 // The user wants the block shown on the front page and all subcontexts
1379 $bi->parentcontextid
= $frontpagecontext->id
;
1380 $bi->showinsubcontexts
= true;
1381 $bi->pagetypepattern
= '*';
1383 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1384 // The user want to show the front page on the frontpage only
1385 $bi->parentcontextid
= $frontpagecontext->id
;
1386 $bi->showinsubcontexts
= false;
1387 $bi->pagetypepattern
= 'site-index';
1388 // This is the only relevant page type anyway but we'll set it explicitly just
1389 // in case the front page grows site-index-* subpages of its own later
1395 $bits = explode('-', $bi->pagetypepattern
);
1396 // hacks for some contexts
1397 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1398 // For course context
1399 // is page type pattern is mod-*, change showinsubcontext to 1
1400 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1401 $bi->showinsubcontexts
= 1;
1403 $bi->showinsubcontexts
= 0;
1405 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1407 // subpagepattern should be null
1408 if ($bits[0] == 'user' or $bits[0] == 'my') {
1409 // we don't need subpagepattern in usercontext
1410 $bi->subpagepattern
= null;
1414 $bi->defaultregion
= $data->bui_defaultregion
;
1415 $bi->defaultweight
= $data->bui_defaultweight
;
1416 $DB->update_record('block_instances', $bi);
1418 if (!empty($block->config
)) {
1419 $config = clone($block->config
);
1421 $config = new stdClass
;
1423 foreach ($data as $configfield => $value) {
1424 if (strpos($configfield, 'config_') !== 0) {
1427 $field = substr($configfield, 7);
1428 $config->$field = $value;
1430 $block->instance_config_save($config);
1433 $bp->visible
= $data->bui_visible
;
1434 $bp->region
= $data->bui_region
;
1435 $bp->weight
= $data->bui_weight
;
1436 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1437 $data->bui_weight
!= $data->bui_defaultweight
;
1439 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1440 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1442 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1443 $bp->id
= $block->instance
->blockpositionid
;
1444 $DB->update_record('block_positions', $bp);
1446 } else if ($needbprecord) {
1447 $bp->blockinstanceid
= $block->instance
->id
;
1448 $bp->contextid
= $this->page
->context
->id
;
1449 $bp->pagetype
= $this->page
->pagetype
;
1450 if ($this->page
->subpage
) {
1451 $bp->subpage
= $this->page
->subpage
;
1455 $DB->insert_record('block_positions', $bp);
1458 redirect($this->page
->url
);
1461 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1462 $editpage->set_title($strheading);
1463 $editpage->set_heading($strheading);
1464 $bits = explode('-', $this->page
->pagetype
);
1465 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1466 // better navbar for tag pages
1467 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1468 $tag = tag_get('id', $this->page
->subpage
, '*');
1469 // tag search page doesn't have subpageid
1471 $editpage->navbar
->add($tag->name
, new moodle_url('/tag/index.php', array('id'=>$tag->id
)));
1474 $editpage->navbar
->add($block->get_title());
1475 $editpage->navbar
->add(get_string('configuration'));
1476 echo $output->header();
1477 echo $output->heading($strheading, 2);
1479 echo $output->footer();
1485 * Handle showing/processing the submission from the block editing form.
1486 * @return boolean true if the form was submitted and the new config saved. Does not
1487 * return if the editing form was displayed. False otherwise.
1489 public function process_url_move() {
1490 global $CFG, $DB, $PAGE;
1492 $blockid = optional_param('bui_moveid', null, PARAM_INT
);
1499 $block = $this->find_instance($blockid);
1501 if (!$this->page
->user_can_edit_blocks()) {
1502 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1505 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1506 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1507 if (!$newregion ||
is_null($newweight)) {
1508 // Don't have a valid target position yet, must be just starting the move.
1509 $this->movingblock
= $blockid;
1510 $this->page
->ensure_param_not_in_url('bui_moveid');
1514 if (!$this->is_known_region($newregion)) {
1515 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1518 // Move this block. This may involve moving other nearby blocks.
1519 $blocks = $this->birecordsbyregion
[$newregion];
1521 $maxweight = self
::MAX_WEIGHT
;
1522 $minweight = -self
::MAX_WEIGHT
;
1524 // Initialise the used weights and spareweights array with the default values
1525 $spareweights = array();
1526 $usedweights = array();
1527 for ($i = $minweight; $i <= $maxweight; $i++
) {
1528 $spareweights[$i] = $i;
1529 $usedweights[$i] = array();
1532 // Check each block and sort out where we have used weights
1533 foreach ($blocks as $bi) {
1534 if ($bi->weight
> $maxweight) {
1535 // If this statement is true then the blocks weight is more than the
1536 // current maximum. To ensure that we can get the best block position
1537 // we will initialise elements within the usedweights and spareweights
1538 // arrays between the blocks weight (which will then be the new max) and
1540 $parseweight = $bi->weight
;
1541 while (!array_key_exists($parseweight, $usedweights)) {
1542 $usedweights[$parseweight] = array();
1543 $spareweights[$parseweight] = $parseweight;
1546 $maxweight = $bi->weight
;
1547 } else if ($bi->weight
< $minweight) {
1548 // As above except this time the blocks weight is LESS than the
1549 // the current minimum, so we will initialise the array from the
1550 // blocks weight (new minimum) to the current minimum
1551 $parseweight = $bi->weight
;
1552 while (!array_key_exists($parseweight, $usedweights)) {
1553 $usedweights[$parseweight] = array();
1554 $spareweights[$parseweight] = $parseweight;
1557 $minweight = $bi->weight
;
1559 if ($bi->id
!= $block->instance
->id
) {
1560 unset($spareweights[$bi->weight
]);
1561 $usedweights[$bi->weight
][] = $bi->id
;
1565 // First we find the nearest gap in the list of weights.
1566 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1568 foreach ($spareweights as $spareweight) {
1569 if (abs($newweight - $spareweight) < $bestdistance) {
1570 $bestdistance = abs($newweight - $spareweight);
1571 $bestgap = $spareweight;
1575 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1576 if (is_null($bestgap)) {
1577 $bestgap = self
::MAX_WEIGHT +
1;
1578 while (!empty($usedweights[$bestgap])) {
1583 // Now we know the gap we are aiming for, so move all the blocks along.
1584 if ($bestgap < $newweight) {
1585 $newweight = floor($newweight);
1586 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1587 foreach ($usedweights[$weight] as $biid) {
1588 $this->reposition_block($biid, $newregion, $weight - 1);
1591 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1593 $newweight = ceil($newweight);
1594 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1595 if (array_key_exists($weight, $usedweights)) {
1596 foreach ($usedweights[$weight] as $biid) {
1597 $this->reposition_block($biid, $newregion, $weight +
1);
1601 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1604 $this->page
->ensure_param_not_in_url('bui_moveid');
1605 $this->page
->ensure_param_not_in_url('bui_newregion');
1606 $this->page
->ensure_param_not_in_url('bui_newweight');
1611 * Turns the display of normal blocks either on or off.
1613 * @param bool $setting
1615 public function show_only_fake_blocks($setting = true) {
1616 $this->fakeblocksonly
= $setting;
1620 /// Helper functions for working with block classes ============================
1623 * Call a class method (one that does not require a block instance) on a block class.
1625 * @param string $blockname the name of the block.
1626 * @param string $method the method name.
1627 * @param array $param parameters to pass to the method.
1628 * @return mixed whatever the method returns.
1630 function block_method_result($blockname, $method, $param = NULL) {
1631 if(!block_load_class($blockname)) {
1634 return call_user_func(array('block_'.$blockname, $method), $param);
1638 * Creates a new instance of the specified block class.
1640 * @param string $blockname the name of the block.
1641 * @param $instance block_instances DB table row (optional).
1642 * @param moodle_page $page the page this block is appearing on.
1643 * @return block_base the requested block instance.
1645 function block_instance($blockname, $instance = NULL, $page = NULL) {
1646 if(!block_load_class($blockname)) {
1649 $classname = 'block_'.$blockname;
1650 $retval = new $classname;
1651 if($instance !== NULL) {
1652 if (is_null($page)) {
1656 $retval->_load_instance($instance, $page);
1662 * Load the block class for a particular type of block.
1664 * @param string $blockname the name of the block.
1665 * @return boolean success or failure.
1667 function block_load_class($blockname) {
1670 if(empty($blockname)) {
1674 $classname = 'block_'.$blockname;
1676 if(class_exists($classname)) {
1680 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1682 if (file_exists($blockpath)) {
1683 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1684 include_once($blockpath);
1686 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1690 return class_exists($classname);
1694 * Given a specific page type, return all the page type patterns that might
1697 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1698 * @return array an array of all the page type patterns that might match this page type.
1700 function matching_page_type_patterns($pagetype) {
1701 $patterns = array($pagetype);
1702 $bits = explode('-', $pagetype);
1703 if (count($bits) == 3 && $bits[0] == 'mod') {
1704 if ($bits[2] == 'view') {
1705 $patterns[] = 'mod-*-view';
1706 } else if ($bits[2] == 'index') {
1707 $patterns[] = 'mod-*-index';
1710 while (count($bits) > 0) {
1711 $patterns[] = implode('-', $bits) . '-*';
1719 * Given a specific page type, parent context and currect context, return all the page type patterns
1720 * that might be used by this block.
1722 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1723 * @param stdClass $parentcontext Block's parent context
1724 * @param stdClass $currentcontext Current context of block
1725 * @return array an array of all the page type patterns that might match this page type.
1727 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1728 global $CFG; // Required for includes bellow.
1730 $bits = explode('-', $pagetype);
1732 $core = core_component
::get_core_subsystems();
1733 $plugins = core_component
::get_plugin_types();
1735 //progressively strip pieces off the page type looking for a match
1736 $componentarray = null;
1737 for ($i = count($bits); $i > 0; $i--) {
1738 $possiblecomponentarray = array_slice($bits, 0, $i);
1739 $possiblecomponent = implode('', $possiblecomponentarray);
1741 // Check to see if the component is a core component
1742 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1743 $libfile = $core[$possiblecomponent].'/lib.php';
1744 if (file_exists($libfile)) {
1745 require_once($libfile);
1746 $function = $possiblecomponent.'_page_type_list';
1747 if (function_exists($function)) {
1748 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1755 //check the plugin directory and look for a callback
1756 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1758 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1759 if (count($bits) > $i) {
1760 $pluginname = $bits[$i];
1761 $directory = core_component
::get_plugin_directory($possiblecomponent, $pluginname);
1762 if (!empty($directory)){
1763 $libfile = $directory.'/lib.php';
1764 if (file_exists($libfile)) {
1765 require_once($libfile);
1766 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1767 if (!function_exists($function)) {
1768 $function = $pluginname.'_page_type_list';
1770 if (function_exists($function)) {
1771 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1779 //we'll only get to here if we still don't have any patterns
1780 //the plugin type may have a callback
1781 $directory = $plugins[$possiblecomponent];
1782 $libfile = $directory.'/lib.php';
1783 if (file_exists($libfile)) {
1784 require_once($libfile);
1785 $function = $possiblecomponent.'_page_type_list';
1786 if (function_exists($function)) {
1787 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1795 if (empty($patterns)) {
1796 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1799 // Ensure that the * pattern is always available if editing block 'at distance', so
1800 // we always can 'bring back' it to the original context. MDL-30340
1801 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
1802 // TODO: We could change the string here, showing its 'bring back' meaning
1803 $patterns['*'] = get_string('page-x', 'pagetype');
1810 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1812 * @param string $pagetype
1813 * @param stdClass $parentcontext
1814 * @param stdClass $currentcontext
1817 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1818 // Generate page type patterns based on current page type if
1819 // callbacks haven't been defined
1820 $patterns = array($pagetype => $pagetype);
1821 $bits = explode('-', $pagetype);
1822 while (count($bits) > 0) {
1823 $pattern = implode('-', $bits) . '-*';
1824 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1825 // guessing page type description
1826 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1827 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1829 $patterns[$pattern] = $pattern;
1833 $patterns['*'] = get_string('page-x', 'pagetype');
1838 * Generates the page type list for the my moodle page
1840 * @param string $pagetype
1841 * @param stdClass $parentcontext
1842 * @param stdClass $currentcontext
1845 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1846 return array('my-index' => get_string('page-my-index', 'pagetype'));
1850 * Generates the page type list for a module by either locating and using the modules callback
1851 * or by generating a default list.
1853 * @param string $pagetype
1854 * @param stdClass $parentcontext
1855 * @param stdClass $currentcontext
1858 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1859 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1860 if (empty($patterns)) {
1861 // if modules don't have callbacks
1862 // generate two default page type patterns for modules only
1863 $bits = explode('-', $pagetype);
1864 $patterns = array($pagetype => $pagetype);
1865 if ($bits[2] == 'view') {
1866 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1867 } else if ($bits[2] == 'index') {
1868 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1873 /// Functions update the blocks if required by the request parameters ==========
1876 * Return a {@link block_contents} representing the add a new block UI, if
1877 * this user is allowed to see it.
1879 * @return block_contents an appropriate block_contents, or null if the user
1880 * cannot add any blocks here.
1882 function block_add_block_ui($page, $output) {
1883 global $CFG, $OUTPUT;
1884 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
1888 $bc = new block_contents();
1889 $bc->title
= get_string('addblock');
1890 $bc->add_class('block_adminblock');
1891 $bc->attributes
['data-block'] = 'adminblock';
1893 $missingblocks = $page->blocks
->get_addable_blocks();
1894 if (empty($missingblocks)) {
1895 $bc->content
= get_string('noblockstoaddhere');
1900 foreach ($missingblocks as $block) {
1901 $blockobject = block_instance($block->name
);
1902 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1903 $menu[$block->name
] = $blockobject->get_title();
1906 core_collator
::asort($menu);
1908 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
1909 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1910 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1911 $bc->content
= $OUTPUT->render($select);
1915 // Functions that have been deprecated by block_manager =======================
1918 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1920 * This function returns an array with the IDs of any blocks that you can add to your page.
1921 * Parameters are passed by reference for speed; they are not modified at all.
1923 * @param $page the page object.
1924 * @param $blockmanager Not used.
1925 * @return array of block type ids.
1927 function blocks_get_missing(&$page, &$blockmanager) {
1928 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER
);
1929 $blocks = $page->blocks
->get_addable_blocks();
1931 foreach ($blocks as $block) {
1932 $ids[] = $block->id
;
1938 * Actually delete from the database any blocks that are currently on this page,
1939 * but which should not be there according to blocks_name_allowed_in_format.
1941 * @todo Write/Fix this function. Currently returns immediately
1944 function blocks_remove_inappropriate($course) {
1948 $blockmanager = blocks_get_by_page($page);
1950 if (empty($blockmanager)) {
1954 if (($pageformat = $page->pagetype) == NULL) {
1958 foreach($blockmanager as $region) {
1959 foreach($region as $instance) {
1960 $block = blocks_get_record($instance->blockid);
1961 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1962 blocks_delete_instance($instance->instance);
1969 * Check that a given name is in a permittable format
1971 * @param string $name
1972 * @param string $pageformat
1975 function blocks_name_allowed_in_format($name, $pageformat) {
1978 if (!$bi = block_instance($name)) {
1982 $formats = $bi->applicable_formats();
1986 foreach ($formats as $format => $allowed) {
1987 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1988 $depth = substr_count($format, '-');
1989 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1994 if ($accept === NULL) {
1995 $accept = !empty($formats['all']);
2001 * Delete a block, and associated data.
2003 * @param object $instance a row from the block_instances table
2004 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2005 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2007 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2010 if ($block = block_instance($instance->blockname
, $instance)) {
2011 $block->instance_delete();
2013 context_helper
::delete_instance(CONTEXT_BLOCK
, $instance->id
);
2015 if (!$skipblockstables) {
2016 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
2017 $DB->delete_records('block_instances', array('id' => $instance->id
));
2018 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
2023 * Delete all the blocks that belong to a particular context.
2025 * @param int $contextid the context id.
2027 function blocks_delete_all_for_context($contextid) {
2029 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2030 foreach ($instances as $instance) {
2031 blocks_delete_instance($instance, true);
2033 $instances->close();
2034 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2035 $DB->delete_records('block_positions', array('contextid' => $contextid));
2039 * Set a block to be visible or hidden on a particular page.
2041 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2042 * block_positions table as return by block_manager.
2043 * @param moodle_page $page the back to set the visibility with respect to.
2044 * @param integer $newvisibility 1 for visible, 0 for hidden.
2046 function blocks_set_visibility($instance, $page, $newvisibility) {
2048 if (!empty($instance->blockpositionid
)) {
2049 // Already have local information on this page.
2050 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
2054 // Create a new block_positions record.
2056 $bp->blockinstanceid
= $instance->id
;
2057 $bp->contextid
= $page->context
->id
;
2058 $bp->pagetype
= $page->pagetype
;
2059 if ($page->subpage
) {
2060 $bp->subpage
= $page->subpage
;
2062 $bp->visible
= $newvisibility;
2063 $bp->region
= $instance->defaultregion
;
2064 $bp->weight
= $instance->defaultweight
;
2065 $DB->insert_record('block_positions', $bp);
2069 * @deprecated since 2.0
2070 * Delete all the blocks from a particular page.
2072 * @param string $pagetype the page type.
2073 * @param integer $pageid the page id.
2074 * @return bool success or failure.
2076 function blocks_delete_all_on_page($pagetype, $pageid) {
2079 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
2080 'This function cannot work any more. Doing nothing. ' .
2081 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER
);
2086 * Get the block record for a particular blockid - that is, a particular type os block.
2088 * @param $int blockid block type id. If null, an array of all block types is returned.
2089 * @param bool $notusedanymore No longer used.
2090 * @return array|object row from block table, or all rows.
2092 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2094 $blocks = $PAGE->blocks
->get_installed_blocks();
2095 if ($blockid === NULL) {
2097 } else if (isset($blocks[$blockid])) {
2098 return $blocks[$blockid];
2105 * Find a given block by its blockid within a provide array
2107 * @param int $blockid
2108 * @param array $blocksarray
2109 * @return bool|object Instance if found else false
2111 function blocks_find_block($blockid, $blocksarray) {
2112 if (empty($blocksarray)) {
2115 foreach($blocksarray as $blockgroup) {
2116 if (empty($blockgroup)) {
2119 foreach($blockgroup as $instance) {
2120 if($instance->blockid
== $blockid) {
2128 // Functions for programatically adding default blocks to pages ================
2131 * Parse a list of default blocks. See config-dist for a description of the format.
2133 * @param string $blocksstr
2136 function blocks_parse_default_blocks_list($blocksstr) {
2138 $bits = explode(':', $blocksstr);
2139 if (!empty($bits)) {
2140 $leftbits = trim(array_shift($bits));
2141 if ($leftbits != '') {
2142 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2145 if (!empty($bits)) {
2146 $rightbits =trim(array_shift($bits));
2147 if ($rightbits != '') {
2148 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2155 * @return array the blocks that should be added to the site course by default.
2157 function blocks_get_default_site_course_blocks() {
2160 if (!empty($CFG->defaultblocks_site
)) {
2161 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2164 BLOCK_POS_LEFT
=> array('site_main_menu'),
2165 BLOCK_POS_RIGHT
=> array('course_summary', 'calendar_month')
2171 * Add the default blocks to a course.
2173 * @param object $course a course object.
2175 function blocks_add_default_course_blocks($course) {
2178 if (!empty($CFG->defaultblocks_override
)) {
2179 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2181 } else if ($course->id
== SITEID
) {
2182 $blocknames = blocks_get_default_site_course_blocks();
2184 } else if (!empty($CFG->{'defaultblocks_' . $course->format
})) {
2185 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format
});
2188 require_once($CFG->dirroot
. '/course/lib.php');
2189 $blocknames = course_get_format($course)->get_default_blocks();
2193 if ($course->id
== SITEID
) {
2194 $pagetypepattern = 'site-index';
2196 $pagetypepattern = 'course-view-*';
2198 $page = new moodle_page();
2199 $page->set_course($course);
2200 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2204 * Add the default system-context blocks. E.g. the admin tree.
2206 function blocks_add_default_system_blocks() {
2209 $page = new moodle_page();
2210 $page->set_context(context_system
::instance());
2211 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('navigation', 'settings')), '*', null, true);
2212 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2214 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2215 $subpagepattern = $defaultmypage->id
;
2217 $subpagepattern = null;
2220 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);