3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * Default names for the block regions in the standard theme.
34 define('BLOCK_POS_LEFT', 'side-pre');
35 define('BLOCK_POS_RIGHT', 'side-post');
38 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
39 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
40 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
42 define('BUI_CONTEXTS_CURRENT', 0);
43 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
45 // Position of "Add block" control, to be used in theme config as a value for $THEME->addblockposition:
46 // - default: as a fake block that is displayed in editing mode
47 // - flatnav: "Add block" item in the flat navigation drawer in editing mode
48 // - custom: none of the above, theme will take care of displaying the control.
49 define('BLOCK_ADDBLOCK_POSITION_DEFAULT', 0);
50 define('BLOCK_ADDBLOCK_POSITION_FLATNAV', 1);
51 define('BLOCK_ADDBLOCK_POSITION_CUSTOM', -1);
54 * Exception thrown when someone tried to do something with a block that does
55 * not exist on a page.
57 * @copyright 2009 Tim Hunt
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 class block_not_on_page_exception
extends moodle_exception
{
64 * @param int $instanceid the block instance id of the block that was looked for.
65 * @param object $page the current page.
67 public function __construct($instanceid, $page) {
69 $a->instanceid
= $instanceid;
70 $a->url
= $page->url
->out();
71 parent
::__construct('blockdoesnotexistonpage', '', $page->url
->out(), $a);
76 * This class keeps track of the block that should appear on a moodle_page.
78 * The page to work with as passed to the constructor.
80 * @copyright 2009 Tim Hunt
81 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
86 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
87 * although other weights are valid.
89 const MAX_WEIGHT
= 10;
91 /// Field declarations =========================================================
94 * the moodle_page we are managing blocks for.
99 /** @var array region name => 1.*/
100 protected $regions = array();
102 /** @var string the region where new blocks are added.*/
103 protected $defaultregion = null;
105 /** @var array will be $DB->get_records('blocks') */
106 protected $allblocks = null;
109 * @var array blocks that this user can add to this page. Will be a subset
110 * of $allblocks, but with array keys block->name. Access this via the
111 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
113 protected $addableblocks = null;
116 * Will be an array region-name => array(db rows loaded in load_blocks);
119 protected $birecordsbyregion = null;
122 * array region-name => array(block objects); populated as necessary by
123 * the ensure_instances_exist method.
126 protected $blockinstances = array();
129 * array region-name => array(block_contents objects) what actually needs to
130 * be displayed in each region.
133 protected $visibleblockcontent = array();
136 * array region-name => array(block_contents objects) extra block-like things
137 * to be displayed in each region, before the real blocks.
140 protected $extracontent = array();
143 * Used by the block move id, to track whether a block is currently being moved.
145 * When you click on the move icon of a block, first the page needs to reload with
146 * extra UI for choosing a new position for a particular block. In that situation
147 * this field holds the id of the block being moved.
151 protected $movingblock = null;
154 * Show only fake blocks
156 protected $fakeblocksonly = false;
158 /// Constructor ================================================================
162 * @param object $page the moodle_page object object we are managing the blocks for,
163 * or a reasonable faxilimily. (See the comment at the top of this class
164 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
166 public function __construct($page) {
170 /// Getter methods =============================================================
173 * Get an array of all region names on this page where a block may appear
175 * @return array the internal names of the regions on this page where block may appear.
177 public function get_regions() {
178 if (is_null($this->defaultregion
)) {
179 $this->page
->initialise_theme_and_output();
181 return array_keys($this->regions
);
185 * Get the region name of the region blocks are added to by default
187 * @return string the internal names of the region where new blocks are added
188 * by default, and where any blocks from an unrecognised region are shown.
189 * (Imagine that blocks were added with one theme selected, then you switched
190 * to a theme with different block positions.)
192 public function get_default_region() {
193 $this->page
->initialise_theme_and_output();
194 return $this->defaultregion
;
198 * The list of block types that may be added to this page.
200 * @return array block name => record from block table.
202 public function get_addable_blocks() {
203 $this->check_is_loaded();
205 if (!is_null($this->addableblocks
)) {
206 return $this->addableblocks
;
210 $this->addableblocks
= array();
212 $allblocks = blocks_get_record();
213 if (empty($allblocks)) {
214 return $this->addableblocks
;
217 $unaddableblocks = self
::get_undeletable_block_types();
218 $requiredbythemeblocks = $this->get_required_by_theme_block_types();
219 $pageformat = $this->page
->pagetype
;
220 foreach($allblocks as $block) {
221 if (!$bi = block_instance($block->name
)) {
224 if ($block->visible
&& !in_array($block->name
, $unaddableblocks) &&
225 !in_array($block->name
, $requiredbythemeblocks) &&
226 ($bi->instance_allow_multiple() ||
!$this->is_block_present($block->name
)) &&
227 blocks_name_allowed_in_format($block->name
, $pageformat) &&
228 $bi->user_can_addto($this->page
)) {
229 $block->title
= $bi->get_title();
230 $this->addableblocks
[$block->name
] = $block;
234 core_collator
::asort_objects_by_property($this->addableblocks
, 'title');
235 return $this->addableblocks
;
239 * Given a block name, find out of any of them are currently present in the page
241 * @param string $blockname - the basic name of a block (eg "navigation")
242 * @return boolean - is there one of these blocks in the current page?
244 public function is_block_present($blockname) {
245 if (empty($this->blockinstances
)) {
249 $requiredbythemeblocks = $this->get_required_by_theme_block_types();
250 foreach ($this->blockinstances
as $region) {
251 foreach ($region as $instance) {
252 if (empty($instance->instance
->blockname
)) {
255 if ($instance->instance
->blockname
== $blockname) {
256 if ($instance->instance
->requiredbytheme
) {
257 if (!in_array($blockname, $requiredbythemeblocks)) {
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 if (empty($region)) {
295 return array_key_exists($region, $this->regions
);
299 * Get an array of all blocks within a given region
301 * @param string $region a block region that exists on this page.
302 * @return array of block instances.
304 public function get_blocks_for_region($region) {
305 $this->check_is_loaded();
306 $this->ensure_instances_exist($region);
307 return $this->blockinstances
[$region];
311 * Returns an array of block content objects that exist in a region
313 * @param string $region a block region that exists on this page.
314 * @return array of block block_contents objects for all the blocks in a region.
316 public function get_content_for_region($region, $output) {
317 $this->check_is_loaded();
318 $this->ensure_content_created($region, $output);
319 return $this->visibleblockcontent
[$region];
323 * Returns an array of block content objects for all the existings regions
325 * @param renderer_base $output the rendered to use
326 * @return array of block block_contents objects for all the blocks in all regions.
329 public function get_content_for_all_regions($output) {
331 $this->check_is_loaded();
333 foreach ($this->regions
as $region => $val) {
334 $this->ensure_content_created($region, $output);
335 $contents[$region] = $this->visibleblockcontent
[$region];
341 * Helper method used by get_content_for_region.
342 * @param string $region region name
343 * @param float $weight weight. May be fractional, since you may want to move a block
344 * between ones with weight 2 and 3, say ($weight would be 2.5).
345 * @return string URL for moving block $this->movingblock to this position.
347 protected function get_move_target_url($region, $weight) {
348 return new moodle_url($this->page
->url
, array('bui_moveid' => $this->movingblock
,
349 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
353 * Determine whether a region contains anything. (Either any real blocks, or
354 * the add new block UI.)
356 * (You may wonder why the $output parameter is required. Unfortunately,
357 * because of the way that blocks work, the only reliable way to find out
358 * if a block will be visible is to get the content for output, and to
359 * get the content, you need a renderer. Fortunately, this is not a
360 * performance problem, because we cache the output that is generated, and
361 * in almost every case where we call region_has_content, we are about to
362 * output the blocks anyway, so we are not doing wasted effort.)
364 * @param string $region a block region that exists on this page.
365 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
366 * @return boolean Whether there is anything in this region.
368 public function region_has_content($region, $output) {
370 if (!$this->is_known_region($region)) {
373 $this->check_is_loaded();
374 $this->ensure_content_created($region, $output);
375 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
376 // Mark Nielsen's patch - part 1
377 if ($this->page
->user_is_editing() && $this->page
->user_can_edit_blocks() && $this->movingblock
) {
378 // If editing is on, we need all the block regions visible, for the
382 return !empty($this->visibleblockcontent
[$region]) ||
!empty($this->extracontent
[$region]);
386 * Get an array of all of the installed blocks.
388 * @return array contents of the block table.
390 public function get_installed_blocks() {
392 if (is_null($this->allblocks
)) {
393 $this->allblocks
= $DB->get_records('block');
395 return $this->allblocks
;
399 * @return array names of block types that must exist on every page with this theme.
401 public function get_required_by_theme_block_types() {
402 $requiredbythemeblocks = false;
403 if (isset($this->page
->theme
->requiredblocks
)) {
404 $requiredbythemeblocks = $this->page
->theme
->requiredblocks
;
407 if ($requiredbythemeblocks === false) {
408 return array('navigation', 'settings');
409 } else if ($requiredbythemeblocks === '') {
411 } else if (is_string($requiredbythemeblocks)) {
412 return explode(',', $requiredbythemeblocks);
414 return $requiredbythemeblocks;
419 * Make this block type undeletable and unaddable.
421 * @param mixed $blockidorname string or int
423 public static function protect_block($blockidorname) {
426 $syscontext = context_system
::instance();
428 require_capability('moodle/site:config', $syscontext);
431 if (is_int($blockidorname)) {
432 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST
);
434 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST
);
436 $undeletableblocktypes = self
::get_undeletable_block_types();
437 if (!in_array($block->name
, $undeletableblocktypes)) {
438 $undeletableblocktypes[] = $block->name
;
439 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
440 add_to_config_log('block_protect', "0", "1", $block->name
);
445 * Make this block type deletable and addable.
447 * @param mixed $blockidorname string or int
449 public static function unprotect_block($blockidorname) {
452 $syscontext = context_system
::instance();
454 require_capability('moodle/site:config', $syscontext);
457 if (is_int($blockidorname)) {
458 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST
);
460 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST
);
462 $undeletableblocktypes = self
::get_undeletable_block_types();
463 if (in_array($block->name
, $undeletableblocktypes)) {
464 $undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name
));
465 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
466 add_to_config_log('block_protect', "1", "0", $block->name
);
472 * Get the list of "protected" blocks via admin block manager ui.
474 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
476 public static function get_undeletable_block_types() {
478 $undeletableblocks = false;
479 if (isset($CFG->undeletableblocktypes
)) {
480 $undeletableblocks = $CFG->undeletableblocktypes
;
483 if (empty($undeletableblocks)) {
485 } else if (is_string($undeletableblocks)) {
486 return explode(',', $undeletableblocks);
488 return $undeletableblocks;
492 /// Setter methods =============================================================
495 * Add a region to a page
497 * @param string $region add a named region where blocks may appear on the current page.
498 * This is an internal name, like 'side-pre', not a string to display in the UI.
499 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
501 public function add_region($region, $custom = true) {
503 $this->check_not_yet_loaded();
505 if (array_key_exists($region, $this->regions
)) {
506 // This here is EXACTLY why we should not be adding block regions into a page. It should
507 // ALWAYS be done in a theme layout.
508 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER
);
510 // We need to register this custom region against the page type being used.
511 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
512 $type = $this->page
->pagetype
;
513 if (!isset($SESSION->custom_block_regions
)) {
514 $SESSION->custom_block_regions
= array($type => array($region));
515 } else if (!isset($SESSION->custom_block_regions
[$type])) {
516 $SESSION->custom_block_regions
[$type] = array($region);
517 } else if (!in_array($region, $SESSION->custom_block_regions
[$type])) {
518 $SESSION->custom_block_regions
[$type][] = $region;
521 $this->regions
[$region] = 1;
525 * Add an array of regions
528 * @param array $regions this utility method calls add_region for each array element.
530 public function add_regions($regions, $custom = true) {
531 foreach ($regions as $region) {
532 $this->add_region($region, $custom);
537 * Finds custom block regions associated with a page type and registers them with this block manager.
539 * @param string $pagetype
541 public function add_custom_regions_for_pagetype($pagetype) {
543 if (isset($SESSION->custom_block_regions
[$pagetype])) {
544 foreach ($SESSION->custom_block_regions
[$pagetype] as $customregion) {
545 $this->add_region($customregion, false);
551 * Set the default region for new blocks on the page
553 * @param string $defaultregion the internal names of the region where new
554 * blocks should be added by default, and where any blocks from an
555 * unrecognised region are shown.
557 public function set_default_region($defaultregion) {
558 $this->check_not_yet_loaded();
559 if ($defaultregion) {
560 $this->check_region_is_known($defaultregion);
562 $this->defaultregion
= $defaultregion;
566 * Add something that looks like a block, but which isn't an actual block_instance,
569 * @param block_contents $bc the content of the block-like thing.
570 * @param string $region a block region that exists on this page.
572 public function add_fake_block($bc, $region) {
573 $this->page
->initialise_theme_and_output();
574 if (!$this->is_known_region($region)) {
575 $region = $this->get_default_region();
577 if (array_key_exists($region, $this->visibleblockcontent
)) {
578 throw new coding_exception('block_manager has already prepared the blocks in region ' .
579 $region . 'for output. It is too late to add a fake block.');
581 if (!isset($bc->attributes
['data-block'])) {
582 $bc->attributes
['data-block'] = '_fake';
584 $bc->attributes
['class'] .= ' block_fake';
585 $this->extracontent
[$region][] = $bc;
589 * Checks to see whether all of the blocks within the given region are docked
591 * @see region_uses_dock
592 * @param string $region
593 * @return bool True if all of the blocks within that region are docked
595 public function region_completely_docked($region, $output) {
597 // If theme doesn't allow docking or allowblockstodock is not set, then return.
598 if (!$this->page
->theme
->enable_dock ||
empty($CFG->allowblockstodock
)) {
602 // Do not dock the region when the user attemps to move a block.
603 if ($this->movingblock
) {
607 // Block regions should not be docked during editing when all the blocks are hidden.
608 if ($this->page
->user_is_editing() && $this->page
->user_can_edit_blocks()) {
612 $this->check_is_loaded();
613 $this->ensure_content_created($region, $output);
614 if (!$this->region_has_content($region, $output)) {
615 // If the region has no content then nothing is docked at all of course.
618 foreach ($this->visibleblockcontent
[$region] as $instance) {
619 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
627 * Checks to see whether any of the blocks within the given regions are docked
629 * @see region_completely_docked
630 * @param array|string $regions array of regions (or single region)
631 * @return bool True if any of the blocks within that region are docked
633 public function region_uses_dock($regions, $output) {
634 if (!$this->page
->theme
->enable_dock
) {
637 $this->check_is_loaded();
638 foreach((array)$regions as $region) {
639 $this->ensure_content_created($region, $output);
640 foreach($this->visibleblockcontent
[$region] as $instance) {
641 if(!empty($instance->content
) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
649 /// Actions ====================================================================
652 * This method actually loads the blocks for our page from the database.
654 * @param boolean|null $includeinvisible
655 * null (default) - load hidden blocks if $this->page->user_is_editing();
656 * true - load hidden blocks.
657 * false - don't load hidden blocks.
659 public function load_blocks($includeinvisible = null) {
662 if (!is_null($this->birecordsbyregion
)) {
667 if ($CFG->version
< 2009050619) {
668 // Upgrade/install not complete. Don't try too show any blocks.
669 $this->birecordsbyregion
= array();
673 // Ensure we have been initialised.
674 if (is_null($this->defaultregion
)) {
675 $this->page
->initialise_theme_and_output();
676 // If there are still no block regions, then there are no blocks on this page.
677 if (empty($this->regions
)) {
678 $this->birecordsbyregion
= array();
683 // Check if we need to load normal blocks
684 if ($this->fakeblocksonly
) {
685 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
689 // Exclude auto created blocks if they are not undeletable in this theme.
690 $requiredbytheme = $this->get_required_by_theme_block_types();
691 $requiredbythemecheck = '';
692 $requiredbythemeparams = array();
693 $requiredbythemenotparams = array();
694 if (!empty($requiredbytheme)) {
695 list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED
, 'requiredbytheme');
696 list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED
,
697 'notrequiredbytheme', false);
698 $requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
699 ' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
701 $requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
704 if (is_null($includeinvisible)) {
705 $includeinvisible = $this->page
->user_is_editing();
707 if ($includeinvisible) {
710 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL) AND (bs.visible = 1 OR bs.visible IS NULL)';
713 $context = $this->page
->context
;
714 $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
715 $parentcontextparams = array();
716 $parentcontextids = $context->get_parent_context_ids();
717 if ($parentcontextids) {
718 list($parentcontexttest, $parentcontextparams) =
719 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
, 'parentcontext');
720 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
723 $pagetypepatterns = matching_page_type_patterns($this->page
->pagetype
);
724 list($pagetypepatterntest, $pagetypepatternparams) =
725 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
, 'pagetypepatterntest');
727 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
728 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
730 $systemcontext = context_system
::instance();
732 'contextlevel' => CONTEXT_BLOCK
,
733 'subpage1' => $this->page
->subpage
,
734 'subpage2' => $this->page
->subpage
,
735 'subpage3' => $this->page
->subpage
,
736 'contextid1' => $context->id
,
737 'contextid2' => $context->id
,
738 'contextid3' => $systemcontext->id
,
739 'contextid4' => $systemcontext->id
,
740 'pagetype' => $this->page
->pagetype
,
741 'pagetype2' => $this->page
->pagetype
,
743 if ($this->page
->subpage
=== '') {
744 $params['subpage1'] = '';
745 $params['subpage2'] = '';
746 $params['subpage3'] = '';
750 COALESCE(bp.id, bs.id) AS blockpositionid,
753 bi.showinsubcontexts,
759 COALESCE(bp.visible, bs.visible, 1) AS visible,
760 COALESCE(bp.region, bs.region, bi.defaultregion) AS region,
761 COALESCE(bp.weight, bs.weight, bi.defaultweight) AS weight,
765 FROM {block_instances} bi
766 JOIN {block} b ON bi.blockname = b.name
767 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
768 AND bp.contextid = :contextid1
769 AND bp.pagetype = :pagetype
770 AND bp.subpage = :subpage1
771 LEFT JOIN {block_positions} bs ON bs.blockinstanceid = bi.id
772 AND bs.contextid = :contextid4
773 AND bs.pagetype = :pagetype2
774 AND bs.subpage = :subpage3
779 AND bi.pagetypepattern $pagetypepatterntest
780 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
783 $requiredbythemecheck
786 COALESCE(bp.region, bs.region, bi.defaultregion),
787 COALESCE(bp.weight, bs.weight, bi.defaultweight),
790 $allparams = $params +
$parentcontextparams +
$pagetypepatternparams +
$requiredbythemeparams +
$requiredbythemenotparams;
791 $blockinstances = $DB->get_recordset_sql($sql, $allparams);
793 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
795 foreach ($blockinstances as $bi) {
796 context_helper
::preload_from_record($bi);
797 if ($this->is_known_region($bi->region
)) {
798 $this->birecordsbyregion
[$bi->region
][] = $bi;
803 $blockinstances->close();
805 // Pages don't necessarily have a defaultregion. The one time this can
806 // happen is when there are no theme block regions, but the script itself
807 // has a block region in the main content area.
808 if (!empty($this->defaultregion
)) {
809 $this->birecordsbyregion
[$this->defaultregion
] =
810 array_merge($this->birecordsbyregion
[$this->defaultregion
], $unknown);
815 * Add a block to the current page, or related pages. The block is added to
816 * context $this->page->contextid. If $pagetypepattern $subpagepattern
818 * @param string $blockname The type of block to add.
819 * @param string $region the block region on this page to add the block to.
820 * @param integer $weight determines the order where this block appears in the region.
821 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
822 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
823 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
825 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
827 // Allow invisible blocks because this is used when adding default page blocks, which
828 // might include invisible ones if the user makes some default blocks invisible
829 $this->check_known_block_type($blockname, true);
830 $this->check_region_is_known($region);
832 if (empty($pagetypepattern)) {
833 $pagetypepattern = $this->page
->pagetype
;
836 $blockinstance = new stdClass
;
837 $blockinstance->blockname
= $blockname;
838 $blockinstance->parentcontextid
= $this->page
->context
->id
;
839 $blockinstance->showinsubcontexts
= !empty($showinsubcontexts);
840 $blockinstance->pagetypepattern
= $pagetypepattern;
841 $blockinstance->subpagepattern
= $subpagepattern;
842 $blockinstance->defaultregion
= $region;
843 $blockinstance->defaultweight
= $weight;
844 $blockinstance->configdata
= '';
845 $blockinstance->timecreated
= time();
846 $blockinstance->timemodified
= $blockinstance->timecreated
;
847 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
849 // Ensure the block context is created.
850 context_block
::instance($blockinstance->id
);
852 // If the new instance was created, allow it to do additional setup
853 if ($block = block_instance($blockname, $blockinstance)) {
854 $block->instance_create();
858 public function add_block_at_end_of_default_region($blockname) {
859 if (empty($this->birecordsbyregion
)) {
860 // No blocks or block regions exist yet.
863 $defaulregion = $this->get_default_region();
865 $lastcurrentblock = end($this->birecordsbyregion
[$defaulregion]);
866 if ($lastcurrentblock) {
867 $weight = $lastcurrentblock->weight +
1;
872 if ($this->page
->subpage
) {
873 $subpage = $this->page
->subpage
;
878 // Special case. Course view page type include the course format, but we
879 // want to add the block non-format-specifically.
880 $pagetypepattern = $this->page
->pagetype
;
881 if (strpos($pagetypepattern, 'course-view') === 0) {
882 $pagetypepattern = 'course-view-*';
885 // We should end using this for ALL the blocks, making always the 1st option
886 // the default one to be used. Until then, this is one hack to avoid the
887 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
888 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
889 // (the FIRST $pagetypepattern will be set)
891 // We are applying it to all blocks created in mod pages for now and only if the
892 // default pagetype is not one of the available options
893 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
894 $pagetypelist = generate_page_type_patterns($this->page
->pagetype
, null, $this->page
->context
);
895 // Only go for the first if the pagetype is not a valid option
896 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
897 $pagetypepattern = key($pagetypelist);
900 // Surely other pages like course-report will need this too, they just are not important
901 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
903 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
907 * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
908 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
909 * and incremented by the position of the block in the $blocks array
911 * @param array $blocks array with array keys the region names, and values an array of block names.
912 * @param string $pagetypepattern optional. Passed to {@link add_block()}
913 * @param string $subpagepattern optional. Passed to {@link add_block()}
914 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
915 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
917 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
918 $initialweight = $weight;
919 $this->add_regions(array_keys($blocks), false);
920 foreach ($blocks as $region => $regionblocks) {
921 foreach ($regionblocks as $offset => $blockname) {
922 $weight = $initialweight +
$offset;
923 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
929 * Move a block to a new position on this page.
931 * If this block cannot appear on any other pages, then we change defaultposition/weight
932 * in the block_instances table. Otherwise we just set the position on this page.
934 * @param $blockinstanceid the block instance id.
935 * @param $newregion the new region name.
936 * @param $newweight the new weight.
938 public function reposition_block($blockinstanceid, $newregion, $newweight) {
941 $this->check_region_is_known($newregion);
942 $inst = $this->find_instance($blockinstanceid);
944 $bi = $inst->instance
;
945 if ($bi->weight
== $bi->defaultweight
&& $bi->region
== $bi->defaultregion
&&
946 !$bi->showinsubcontexts
&& strpos($bi->pagetypepattern
, '*') === false &&
947 (!$this->page
->subpage ||
$bi->subpagepattern
)) {
949 // Set default position
950 $newbi = new stdClass
;
951 $newbi->id
= $bi->id
;
952 $newbi->defaultregion
= $newregion;
953 $newbi->defaultweight
= $newweight;
954 $newbi->timemodified
= time();
955 $DB->update_record('block_instances', $newbi);
957 if ($bi->blockpositionid
) {
959 $bp->id
= $bi->blockpositionid
;
960 $bp->region
= $newregion;
961 $bp->weight
= $newweight;
962 $DB->update_record('block_positions', $bp);
966 // Just set position on this page.
968 $bp->region
= $newregion;
969 $bp->weight
= $newweight;
971 if ($bi->blockpositionid
) {
972 $bp->id
= $bi->blockpositionid
;
973 $DB->update_record('block_positions', $bp);
976 $bp->blockinstanceid
= $bi->id
;
977 $bp->contextid
= $this->page
->context
->id
;
978 $bp->pagetype
= $this->page
->pagetype
;
979 if ($this->page
->subpage
) {
980 $bp->subpage
= $this->page
->subpage
;
984 $bp->visible
= $bi->visible
;
985 $DB->insert_record('block_positions', $bp);
991 * Find a given block by its instance id
993 * @param integer $instanceid
996 public function find_instance($instanceid) {
997 foreach ($this->regions
as $region => $notused) {
998 $this->ensure_instances_exist($region);
999 foreach($this->blockinstances
[$region] as $instance) {
1000 if ($instance->instance
->id
== $instanceid) {
1005 throw new block_not_on_page_exception($instanceid, $this->page
);
1008 /// Inner workings =============================================================
1011 * Check whether the page blocks have been loaded yet
1013 * @return void Throws coding exception if already loaded
1015 protected function check_not_yet_loaded() {
1016 if (!is_null($this->birecordsbyregion
)) {
1017 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.');
1022 * Check whether the page blocks have been loaded yet
1024 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
1026 * @return void Throws coding exception if already loaded
1028 protected function check_is_loaded() {
1029 if (is_null($this->birecordsbyregion
)) {
1030 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
1035 * Check if a block type is known and usable
1037 * @param string $blockname The block type name to search for
1038 * @param bool $includeinvisible Include disabled block types in the initial pass
1039 * @return void Coding Exception thrown if unknown or not enabled
1041 protected function check_known_block_type($blockname, $includeinvisible = false) {
1042 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
1043 if ($this->is_known_block_type($blockname, true)) {
1044 throw new coding_exception('Unknown block type ' . $blockname);
1046 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
1052 * Check if a region is known by its name
1054 * @param string $region
1055 * @return void Coding Exception thrown if the region is not known
1057 protected function check_region_is_known($region) {
1058 if (!$this->is_known_region($region)) {
1059 throw new coding_exception('Trying to reference an unknown block region ' . $region);
1064 * Returns an array of region names as keys and nested arrays for values
1066 * @return array an array where the array keys are the region names, and the array
1067 * values are empty arrays.
1069 protected function prepare_per_region_arrays() {
1071 foreach ($this->regions
as $region => $notused) {
1072 $result[$region] = array();
1078 * Create a set of new block instance from a record array
1080 * @param array $birecords An array of block instance records
1081 * @return array An array of instantiated block_instance objects
1083 protected function create_block_instances($birecords) {
1085 foreach ($birecords as $record) {
1086 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
1087 $results[] = $blockobject;
1094 * Create all the block instances for all the blocks that were loaded by
1095 * load_blocks. This is used, for example, to ensure that all blocks get a
1096 * chance to initialise themselves via the {@link block_base::specialize()}
1097 * method, before any output is done.
1099 * It is also used to create any blocks that are "requiredbytheme" by the current theme.
1100 * These blocks that are auto-created have requiredbytheme set on the block instance
1101 * so they are only visible on themes that require them.
1103 public function create_all_block_instances() {
1106 // If there are any un-removable blocks that were not created - force them.
1107 $requiredbytheme = $this->get_required_by_theme_block_types();
1108 if (!$this->fakeblocksonly
) {
1109 foreach ($requiredbytheme as $forced) {
1110 if (empty($forced)) {
1114 foreach ($this->get_regions() as $region) {
1115 foreach($this->birecordsbyregion
[$region] as $instance) {
1116 if ($instance->blockname
== $forced) {
1122 $this->add_block_required_by_theme($forced);
1129 // Some blocks were missing. Lets do it again.
1130 $this->birecordsbyregion
= null;
1131 $this->load_blocks();
1133 foreach ($this->get_regions() as $region) {
1134 $this->ensure_instances_exist($region);
1140 * Add a block that is required by the current theme but has not been
1141 * created yet. This is a special type of block that only shows in themes that
1142 * require it (by listing it in undeletable_block_types).
1144 * @param string $blockname the name of the block type.
1146 protected function add_block_required_by_theme($blockname) {
1149 if (empty($this->birecordsbyregion
)) {
1150 // No blocks or block regions exist yet.
1154 // Never auto create blocks when we are showing fake blocks only.
1155 if ($this->fakeblocksonly
) {
1159 // Never add a duplicate block required by theme.
1160 if ($DB->record_exists('block_instances', array('blockname' => $blockname, 'requiredbytheme' => 1))) {
1164 $systemcontext = context_system
::instance();
1165 $defaultregion = $this->get_default_region();
1166 // Add a special system wide block instance only for themes that require it.
1167 $blockinstance = new stdClass
;
1168 $blockinstance->blockname
= $blockname;
1169 $blockinstance->parentcontextid
= $systemcontext->id
;
1170 $blockinstance->showinsubcontexts
= true;
1171 $blockinstance->requiredbytheme
= true;
1172 $blockinstance->pagetypepattern
= '*';
1173 $blockinstance->subpagepattern
= null;
1174 $blockinstance->defaultregion
= $defaultregion;
1175 $blockinstance->defaultweight
= 0;
1176 $blockinstance->configdata
= '';
1177 $blockinstance->timecreated
= time();
1178 $blockinstance->timemodified
= $blockinstance->timecreated
;
1179 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
1181 // Ensure the block context is created.
1182 context_block
::instance($blockinstance->id
);
1184 // If the new instance was created, allow it to do additional setup.
1185 if ($block = block_instance($blockname, $blockinstance)) {
1186 $block->instance_create();
1191 * Return an array of content objects from a set of block instances
1193 * @param array $instances An array of block instances
1194 * @param renderer_base The renderer to use.
1195 * @param string $region the region name.
1196 * @return array An array of block_content (and possibly block_move_target) objects.
1198 protected function create_block_contents($instances, $output, $region) {
1203 if ($this->movingblock
) {
1204 $first = reset($instances);
1206 $lastweight = $first->instance
->weight
- 2;
1210 foreach ($instances as $instance) {
1211 $content = $instance->get_content_for_output($output);
1212 if (empty($content)) {
1216 if ($this->movingblock
&& $lastweight != $instance->instance
->weight
&&
1217 $content->blockinstanceid
!= $this->movingblock
&& $lastblock != $this->movingblock
) {
1218 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight +
$instance->instance
->weight
)/2));
1221 if ($content->blockinstanceid
== $this->movingblock
) {
1222 $content->add_class('beingmoved');
1223 $content->annotation
.= get_string('movingthisblockcancel', 'block',
1224 html_writer
::link($this->page
->url
, get_string('cancel')));
1227 $results[] = $content;
1228 $lastweight = $instance->instance
->weight
;
1229 $lastblock = $instance->instance
->id
;
1232 if ($this->movingblock
&& $lastblock != $this->movingblock
) {
1233 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight +
1));
1239 * Ensure block instances exist for a given region
1241 * @param string $region Check for bi's with the instance with this name
1243 protected function ensure_instances_exist($region) {
1244 $this->check_region_is_known($region);
1245 if (!array_key_exists($region, $this->blockinstances
)) {
1246 $this->blockinstances
[$region] =
1247 $this->create_block_instances($this->birecordsbyregion
[$region]);
1252 * Ensure that there is some content within the given region
1254 * @param string $region The name of the region to check
1256 public function ensure_content_created($region, $output) {
1257 $this->ensure_instances_exist($region);
1258 if (!array_key_exists($region, $this->visibleblockcontent
)) {
1259 $contents = array();
1260 if (array_key_exists($region, $this->extracontent
)) {
1261 $contents = $this->extracontent
[$region];
1263 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances
[$region], $output, $region));
1264 if (($region == $this->defaultregion
) && (!isset($this->page
->theme
->addblockposition
) ||
1265 $this->page
->theme
->addblockposition
== BLOCK_ADDBLOCK_POSITION_DEFAULT
)) {
1266 $addblockui = block_add_block_ui($this->page
, $output);
1268 $contents[] = $addblockui;
1271 $this->visibleblockcontent
[$region] = $contents;
1275 /// Process actions from the URL ===============================================
1278 * Get the appropriate list of editing icons for a block. This is used
1279 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1281 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1282 * @return an array in the format for {@link block_contents::$controls}
1284 public function edit_controls($block) {
1287 $controls = array();
1288 $actionurl = $this->page
->url
->out(false, array('sesskey'=> sesskey()));
1289 $blocktitle = $block->title
;
1290 if (empty($blocktitle)) {
1291 $blocktitle = $block->arialabel
;
1294 if ($this->page
->user_can_edit_blocks()) {
1296 $str = new lang_string('moveblock', 'block', $blocktitle);
1297 $controls[] = new action_menu_link_primary(
1298 new moodle_url($actionurl, array('bui_moveid' => $block->instance
->id
)),
1299 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1301 array('class' => 'editing_move')
1306 if ($this->page
->user_can_edit_blocks() ||
$block->user_can_edit()) {
1307 // Edit config icon - always show - needed for positioning UI.
1308 $str = new lang_string('configureblock', 'block', $blocktitle);
1309 $controls[] = new action_menu_link_secondary(
1310 new moodle_url($actionurl, array('bui_editid' => $block->instance
->id
)),
1311 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1313 array('class' => 'editing_edit')
1318 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1320 if ($block->instance
->visible
) {
1321 $str = new lang_string('hideblock', 'block', $blocktitle);
1322 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance
->id
));
1323 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1324 $attributes = array('class' => 'editing_hide');
1326 $str = new lang_string('showblock', 'block', $blocktitle);
1327 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance
->id
));
1328 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1329 $attributes = array('class' => 'editing_show');
1331 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1335 if (get_assignable_roles($block->context
, ROLENAME_SHORT
)) {
1336 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context
->id
,
1337 'returnurl' => $this->page
->url
->out_as_local_url()));
1338 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1339 $controls[] = new action_menu_link_secondary(
1341 new pix_icon('i/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1342 $str, array('class' => 'editing_assignroles')
1347 if (has_capability('moodle/role:review', $block->context
) or get_overridable_roles($block->context
)) {
1348 $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context
->id
,
1349 'returnurl' => $this->page
->url
->out_as_local_url()));
1350 $str = get_string('permissions', 'role');
1351 $controls[] = new action_menu_link_secondary(
1353 new pix_icon('i/permissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1354 $str, array('class' => 'editing_permissions')
1358 // Change permissions.
1359 if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context
)) {
1360 $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context
->id
,
1361 'returnurl' => $this->page
->url
->out_as_local_url()));
1362 $str = get_string('checkpermissions', 'role');
1363 $controls[] = new action_menu_link_secondary(
1365 new pix_icon('i/checkpermissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1366 $str, array('class' => 'editing_checkroles')
1370 if ($this->user_can_delete_block($block)) {
1372 $str = new lang_string('deleteblock', 'block', $blocktitle);
1373 $controls[] = new action_menu_link_secondary(
1374 new moodle_url($actionurl, array('bui_deleteid' => $block->instance
->id
)),
1375 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1377 array('class' => 'editing_delete')
1385 * @param block_base $block a block that appears on this page.
1386 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1388 protected function user_can_delete_block($block) {
1389 return $this->page
->user_can_edit_blocks() && $block->user_can_edit() &&
1390 $block->user_can_addto($this->page
) &&
1391 !in_array($block->instance
->blockname
, self
::get_undeletable_block_types()) &&
1392 !in_array($block->instance
->blockname
, $this->get_required_by_theme_block_types());
1396 * Process any block actions that were specified in the URL.
1398 * @return boolean true if anything was done. False if not.
1400 public function process_url_actions() {
1401 if (!$this->page
->user_is_editing()) {
1404 return $this->process_url_add() ||
$this->process_url_delete() ||
1405 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1406 $this->process_url_move();
1410 * Handle adding a block.
1411 * @return boolean true if anything was done. False if not.
1413 public function process_url_add() {
1414 global $CFG, $PAGE, $OUTPUT;
1416 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1417 if ($blocktype === null) {
1423 if (!$this->page
->user_can_edit_blocks()) {
1424 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1427 $addableblocks = $this->get_addable_blocks();
1429 if ($blocktype === '') {
1430 // Display add block selection.
1431 $addpage = new moodle_page();
1432 $addpage->set_pagelayout('admin');
1433 $addpage->blocks
->show_only_fake_blocks(true);
1434 $addpage->set_course($this->page
->course
);
1435 $addpage->set_context($this->page
->context
);
1436 if ($this->page
->cm
) {
1437 $addpage->set_cm($this->page
->cm
);
1440 $addpagebase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1441 $addpageparams = $this->page
->url
->params();
1442 $addpage->set_url($addpagebase, $addpageparams);
1443 $addpage->set_block_actions_done();
1444 // At this point we are going to display the block selector, overwrite global $PAGE ready for this.
1446 // Some functions use $OUTPUT so we need to replace that too.
1447 $OUTPUT = $addpage->get_renderer('core');
1450 $straddblock = get_string('addblock');
1452 $PAGE->navbar
->add($straddblock);
1453 $PAGE->set_title($straddblock);
1454 $PAGE->set_heading($site->fullname
);
1455 echo $OUTPUT->header();
1456 echo $OUTPUT->heading($straddblock);
1458 if (!$addableblocks) {
1459 echo $OUTPUT->box(get_string('noblockstoaddhere'));
1460 echo $OUTPUT->container($OUTPUT->action_link($addpage->url
, get_string('back')), 'm-x-3 m-b-1');
1462 $url = new moodle_url($addpage->url
, array('sesskey' => sesskey()));
1463 echo $OUTPUT->render_from_template('core/add_block_body',
1464 ['blocks' => array_values($addableblocks),
1465 'url' => '?' . $url->get_query_string(false)]);
1466 echo $OUTPUT->container($OUTPUT->action_link($addpage->url
, get_string('cancel')), 'm-x-3 m-b-1');
1469 echo $OUTPUT->footer();
1470 // Make sure that nothing else happens after we have displayed this form.
1474 if (!array_key_exists($blocktype, $addableblocks)) {
1475 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1478 $this->add_block_at_end_of_default_region($blocktype);
1480 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1481 $this->page
->ensure_param_not_in_url('bui_addblock');
1487 * Handle deleting a block.
1488 * @return boolean true if anything was done. False if not.
1490 public function process_url_delete() {
1491 global $CFG, $PAGE, $OUTPUT;
1493 $blockid = optional_param('bui_deleteid', null, PARAM_INT
);
1494 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT
);
1501 $block = $this->page
->blocks
->find_instance($blockid);
1502 if (!$this->user_can_delete_block($block)) {
1503 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1506 if (!$confirmdelete) {
1507 $deletepage = new moodle_page();
1508 $deletepage->set_pagelayout('admin');
1509 $deletepage->blocks
->show_only_fake_blocks(true);
1510 $deletepage->set_course($this->page
->course
);
1511 $deletepage->set_context($this->page
->context
);
1512 if ($this->page
->cm
) {
1513 $deletepage->set_cm($this->page
->cm
);
1516 $deleteurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1517 $deleteurlparams = $this->page
->url
->params();
1518 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1519 $deletepage->set_block_actions_done();
1520 // At this point we are either going to redirect, or display the form, so
1521 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1522 $PAGE = $deletepage;
1523 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1524 $output = $deletepage->get_renderer('core');
1528 $blocktitle = $block->get_title();
1529 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1530 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1532 // If the block is being shown in sub contexts display a warning.
1533 if ($block->instance
->showinsubcontexts
== 1) {
1534 $parentcontext = context
::instance_by_id($block->instance
->parentcontextid
);
1535 $systemcontext = context_system
::instance();
1536 $messagestring = new stdClass();
1537 $messagestring->location
= $parentcontext->get_context_name();
1539 // Checking for blocks that may have visibility on the front page and pages added on that.
1540 if ($parentcontext->id
!= $systemcontext->id
&& is_inside_frontpage($parentcontext)) {
1541 $messagestring->pagetype
= get_string('showonfrontpageandsubs', 'block');
1543 $pagetypes = generate_page_type_patterns($this->page
->pagetype
, $parentcontext);
1544 $messagestring->pagetype
= $block->instance
->pagetypepattern
;
1545 if (isset($pagetypes[$block->instance
->pagetypepattern
])) {
1546 $messagestring->pagetype
= $pagetypes[$block->instance
->pagetypepattern
];
1550 $message = get_string('deleteblockwarning', 'block', $messagestring);
1553 $PAGE->navbar
->add($strdeletecheck);
1554 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1555 $PAGE->set_heading($site->fullname
);
1556 echo $OUTPUT->header();
1557 $confirmurl = new moodle_url($deletepage->url
, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance
->id
, 'bui_confirm' => 1));
1558 $cancelurl = new moodle_url($deletepage->url
);
1559 $yesbutton = new single_button($confirmurl, get_string('yes'));
1560 $nobutton = new single_button($cancelurl, get_string('no'));
1561 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1562 echo $OUTPUT->footer();
1563 // Make sure that nothing else happens after we have displayed this form.
1566 blocks_delete_instance($block->instance
);
1567 // bui_deleteid and bui_confirm should not be in the PAGE url.
1568 $this->page
->ensure_param_not_in_url('bui_deleteid');
1569 $this->page
->ensure_param_not_in_url('bui_confirm');
1575 * Handle showing or hiding a block.
1576 * @return boolean true if anything was done. False if not.
1578 public function process_url_show_hide() {
1579 if ($blockid = optional_param('bui_hideid', null, PARAM_INT
)) {
1581 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT
)) {
1589 $block = $this->page
->blocks
->find_instance($blockid);
1591 if (!$this->page
->user_can_edit_blocks()) {
1592 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1593 } else if (!$block->instance_can_be_hidden()) {
1597 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1599 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1600 $this->page
->ensure_param_not_in_url('bui_hideid');
1601 $this->page
->ensure_param_not_in_url('bui_showid');
1607 * Handle showing/processing the submission from the block editing form.
1608 * @return boolean true if the form was submitted and the new config saved. Does not
1609 * return if the editing form was displayed. False otherwise.
1611 public function process_url_edit() {
1612 global $CFG, $DB, $PAGE, $OUTPUT;
1614 $blockid = optional_param('bui_editid', null, PARAM_INT
);
1620 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1622 $block = $this->find_instance($blockid);
1624 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1625 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1628 $editpage = new moodle_page();
1629 $editpage->set_pagelayout('admin');
1630 $editpage->blocks
->show_only_fake_blocks(true);
1631 $editpage->set_course($this->page
->course
);
1632 //$editpage->set_context($block->context);
1633 $editpage->set_context($this->page
->context
);
1634 if ($this->page
->cm
) {
1635 $editpage->set_cm($this->page
->cm
);
1637 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1638 $editurlparams = $this->page
->url
->params();
1639 $editurlparams['bui_editid'] = $blockid;
1640 $editpage->set_url($editurlbase, $editurlparams);
1641 $editpage->set_block_actions_done();
1642 // At this point we are either going to redirect, or display the form, so
1643 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1645 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1646 $output = $editpage->get_renderer('core');
1649 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1650 if (is_readable($formfile)) {
1651 require_once($formfile);
1652 $classname = 'block_' . $block->name() . '_edit_form';
1653 if (!class_exists($classname)) {
1654 $classname = 'block_edit_form';
1657 $classname = 'block_edit_form';
1660 $mform = new $classname($editpage->url
, $block, $this->page
);
1661 $mform->set_data($block->instance
);
1663 if ($mform->is_cancelled()) {
1664 redirect($this->page
->url
);
1666 } else if ($data = $mform->get_data()) {
1668 $bi->id
= $block->instance
->id
;
1670 // This may get overwritten by the special case handling below.
1671 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1672 $bi->showinsubcontexts
= (bool) $data->bui_contexts
;
1673 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1674 $bi->subpagepattern
= null;
1676 $bi->subpagepattern
= $data->bui_subpagepattern
;
1679 $systemcontext = context_system
::instance();
1680 $frontpagecontext = context_course
::instance(SITEID
);
1681 $parentcontext = context
::instance_by_id($data->bui_parentcontextid
);
1683 // Updating stickiness and contexts. See MDL-21375 for details.
1684 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1686 // Explicitly set the default context
1687 $bi->parentcontextid
= $parentcontext->id
;
1689 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1691 // The interface here is a special case because the pagetype pattern is
1692 // totally derived from the context menu. Here are the excpetions. MDL-30340
1694 switch ($data->bui_contexts
) {
1695 case BUI_CONTEXTS_ENTIRE_SITE
:
1696 // The user wants to show the block across the entire site
1697 $bi->parentcontextid
= $systemcontext->id
;
1698 $bi->showinsubcontexts
= true;
1699 $bi->pagetypepattern
= '*';
1701 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1702 // The user wants the block shown on the front page and all subcontexts
1703 $bi->parentcontextid
= $frontpagecontext->id
;
1704 $bi->showinsubcontexts
= true;
1705 $bi->pagetypepattern
= '*';
1707 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1708 // The user want to show the front page on the frontpage only
1709 $bi->parentcontextid
= $frontpagecontext->id
;
1710 $bi->showinsubcontexts
= false;
1711 $bi->pagetypepattern
= 'site-index';
1712 // This is the only relevant page type anyway but we'll set it explicitly just
1713 // in case the front page grows site-index-* subpages of its own later
1719 $bits = explode('-', $bi->pagetypepattern
);
1720 // hacks for some contexts
1721 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1722 // For course context
1723 // is page type pattern is mod-*, change showinsubcontext to 1
1724 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1725 $bi->showinsubcontexts
= 1;
1727 $bi->showinsubcontexts
= 0;
1729 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1731 // subpagepattern should be null
1732 if ($bits[0] == 'user' or $bits[0] == 'my') {
1733 // we don't need subpagepattern in usercontext
1734 $bi->subpagepattern
= null;
1738 $bi->defaultregion
= $data->bui_defaultregion
;
1739 $bi->defaultweight
= $data->bui_defaultweight
;
1740 $bi->timemodified
= time();
1741 $DB->update_record('block_instances', $bi);
1743 if (!empty($block->config
)) {
1744 $config = clone($block->config
);
1746 $config = new stdClass
;
1748 foreach ($data as $configfield => $value) {
1749 if (strpos($configfield, 'config_') !== 0) {
1752 $field = substr($configfield, 7);
1753 $config->$field = $value;
1755 $block->instance_config_save($config);
1758 $bp->visible
= $data->bui_visible
;
1759 $bp->region
= $data->bui_region
;
1760 $bp->weight
= $data->bui_weight
;
1761 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1762 $data->bui_weight
!= $data->bui_defaultweight
;
1764 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1765 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1767 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1768 $bp->id
= $block->instance
->blockpositionid
;
1769 $DB->update_record('block_positions', $bp);
1771 } else if ($needbprecord) {
1772 $bp->blockinstanceid
= $block->instance
->id
;
1773 $bp->contextid
= $this->page
->context
->id
;
1774 $bp->pagetype
= $this->page
->pagetype
;
1775 if ($this->page
->subpage
) {
1776 $bp->subpage
= $this->page
->subpage
;
1780 $DB->insert_record('block_positions', $bp);
1783 redirect($this->page
->url
);
1786 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1787 $editpage->set_title($strheading);
1788 $editpage->set_heading($strheading);
1789 $bits = explode('-', $this->page
->pagetype
);
1790 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1791 // better navbar for tag pages
1792 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1793 $tag = core_tag_tag
::get($this->page
->subpage
);
1794 // tag search page doesn't have subpageid
1796 $editpage->navbar
->add($tag->get_display_name(), $tag->get_view_url());
1799 $editpage->navbar
->add($block->get_title());
1800 $editpage->navbar
->add(get_string('configuration'));
1801 echo $output->header();
1802 echo $output->heading($strheading, 2);
1804 echo $output->footer();
1810 * Handle showing/processing the submission from the block editing form.
1811 * @return boolean true if the form was submitted and the new config saved. Does not
1812 * return if the editing form was displayed. False otherwise.
1814 public function process_url_move() {
1815 global $CFG, $DB, $PAGE;
1817 $blockid = optional_param('bui_moveid', null, PARAM_INT
);
1824 $block = $this->find_instance($blockid);
1826 if (!$this->page
->user_can_edit_blocks()) {
1827 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1830 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1831 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1832 if (!$newregion ||
is_null($newweight)) {
1833 // Don't have a valid target position yet, must be just starting the move.
1834 $this->movingblock
= $blockid;
1835 $this->page
->ensure_param_not_in_url('bui_moveid');
1839 if (!$this->is_known_region($newregion)) {
1840 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1843 // Move this block. This may involve moving other nearby blocks.
1844 $blocks = $this->birecordsbyregion
[$newregion];
1846 $maxweight = self
::MAX_WEIGHT
;
1847 $minweight = -self
::MAX_WEIGHT
;
1849 // Initialise the used weights and spareweights array with the default values
1850 $spareweights = array();
1851 $usedweights = array();
1852 for ($i = $minweight; $i <= $maxweight; $i++
) {
1853 $spareweights[$i] = $i;
1854 $usedweights[$i] = array();
1857 // Check each block and sort out where we have used weights
1858 foreach ($blocks as $bi) {
1859 if ($bi->weight
> $maxweight) {
1860 // If this statement is true then the blocks weight is more than the
1861 // current maximum. To ensure that we can get the best block position
1862 // we will initialise elements within the usedweights and spareweights
1863 // arrays between the blocks weight (which will then be the new max) and
1865 $parseweight = $bi->weight
;
1866 while (!array_key_exists($parseweight, $usedweights)) {
1867 $usedweights[$parseweight] = array();
1868 $spareweights[$parseweight] = $parseweight;
1871 $maxweight = $bi->weight
;
1872 } else if ($bi->weight
< $minweight) {
1873 // As above except this time the blocks weight is LESS than the
1874 // the current minimum, so we will initialise the array from the
1875 // blocks weight (new minimum) to the current minimum
1876 $parseweight = $bi->weight
;
1877 while (!array_key_exists($parseweight, $usedweights)) {
1878 $usedweights[$parseweight] = array();
1879 $spareweights[$parseweight] = $parseweight;
1882 $minweight = $bi->weight
;
1884 if ($bi->id
!= $block->instance
->id
) {
1885 unset($spareweights[$bi->weight
]);
1886 $usedweights[$bi->weight
][] = $bi->id
;
1890 // First we find the nearest gap in the list of weights.
1891 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1893 foreach ($spareweights as $spareweight) {
1894 if (abs($newweight - $spareweight) < $bestdistance) {
1895 $bestdistance = abs($newweight - $spareweight);
1896 $bestgap = $spareweight;
1900 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1901 if (is_null($bestgap)) {
1902 $bestgap = self
::MAX_WEIGHT +
1;
1903 while (!empty($usedweights[$bestgap])) {
1908 // Now we know the gap we are aiming for, so move all the blocks along.
1909 if ($bestgap < $newweight) {
1910 $newweight = floor($newweight);
1911 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1912 if (array_key_exists($weight, $usedweights)) {
1913 foreach ($usedweights[$weight] as $biid) {
1914 $this->reposition_block($biid, $newregion, $weight - 1);
1918 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1920 $newweight = ceil($newweight);
1921 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1922 if (array_key_exists($weight, $usedweights)) {
1923 foreach ($usedweights[$weight] as $biid) {
1924 $this->reposition_block($biid, $newregion, $weight +
1);
1928 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1931 $this->page
->ensure_param_not_in_url('bui_moveid');
1932 $this->page
->ensure_param_not_in_url('bui_newregion');
1933 $this->page
->ensure_param_not_in_url('bui_newweight');
1938 * Turns the display of normal blocks either on or off.
1940 * @param bool $setting
1942 public function show_only_fake_blocks($setting = true) {
1943 $this->fakeblocksonly
= $setting;
1947 /// Helper functions for working with block classes ============================
1950 * Call a class method (one that does not require a block instance) on a block class.
1952 * @param string $blockname the name of the block.
1953 * @param string $method the method name.
1954 * @param array $param parameters to pass to the method.
1955 * @return mixed whatever the method returns.
1957 function block_method_result($blockname, $method, $param = NULL) {
1958 if(!block_load_class($blockname)) {
1961 return call_user_func(array('block_'.$blockname, $method), $param);
1965 * Creates a new instance of the specified block class.
1967 * @param string $blockname the name of the block.
1968 * @param $instance block_instances DB table row (optional).
1969 * @param moodle_page $page the page this block is appearing on.
1970 * @return block_base the requested block instance.
1972 function block_instance($blockname, $instance = NULL, $page = NULL) {
1973 if(!block_load_class($blockname)) {
1976 $classname = 'block_'.$blockname;
1977 $retval = new $classname;
1978 if($instance !== NULL) {
1979 if (is_null($page)) {
1983 $retval->_load_instance($instance, $page);
1989 * Load the block class for a particular type of block.
1991 * @param string $blockname the name of the block.
1992 * @return boolean success or failure.
1994 function block_load_class($blockname) {
1997 if(empty($blockname)) {
2001 $classname = 'block_'.$blockname;
2003 if(class_exists($classname)) {
2007 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
2009 if (file_exists($blockpath)) {
2010 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
2011 include_once($blockpath);
2013 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
2017 return class_exists($classname);
2021 * Given a specific page type, return all the page type patterns that might
2024 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2025 * @return array an array of all the page type patterns that might match this page type.
2027 function matching_page_type_patterns($pagetype) {
2028 $patterns = array($pagetype);
2029 $bits = explode('-', $pagetype);
2030 if (count($bits) == 3 && $bits[0] == 'mod') {
2031 if ($bits[2] == 'view') {
2032 $patterns[] = 'mod-*-view';
2033 } else if ($bits[2] == 'index') {
2034 $patterns[] = 'mod-*-index';
2037 while (count($bits) > 0) {
2038 $patterns[] = implode('-', $bits) . '-*';
2046 * Give an specific pattern, return all the page type patterns that would also match it.
2048 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
2049 * @return array of all the page type patterns matching.
2051 function matching_page_type_patterns_from_pattern($pattern) {
2052 $patterns = array($pattern);
2053 if ($pattern === '*') {
2057 // Only keep the part before the star because we will append -* to all the bits.
2058 $star = strpos($pattern, '-*');
2059 if ($star !== false) {
2060 $pattern = substr($pattern, 0, $star);
2063 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
2064 $patterns = array_unique($patterns);
2070 * Given a specific page type, parent context and currect context, return all the page type patterns
2071 * that might be used by this block.
2073 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2074 * @param stdClass $parentcontext Block's parent context
2075 * @param stdClass $currentcontext Current context of block
2076 * @return array an array of all the page type patterns that might match this page type.
2078 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
2079 global $CFG; // Required for includes bellow.
2081 $bits = explode('-', $pagetype);
2083 $core = core_component
::get_core_subsystems();
2084 $plugins = core_component
::get_plugin_types();
2086 //progressively strip pieces off the page type looking for a match
2087 $componentarray = null;
2088 for ($i = count($bits); $i > 0; $i--) {
2089 $possiblecomponentarray = array_slice($bits, 0, $i);
2090 $possiblecomponent = implode('', $possiblecomponentarray);
2092 // Check to see if the component is a core component
2093 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
2094 $libfile = $core[$possiblecomponent].'/lib.php';
2095 if (file_exists($libfile)) {
2096 require_once($libfile);
2097 $function = $possiblecomponent.'_page_type_list';
2098 if (function_exists($function)) {
2099 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2106 //check the plugin directory and look for a callback
2107 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
2109 //We've found a plugin type. Look for a plugin name by getting the next section of page type
2110 if (count($bits) > $i) {
2111 $pluginname = $bits[$i];
2112 $directory = core_component
::get_plugin_directory($possiblecomponent, $pluginname);
2113 if (!empty($directory)){
2114 $libfile = $directory.'/lib.php';
2115 if (file_exists($libfile)) {
2116 require_once($libfile);
2117 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
2118 if (!function_exists($function)) {
2119 $function = $pluginname.'_page_type_list';
2121 if (function_exists($function)) {
2122 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2130 //we'll only get to here if we still don't have any patterns
2131 //the plugin type may have a callback
2132 $directory = $plugins[$possiblecomponent];
2133 $libfile = $directory.'/lib.php';
2134 if (file_exists($libfile)) {
2135 require_once($libfile);
2136 $function = $possiblecomponent.'_page_type_list';
2137 if (function_exists($function)) {
2138 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2146 if (empty($patterns)) {
2147 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
2150 // Ensure that the * pattern is always available if editing block 'at distance', so
2151 // we always can 'bring back' it to the original context. MDL-30340
2152 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
2153 // TODO: We could change the string here, showing its 'bring back' meaning
2154 $patterns['*'] = get_string('page-x', 'pagetype');
2161 * Generates a default page type list when a more appropriate callback cannot be decided upon.
2163 * @param string $pagetype
2164 * @param stdClass $parentcontext
2165 * @param stdClass $currentcontext
2168 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2169 // Generate page type patterns based on current page type if
2170 // callbacks haven't been defined
2171 $patterns = array($pagetype => $pagetype);
2172 $bits = explode('-', $pagetype);
2173 while (count($bits) > 0) {
2174 $pattern = implode('-', $bits) . '-*';
2175 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
2176 // guessing page type description
2177 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
2178 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
2180 $patterns[$pattern] = $pattern;
2184 $patterns['*'] = get_string('page-x', 'pagetype');
2189 * Generates the page type list for the my moodle page
2191 * @param string $pagetype
2192 * @param stdClass $parentcontext
2193 * @param stdClass $currentcontext
2196 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2197 return array('my-index' => get_string('page-my-index', 'pagetype'));
2201 * Generates the page type list for a module by either locating and using the modules callback
2202 * or by generating a default list.
2204 * @param string $pagetype
2205 * @param stdClass $parentcontext
2206 * @param stdClass $currentcontext
2209 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2210 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
2211 if (empty($patterns)) {
2212 // if modules don't have callbacks
2213 // generate two default page type patterns for modules only
2214 $bits = explode('-', $pagetype);
2215 $patterns = array($pagetype => $pagetype);
2216 if ($bits[2] == 'view') {
2217 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
2218 } else if ($bits[2] == 'index') {
2219 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
2224 /// Functions update the blocks if required by the request parameters ==========
2227 * Return a {@link block_contents} representing the add a new block UI, if
2228 * this user is allowed to see it.
2230 * @return block_contents an appropriate block_contents, or null if the user
2231 * cannot add any blocks here.
2233 function block_add_block_ui($page, $output) {
2234 global $CFG, $OUTPUT;
2235 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
2239 $bc = new block_contents();
2240 $bc->title
= get_string('addblock');
2241 $bc->add_class('block_adminblock');
2242 $bc->attributes
['data-block'] = 'adminblock';
2244 $missingblocks = $page->blocks
->get_addable_blocks();
2245 if (empty($missingblocks)) {
2246 $bc->content
= get_string('noblockstoaddhere');
2251 foreach ($missingblocks as $block) {
2252 $menu[$block->name
] = $block->title
;
2255 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
2256 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
2257 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
2258 $bc->content
= $OUTPUT->render($select);
2263 * Actually delete from the database any blocks that are currently on this page,
2264 * but which should not be there according to blocks_name_allowed_in_format.
2266 * @todo Write/Fix this function. Currently returns immediately
2269 function blocks_remove_inappropriate($course) {
2273 $blockmanager = blocks_get_by_page($page);
2275 if (empty($blockmanager)) {
2279 if (($pageformat = $page->pagetype) == NULL) {
2283 foreach($blockmanager as $region) {
2284 foreach($region as $instance) {
2285 $block = blocks_get_record($instance->blockid);
2286 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
2287 blocks_delete_instance($instance->instance);
2294 * Check that a given name is in a permittable format
2296 * @param string $name
2297 * @param string $pageformat
2300 function blocks_name_allowed_in_format($name, $pageformat) {
2303 if (!$bi = block_instance($name)) {
2307 $formats = $bi->applicable_formats();
2311 foreach ($formats as $format => $allowed) {
2312 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2313 $depth = substr_count($format, '-');
2314 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2319 if ($accept === NULL) {
2320 $accept = !empty($formats['all']);
2326 * Delete a block, and associated data.
2328 * @param object $instance a row from the block_instances table
2329 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2330 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2332 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2335 // Allow plugins to use this block before we completely delete it.
2336 if ($pluginsfunction = get_plugins_with_function('pre_block_delete')) {
2337 foreach ($pluginsfunction as $plugintype => $plugins) {
2338 foreach ($plugins as $pluginfunction) {
2339 $pluginfunction($instance);
2344 if ($block = block_instance($instance->blockname
, $instance)) {
2345 $block->instance_delete();
2347 context_helper
::delete_instance(CONTEXT_BLOCK
, $instance->id
);
2349 if (!$skipblockstables) {
2350 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
2351 $DB->delete_records('block_instances', array('id' => $instance->id
));
2352 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
2357 * Delete multiple blocks at once.
2359 * @param array $instanceids A list of block instance ID.
2361 function blocks_delete_instances($instanceids) {
2365 $count = count($instanceids);
2366 $chunks = [$instanceids];
2367 if ($count > $limit) {
2368 $chunks = array_chunk($instanceids, $limit);
2371 // Perform deletion for each chunk.
2372 foreach ($chunks as $chunk) {
2373 $instances = $DB->get_recordset_list('block_instances', 'id', $chunk);
2374 foreach ($instances as $instance) {
2375 blocks_delete_instance($instance, false, true);
2377 $instances->close();
2379 $DB->delete_records_list('block_positions', 'blockinstanceid', $chunk);
2380 $DB->delete_records_list('block_instances', 'id', $chunk);
2382 $preferences = array();
2383 foreach ($chunk as $instanceid) {
2384 $preferences[] = 'block' . $instanceid . 'hidden';
2385 $preferences[] = 'docked_block_instance_' . $instanceid;
2387 $DB->delete_records_list('user_preferences', 'name', $preferences);
2392 * Delete all the blocks that belong to a particular context.
2394 * @param int $contextid the context id.
2396 function blocks_delete_all_for_context($contextid) {
2398 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2399 foreach ($instances as $instance) {
2400 blocks_delete_instance($instance, true);
2402 $instances->close();
2403 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2404 $DB->delete_records('block_positions', array('contextid' => $contextid));
2408 * Set a block to be visible or hidden on a particular page.
2410 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2411 * block_positions table as return by block_manager.
2412 * @param moodle_page $page the back to set the visibility with respect to.
2413 * @param integer $newvisibility 1 for visible, 0 for hidden.
2415 function blocks_set_visibility($instance, $page, $newvisibility) {
2417 if (!empty($instance->blockpositionid
)) {
2418 // Already have local information on this page.
2419 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
2423 // Create a new block_positions record.
2425 $bp->blockinstanceid
= $instance->id
;
2426 $bp->contextid
= $page->context
->id
;
2427 $bp->pagetype
= $page->pagetype
;
2428 if ($page->subpage
) {
2429 $bp->subpage
= $page->subpage
;
2431 $bp->visible
= $newvisibility;
2432 $bp->region
= $instance->defaultregion
;
2433 $bp->weight
= $instance->defaultweight
;
2434 $DB->insert_record('block_positions', $bp);
2438 * Get the block record for a particular blockid - that is, a particular type os block.
2440 * @param $int blockid block type id. If null, an array of all block types is returned.
2441 * @param bool $notusedanymore No longer used.
2442 * @return array|object row from block table, or all rows.
2444 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2446 $blocks = $PAGE->blocks
->get_installed_blocks();
2447 if ($blockid === NULL) {
2449 } else if (isset($blocks[$blockid])) {
2450 return $blocks[$blockid];
2457 * Find a given block by its blockid within a provide array
2459 * @param int $blockid
2460 * @param array $blocksarray
2461 * @return bool|object Instance if found else false
2463 function blocks_find_block($blockid, $blocksarray) {
2464 if (empty($blocksarray)) {
2467 foreach($blocksarray as $blockgroup) {
2468 if (empty($blockgroup)) {
2471 foreach($blockgroup as $instance) {
2472 if($instance->blockid
== $blockid) {
2480 // Functions for programatically adding default blocks to pages ================
2483 * Parse a list of default blocks. See config-dist for a description of the format.
2485 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2486 * @return array the parsed list of default blocks
2488 function blocks_parse_default_blocks_list($blocksstr) {
2490 $bits = explode(':', $blocksstr);
2491 if (!empty($bits)) {
2492 $leftbits = trim(array_shift($bits));
2493 if ($leftbits != '') {
2494 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2497 if (!empty($bits)) {
2498 $rightbits = trim(array_shift($bits));
2499 if ($rightbits != '') {
2500 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2507 * @return array the blocks that should be added to the site course by default.
2509 function blocks_get_default_site_course_blocks() {
2512 if (isset($CFG->defaultblocks_site
)) {
2513 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2516 BLOCK_POS_LEFT
=> array(),
2517 BLOCK_POS_RIGHT
=> array()
2523 * Add the default blocks to a course.
2525 * @param object $course a course object.
2527 function blocks_add_default_course_blocks($course) {
2530 if (isset($CFG->defaultblocks_override
)) {
2531 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2533 } else if ($course->id
== SITEID
) {
2534 $blocknames = blocks_get_default_site_course_blocks();
2536 } else if (isset($CFG->{'defaultblocks_' . $course->format
})) {
2537 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format
});
2540 require_once($CFG->dirroot
. '/course/lib.php');
2541 $blocknames = course_get_format($course)->get_default_blocks();
2545 if ($course->id
== SITEID
) {
2546 $pagetypepattern = 'site-index';
2548 $pagetypepattern = 'course-view-*';
2550 $page = new moodle_page();
2551 $page->set_course($course);
2552 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2556 * Add the default system-context blocks. E.g. the admin tree.
2558 function blocks_add_default_system_blocks() {
2561 $page = new moodle_page();
2562 $page->set_context(context_system
::instance());
2563 // We don't add blocks required by the theme, they will be auto-created.
2564 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2566 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2567 $subpagepattern = $defaultmypage->id
;
2569 $subpagepattern = null;
2572 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2573 $newcontent = array('lp', 'myoverview');
2574 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);