Merge branch 'master_MDL-57324' of git://github.com/danmarsden/moodle
[moodle.git] / lib / blocklib.php
blobe3a386883ea55598329f78ac57e6e5b716a784eb
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
23 * @package core
24 * @subpackage block
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();
31 /**#@+
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');
36 /**#@-*/
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);
53 /**
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
59 * @since Moodle 2.0
61 class block_not_on_page_exception extends moodle_exception {
62 /**
63 * Constructor
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) {
68 $a = new stdClass;
69 $a->instanceid = $instanceid;
70 $a->url = $page->url->out();
71 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
75 /**
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
82 * @since Moodle 2.0
84 class block_manager {
85 /**
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 =========================================================
93 /**
94 * the moodle_page we are managing blocks for.
95 * @var moodle_page
97 protected $page;
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);
117 * @var array
119 protected $birecordsbyregion = null;
122 * array region-name => array(block objects); populated as necessary by
123 * the ensure_instances_exist method.
124 * @var array
126 protected $blockinstances = array();
129 * array region-name => array(block_contents objects) what actually needs to
130 * be displayed in each region.
131 * @var array
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.
138 * @var array
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.
149 * @var integer|null
151 protected $movingblock = null;
154 * Show only fake blocks
156 protected $fakeblocksonly = false;
158 /// Constructor ================================================================
161 * 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) {
167 $this->page = $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;
209 // Lazy load.
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 = self::get_required_by_theme_block_types();
219 $pageformat = $this->page->pagetype;
220 foreach($allblocks as $block) {
221 if (!$bi = block_instance($block->name)) {
222 continue;
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)) {
246 return false;
249 $undeletableblocks = self::get_undeletable_block_types();
250 foreach ($this->blockinstances as $region) {
251 foreach ($region as $instance) {
252 if (empty($instance->instance->blockname)) {
253 continue;
255 if ($instance->instance->blockname == $blockname) {
256 if ($instance->instance->requiredbytheme) {
257 if (!in_array($block->name, $undeletableblocks)) {
258 continue;
261 return true;
265 return false;
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)) {
279 return true;
282 return false;
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)) {
293 return false;
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 * Helper method used by get_content_for_region.
324 * @param string $region region name
325 * @param float $weight weight. May be fractional, since you may want to move a block
326 * between ones with weight 2 and 3, say ($weight would be 2.5).
327 * @return string URL for moving block $this->movingblock to this position.
329 protected function get_move_target_url($region, $weight) {
330 return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
331 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
335 * Determine whether a region contains anything. (Either any real blocks, or
336 * the add new block UI.)
338 * (You may wonder why the $output parameter is required. Unfortunately,
339 * because of the way that blocks work, the only reliable way to find out
340 * if a block will be visible is to get the content for output, and to
341 * get the content, you need a renderer. Fortunately, this is not a
342 * performance problem, because we cache the output that is generated, and
343 * in almost every case where we call region_has_content, we are about to
344 * output the blocks anyway, so we are not doing wasted effort.)
346 * @param string $region a block region that exists on this page.
347 * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
348 * @return boolean Whether there is anything in this region.
350 public function region_has_content($region, $output) {
352 if (!$this->is_known_region($region)) {
353 return false;
355 $this->check_is_loaded();
356 $this->ensure_content_created($region, $output);
357 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
358 // Mark Nielsen's patch - part 1
359 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
360 // If editing is on, we need all the block regions visible, for the
361 // move blocks UI.
362 return true;
364 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
368 * Get an array of all of the installed blocks.
370 * @return array contents of the block table.
372 public function get_installed_blocks() {
373 global $DB;
374 if (is_null($this->allblocks)) {
375 $this->allblocks = $DB->get_records('block');
377 return $this->allblocks;
381 * @return array names of block types that must exist on every page with this theme.
383 public static function get_required_by_theme_block_types() {
384 global $CFG, $PAGE;
385 $requiredbythemeblocks = false;
386 if (isset($PAGE->theme->requiredblocks)) {
387 $requiredbythemeblocks = $PAGE->theme->requiredblocks;
390 if ($requiredbythemeblocks === false) {
391 return array('navigation', 'settings');
392 } else if ($requiredbythemeblocks === '') {
393 return array();
394 } else if (is_string($requiredbythemeblocks)) {
395 return explode(',', $requiredbythemeblocks);
396 } else {
397 return $requiredbythemeblocks;
402 * Make this block type undeletable and unaddable.
404 * @param mixed $blockidorname string or int
406 public static function protect_block($blockidorname) {
407 global $DB;
409 $syscontext = context_system::instance();
411 require_capability('moodle/site:config', $syscontext);
413 $block = false;
414 if (is_int($blockidorname)) {
415 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
416 } else {
417 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
419 $undeletableblocktypes = self::get_undeletable_block_types();
420 if (!in_array($block->name, $undeletableblocktypes)) {
421 $undeletableblocktypes[] = $block->name;
422 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
427 * Make this block type deletable and addable.
429 * @param mixed $blockidorname string or int
431 public static function unprotect_block($blockidorname) {
432 global $DB;
434 $syscontext = context_system::instance();
436 require_capability('moodle/site:config', $syscontext);
438 $block = false;
439 if (is_int($blockidorname)) {
440 $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
441 } else {
442 $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
444 $undeletableblocktypes = self::get_undeletable_block_types();
445 if (in_array($block->name, $undeletableblocktypes)) {
446 $undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name));
447 set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
453 * Get the list of "protected" blocks via admin block manager ui.
455 * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
457 public static function get_undeletable_block_types() {
458 global $CFG, $PAGE;
459 $undeletableblocks = false;
460 if (isset($CFG->undeletableblocktypes)) {
461 $undeletableblocks = $CFG->undeletableblocktypes;
464 if (empty($undeletableblocks)) {
465 return array();
466 } else if (is_string($undeletableblocks)) {
467 return explode(',', $undeletableblocks);
468 } else {
469 return $undeletableblocks;
473 /// Setter methods =============================================================
476 * Add a region to a page
478 * @param string $region add a named region where blocks may appear on the current page.
479 * This is an internal name, like 'side-pre', not a string to display in the UI.
480 * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
482 public function add_region($region, $custom = true) {
483 global $SESSION;
484 $this->check_not_yet_loaded();
485 if ($custom) {
486 if (array_key_exists($region, $this->regions)) {
487 // This here is EXACTLY why we should not be adding block regions into a page. It should
488 // ALWAYS be done in a theme layout.
489 debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
491 // We need to register this custom region against the page type being used.
492 // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
493 $type = $this->page->pagetype;
494 if (!isset($SESSION->custom_block_regions)) {
495 $SESSION->custom_block_regions = array($type => array($region));
496 } else if (!isset($SESSION->custom_block_regions[$type])) {
497 $SESSION->custom_block_regions[$type] = array($region);
498 } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
499 $SESSION->custom_block_regions[$type][] = $region;
502 $this->regions[$region] = 1;
506 * Add an array of regions
507 * @see add_region()
509 * @param array $regions this utility method calls add_region for each array element.
511 public function add_regions($regions, $custom = true) {
512 foreach ($regions as $region) {
513 $this->add_region($region, $custom);
518 * Finds custom block regions associated with a page type and registers them with this block manager.
520 * @param string $pagetype
522 public function add_custom_regions_for_pagetype($pagetype) {
523 global $SESSION;
524 if (isset($SESSION->custom_block_regions[$pagetype])) {
525 foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
526 $this->add_region($customregion, false);
532 * Set the default region for new blocks on the page
534 * @param string $defaultregion the internal names of the region where new
535 * blocks should be added by default, and where any blocks from an
536 * unrecognised region are shown.
538 public function set_default_region($defaultregion) {
539 $this->check_not_yet_loaded();
540 if ($defaultregion) {
541 $this->check_region_is_known($defaultregion);
543 $this->defaultregion = $defaultregion;
547 * Add something that looks like a block, but which isn't an actual block_instance,
548 * to this page.
550 * @param block_contents $bc the content of the block-like thing.
551 * @param string $region a block region that exists on this page.
553 public function add_fake_block($bc, $region) {
554 $this->page->initialise_theme_and_output();
555 if (!$this->is_known_region($region)) {
556 $region = $this->get_default_region();
558 if (array_key_exists($region, $this->visibleblockcontent)) {
559 throw new coding_exception('block_manager has already prepared the blocks in region ' .
560 $region . 'for output. It is too late to add a fake block.');
562 if (!isset($bc->attributes['data-block'])) {
563 $bc->attributes['data-block'] = '_fake';
565 $bc->attributes['class'] .= ' block_fake';
566 $this->extracontent[$region][] = $bc;
570 * Checks to see whether all of the blocks within the given region are docked
572 * @see region_uses_dock
573 * @param string $region
574 * @return bool True if all of the blocks within that region are docked
576 public function region_completely_docked($region, $output) {
577 global $CFG;
578 // If theme doesn't allow docking or allowblockstodock is not set, then return.
579 if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
580 return false;
583 // Do not dock the region when the user attemps to move a block.
584 if ($this->movingblock) {
585 return false;
588 // Block regions should not be docked during editing when all the blocks are hidden.
589 if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
590 return false;
593 $this->check_is_loaded();
594 $this->ensure_content_created($region, $output);
595 if (!$this->region_has_content($region, $output)) {
596 // If the region has no content then nothing is docked at all of course.
597 return false;
599 foreach ($this->visibleblockcontent[$region] as $instance) {
600 if (!get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
601 return false;
604 return true;
608 * Checks to see whether any of the blocks within the given regions are docked
610 * @see region_completely_docked
611 * @param array|string $regions array of regions (or single region)
612 * @return bool True if any of the blocks within that region are docked
614 public function region_uses_dock($regions, $output) {
615 if (!$this->page->theme->enable_dock) {
616 return false;
618 $this->check_is_loaded();
619 foreach((array)$regions as $region) {
620 $this->ensure_content_created($region, $output);
621 foreach($this->visibleblockcontent[$region] as $instance) {
622 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
623 return true;
627 return false;
630 /// Actions ====================================================================
633 * This method actually loads the blocks for our page from the database.
635 * @param boolean|null $includeinvisible
636 * null (default) - load hidden blocks if $this->page->user_is_editing();
637 * true - load hidden blocks.
638 * false - don't load hidden blocks.
640 public function load_blocks($includeinvisible = null) {
641 global $DB, $CFG;
643 if (!is_null($this->birecordsbyregion)) {
644 // Already done.
645 return;
648 if ($CFG->version < 2009050619) {
649 // Upgrade/install not complete. Don't try too show any blocks.
650 $this->birecordsbyregion = array();
651 return;
654 // Ensure we have been initialised.
655 if (is_null($this->defaultregion)) {
656 $this->page->initialise_theme_and_output();
657 // If there are still no block regions, then there are no blocks on this page.
658 if (empty($this->regions)) {
659 $this->birecordsbyregion = array();
660 return;
664 // Check if we need to load normal blocks
665 if ($this->fakeblocksonly) {
666 $this->birecordsbyregion = $this->prepare_per_region_arrays();
667 return;
670 // Exclude auto created blocks if they are not undeletable in this theme.
671 $requiredbytheme = $this->get_required_by_theme_block_types();
672 $requiredbythemecheck = '';
673 $requiredbythemeparams = array();
674 $requiredbythemenotparams = array();
675 if (!empty($requiredbytheme)) {
676 list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED, 'requiredbytheme');
677 list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED,
678 'notrequiredbytheme', false);
679 $requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
680 ' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
681 } else {
682 $requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
685 if (is_null($includeinvisible)) {
686 $includeinvisible = $this->page->user_is_editing();
688 if ($includeinvisible) {
689 $visiblecheck = '';
690 } else {
691 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
694 $context = $this->page->context;
695 $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
696 $parentcontextparams = array();
697 $parentcontextids = $context->get_parent_context_ids();
698 if ($parentcontextids) {
699 list($parentcontexttest, $parentcontextparams) =
700 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
701 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
704 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
705 list($pagetypepatterntest, $pagetypepatternparams) =
706 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
708 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
709 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
711 $systemcontext = context_system::instance();
712 $params = array(
713 'contextlevel' => CONTEXT_BLOCK,
714 'subpage1' => $this->page->subpage,
715 'subpage2' => $this->page->subpage,
716 'contextid1' => $context->id,
717 'contextid2' => $context->id,
718 'contextid3' => $systemcontext->id,
719 'pagetype' => $this->page->pagetype,
721 if ($this->page->subpage === '') {
722 $params['subpage1'] = '';
723 $params['subpage2'] = '';
725 $sql = "SELECT
726 bi.id,
727 bp.id AS blockpositionid,
728 bi.blockname,
729 bi.parentcontextid,
730 bi.showinsubcontexts,
731 bi.pagetypepattern,
732 bi.requiredbytheme,
733 bi.subpagepattern,
734 bi.defaultregion,
735 bi.defaultweight,
736 COALESCE(bp.visible, 1) AS visible,
737 COALESCE(bp.region, bi.defaultregion) AS region,
738 COALESCE(bp.weight, bi.defaultweight) AS weight,
739 bi.configdata
740 $ccselect
742 FROM {block_instances} bi
743 JOIN {block} b ON bi.blockname = b.name
744 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
745 AND bp.contextid = :contextid1
746 AND bp.pagetype = :pagetype
747 AND bp.subpage = :subpage1
748 $ccjoin
750 WHERE
751 $contexttest
752 AND bi.pagetypepattern $pagetypepatterntest
753 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
754 $visiblecheck
755 AND b.visible = 1
756 $requiredbythemecheck
758 ORDER BY
759 COALESCE(bp.region, bi.defaultregion),
760 COALESCE(bp.weight, bi.defaultweight),
761 bi.id";
763 $allparams = $params + $parentcontextparams + $pagetypepatternparams + $requiredbythemeparams + $requiredbythemenotparams;
764 $blockinstances = $DB->get_recordset_sql($sql, $allparams);
766 $this->birecordsbyregion = $this->prepare_per_region_arrays();
767 $unknown = array();
768 foreach ($blockinstances as $bi) {
769 context_helper::preload_from_record($bi);
770 if ($this->is_known_region($bi->region)) {
771 $this->birecordsbyregion[$bi->region][] = $bi;
772 } else {
773 $unknown[] = $bi;
777 // Pages don't necessarily have a defaultregion. The one time this can
778 // happen is when there are no theme block regions, but the script itself
779 // has a block region in the main content area.
780 if (!empty($this->defaultregion)) {
781 $this->birecordsbyregion[$this->defaultregion] =
782 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
787 * Add a block to the current page, or related pages. The block is added to
788 * context $this->page->contextid. If $pagetypepattern $subpagepattern
790 * @param string $blockname The type of block to add.
791 * @param string $region the block region on this page to add the block to.
792 * @param integer $weight determines the order where this block appears in the region.
793 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
794 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
795 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
797 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
798 global $DB;
799 // Allow invisible blocks because this is used when adding default page blocks, which
800 // might include invisible ones if the user makes some default blocks invisible
801 $this->check_known_block_type($blockname, true);
802 $this->check_region_is_known($region);
804 if (empty($pagetypepattern)) {
805 $pagetypepattern = $this->page->pagetype;
808 $blockinstance = new stdClass;
809 $blockinstance->blockname = $blockname;
810 $blockinstance->parentcontextid = $this->page->context->id;
811 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
812 $blockinstance->pagetypepattern = $pagetypepattern;
813 $blockinstance->subpagepattern = $subpagepattern;
814 $blockinstance->defaultregion = $region;
815 $blockinstance->defaultweight = $weight;
816 $blockinstance->configdata = '';
817 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
819 // Ensure the block context is created.
820 context_block::instance($blockinstance->id);
822 // If the new instance was created, allow it to do additional setup
823 if ($block = block_instance($blockname, $blockinstance)) {
824 $block->instance_create();
828 public function add_block_at_end_of_default_region($blockname) {
829 if (empty($this->birecordsbyregion)) {
830 // No blocks or block regions exist yet.
831 return;
833 $defaulregion = $this->get_default_region();
835 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
836 if ($lastcurrentblock) {
837 $weight = $lastcurrentblock->weight + 1;
838 } else {
839 $weight = 0;
842 if ($this->page->subpage) {
843 $subpage = $this->page->subpage;
844 } else {
845 $subpage = null;
848 // Special case. Course view page type include the course format, but we
849 // want to add the block non-format-specifically.
850 $pagetypepattern = $this->page->pagetype;
851 if (strpos($pagetypepattern, 'course-view') === 0) {
852 $pagetypepattern = 'course-view-*';
855 // We should end using this for ALL the blocks, making always the 1st option
856 // the default one to be used. Until then, this is one hack to avoid the
857 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
858 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
859 // (the FIRST $pagetypepattern will be set)
861 // We are applying it to all blocks created in mod pages for now and only if the
862 // default pagetype is not one of the available options
863 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
864 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
865 // Only go for the first if the pagetype is not a valid option
866 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
867 $pagetypepattern = key($pagetypelist);
870 // Surely other pages like course-report will need this too, they just are not important
871 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
873 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
877 * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
878 * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
879 * and incremented by the position of the block in the $blocks array
881 * @param array $blocks array with array keys the region names, and values an array of block names.
882 * @param string $pagetypepattern optional. Passed to {@link add_block()}
883 * @param string $subpagepattern optional. Passed to {@link add_block()}
884 * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
885 * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
887 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
888 $initialweight = $weight;
889 $this->add_regions(array_keys($blocks), false);
890 foreach ($blocks as $region => $regionblocks) {
891 foreach ($regionblocks as $offset => $blockname) {
892 $weight = $initialweight + $offset;
893 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
899 * Move a block to a new position on this page.
901 * If this block cannot appear on any other pages, then we change defaultposition/weight
902 * in the block_instances table. Otherwise we just set the position on this page.
904 * @param $blockinstanceid the block instance id.
905 * @param $newregion the new region name.
906 * @param $newweight the new weight.
908 public function reposition_block($blockinstanceid, $newregion, $newweight) {
909 global $DB;
911 $this->check_region_is_known($newregion);
912 $inst = $this->find_instance($blockinstanceid);
914 $bi = $inst->instance;
915 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
916 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
917 (!$this->page->subpage || $bi->subpagepattern)) {
919 // Set default position
920 $newbi = new stdClass;
921 $newbi->id = $bi->id;
922 $newbi->defaultregion = $newregion;
923 $newbi->defaultweight = $newweight;
924 $DB->update_record('block_instances', $newbi);
926 if ($bi->blockpositionid) {
927 $bp = new stdClass;
928 $bp->id = $bi->blockpositionid;
929 $bp->region = $newregion;
930 $bp->weight = $newweight;
931 $DB->update_record('block_positions', $bp);
934 } else {
935 // Just set position on this page.
936 $bp = new stdClass;
937 $bp->region = $newregion;
938 $bp->weight = $newweight;
940 if ($bi->blockpositionid) {
941 $bp->id = $bi->blockpositionid;
942 $DB->update_record('block_positions', $bp);
944 } else {
945 $bp->blockinstanceid = $bi->id;
946 $bp->contextid = $this->page->context->id;
947 $bp->pagetype = $this->page->pagetype;
948 if ($this->page->subpage) {
949 $bp->subpage = $this->page->subpage;
950 } else {
951 $bp->subpage = '';
953 $bp->visible = $bi->visible;
954 $DB->insert_record('block_positions', $bp);
960 * Find a given block by its instance id
962 * @param integer $instanceid
963 * @return block_base
965 public function find_instance($instanceid) {
966 foreach ($this->regions as $region => $notused) {
967 $this->ensure_instances_exist($region);
968 foreach($this->blockinstances[$region] as $instance) {
969 if ($instance->instance->id == $instanceid) {
970 return $instance;
974 throw new block_not_on_page_exception($instanceid, $this->page);
977 /// Inner workings =============================================================
980 * Check whether the page blocks have been loaded yet
982 * @return void Throws coding exception if already loaded
984 protected function check_not_yet_loaded() {
985 if (!is_null($this->birecordsbyregion)) {
986 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.');
991 * Check whether the page blocks have been loaded yet
993 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
995 * @return void Throws coding exception if already loaded
997 protected function check_is_loaded() {
998 if (is_null($this->birecordsbyregion)) {
999 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
1004 * Check if a block type is known and usable
1006 * @param string $blockname The block type name to search for
1007 * @param bool $includeinvisible Include disabled block types in the initial pass
1008 * @return void Coding Exception thrown if unknown or not enabled
1010 protected function check_known_block_type($blockname, $includeinvisible = false) {
1011 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
1012 if ($this->is_known_block_type($blockname, true)) {
1013 throw new coding_exception('Unknown block type ' . $blockname);
1014 } else {
1015 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
1021 * Check if a region is known by its name
1023 * @param string $region
1024 * @return void Coding Exception thrown if the region is not known
1026 protected function check_region_is_known($region) {
1027 if (!$this->is_known_region($region)) {
1028 throw new coding_exception('Trying to reference an unknown block region ' . $region);
1033 * Returns an array of region names as keys and nested arrays for values
1035 * @return array an array where the array keys are the region names, and the array
1036 * values are empty arrays.
1038 protected function prepare_per_region_arrays() {
1039 $result = array();
1040 foreach ($this->regions as $region => $notused) {
1041 $result[$region] = array();
1043 return $result;
1047 * Create a set of new block instance from a record array
1049 * @param array $birecords An array of block instance records
1050 * @return array An array of instantiated block_instance objects
1052 protected function create_block_instances($birecords) {
1053 $results = array();
1054 foreach ($birecords as $record) {
1055 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
1056 $results[] = $blockobject;
1059 return $results;
1063 * Create all the block instances for all the blocks that were loaded by
1064 * load_blocks. This is used, for example, to ensure that all blocks get a
1065 * chance to initialise themselves via the {@link block_base::specialize()}
1066 * method, before any output is done.
1068 * It is also used to create any blocks that are "requiredbytheme" by the current theme.
1069 * These blocks that are auto-created have requiredbytheme set on the block instance
1070 * so they are only visible on themes that require them.
1072 public function create_all_block_instances() {
1073 global $PAGE;
1074 $missing = false;
1076 // If there are any un-removable blocks that were not created - force them.
1077 $requiredbytheme = $this->get_required_by_theme_block_types();
1078 if (!$this->fakeblocksonly) {
1079 foreach ($requiredbytheme as $forced) {
1080 if (empty($forced)) {
1081 continue;
1083 $found = false;
1084 foreach ($this->get_regions() as $region) {
1085 foreach($this->birecordsbyregion[$region] as $instance) {
1086 if ($instance->blockname == $forced) {
1087 $found = true;
1091 if (!$found) {
1092 $this->add_block_required_by_theme($forced);
1093 $missing = true;
1098 if ($missing) {
1099 // Some blocks were missing. Lets do it again.
1100 $this->birecordsbyregion = null;
1101 $this->load_blocks();
1103 foreach ($this->get_regions() as $region) {
1104 $this->ensure_instances_exist($region);
1110 * Add a block that is required by the current theme but has not been
1111 * created yet. This is a special type of block that only shows in themes that
1112 * require it (by listing it in undeletable_block_types).
1114 * @param string $blockname the name of the block type.
1116 protected function add_block_required_by_theme($blockname) {
1117 global $DB;
1119 if (empty($this->birecordsbyregion)) {
1120 // No blocks or block regions exist yet.
1121 return;
1124 // Never auto create blocks when we are showing fake blocks only.
1125 if ($this->fakeblocksonly) {
1126 return;
1129 // Never add a duplicate block required by theme.
1130 if ($DB->record_exists('block_instances', array('blockname' => $blockname, 'requiredbytheme' => 1))) {
1131 return;
1134 $systemcontext = context_system::instance();
1135 $defaultregion = $this->get_default_region();
1136 // Add a special system wide block instance only for themes that require it.
1137 $blockinstance = new stdClass;
1138 $blockinstance->blockname = $blockname;
1139 $blockinstance->parentcontextid = $systemcontext->id;
1140 $blockinstance->showinsubcontexts = true;
1141 $blockinstance->requiredbytheme = true;
1142 $blockinstance->pagetypepattern = '*';
1143 $blockinstance->subpagepattern = null;
1144 $blockinstance->defaultregion = $defaultregion;
1145 $blockinstance->defaultweight = 0;
1146 $blockinstance->configdata = '';
1147 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
1149 // Ensure the block context is created.
1150 context_block::instance($blockinstance->id);
1152 // If the new instance was created, allow it to do additional setup.
1153 if ($block = block_instance($blockname, $blockinstance)) {
1154 $block->instance_create();
1159 * Return an array of content objects from a set of block instances
1161 * @param array $instances An array of block instances
1162 * @param renderer_base The renderer to use.
1163 * @param string $region the region name.
1164 * @return array An array of block_content (and possibly block_move_target) objects.
1166 protected function create_block_contents($instances, $output, $region) {
1167 $results = array();
1169 $lastweight = 0;
1170 $lastblock = 0;
1171 if ($this->movingblock) {
1172 $first = reset($instances);
1173 if ($first) {
1174 $lastweight = $first->instance->weight - 2;
1178 foreach ($instances as $instance) {
1179 $content = $instance->get_content_for_output($output);
1180 if (empty($content)) {
1181 continue;
1184 if ($this->movingblock && $lastweight != $instance->instance->weight &&
1185 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
1186 $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
1189 if ($content->blockinstanceid == $this->movingblock) {
1190 $content->add_class('beingmoved');
1191 $content->annotation .= get_string('movingthisblockcancel', 'block',
1192 html_writer::link($this->page->url, get_string('cancel')));
1195 $results[] = $content;
1196 $lastweight = $instance->instance->weight;
1197 $lastblock = $instance->instance->id;
1200 if ($this->movingblock && $lastblock != $this->movingblock) {
1201 $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
1203 return $results;
1207 * Ensure block instances exist for a given region
1209 * @param string $region Check for bi's with the instance with this name
1211 protected function ensure_instances_exist($region) {
1212 $this->check_region_is_known($region);
1213 if (!array_key_exists($region, $this->blockinstances)) {
1214 $this->blockinstances[$region] =
1215 $this->create_block_instances($this->birecordsbyregion[$region]);
1220 * Ensure that there is some content within the given region
1222 * @param string $region The name of the region to check
1224 public function ensure_content_created($region, $output) {
1225 $this->ensure_instances_exist($region);
1226 if (!array_key_exists($region, $this->visibleblockcontent)) {
1227 $contents = array();
1228 if (array_key_exists($region, $this->extracontent)) {
1229 $contents = $this->extracontent[$region];
1231 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1232 if (($region == $this->defaultregion) && (!isset($this->page->theme->addblockposition) ||
1233 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_DEFAULT)) {
1234 $addblockui = block_add_block_ui($this->page, $output);
1235 if ($addblockui) {
1236 $contents[] = $addblockui;
1239 $this->visibleblockcontent[$region] = $contents;
1243 /// Process actions from the URL ===============================================
1246 * Get the appropriate list of editing icons for a block. This is used
1247 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1249 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1250 * @return an array in the format for {@link block_contents::$controls}
1252 public function edit_controls($block) {
1253 global $CFG;
1255 $controls = array();
1256 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1257 $blocktitle = $block->title;
1258 if (empty($blocktitle)) {
1259 $blocktitle = $block->arialabel;
1262 if ($this->page->user_can_edit_blocks()) {
1263 // Move icon.
1264 $str = new lang_string('moveblock', 'block', $blocktitle);
1265 $controls[] = new action_menu_link_primary(
1266 new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1267 new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1268 $str,
1269 array('class' => 'editing_move')
1274 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1275 // Edit config icon - always show - needed for positioning UI.
1276 $str = new lang_string('configureblock', 'block', $blocktitle);
1277 $controls[] = new action_menu_link_secondary(
1278 new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1279 new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1280 $str,
1281 array('class' => 'editing_edit')
1286 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1287 // Show/hide icon.
1288 if ($block->instance->visible) {
1289 $str = new lang_string('hideblock', 'block', $blocktitle);
1290 $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1291 $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1292 $attributes = array('class' => 'editing_hide');
1293 } else {
1294 $str = new lang_string('showblock', 'block', $blocktitle);
1295 $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1296 $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1297 $attributes = array('class' => 'editing_show');
1299 $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1302 // Assign roles.
1303 if (get_assignable_roles($block->context, ROLENAME_SHORT)) {
1304 $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id,
1305 'returnurl' => $this->page->url->out_as_local_url()));
1306 $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1307 $controls[] = new action_menu_link_secondary(
1308 $rolesurl,
1309 new pix_icon('i/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1310 $str, array('class' => 'editing_assignroles')
1314 // Permissions.
1315 if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) {
1316 $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id,
1317 'returnurl' => $this->page->url->out_as_local_url()));
1318 $str = get_string('permissions', 'role');
1319 $controls[] = new action_menu_link_secondary(
1320 $rolesurl,
1321 new pix_icon('i/permissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1322 $str, array('class' => 'editing_permissions')
1326 // Change permissions.
1327 if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) {
1328 $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id,
1329 'returnurl' => $this->page->url->out_as_local_url()));
1330 $str = get_string('checkpermissions', 'role');
1331 $controls[] = new action_menu_link_secondary(
1332 $rolesurl,
1333 new pix_icon('i/checkpermissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1334 $str, array('class' => 'editing_checkroles')
1338 if ($this->user_can_delete_block($block)) {
1339 // Delete icon.
1340 $str = new lang_string('deleteblock', 'block', $blocktitle);
1341 $controls[] = new action_menu_link_secondary(
1342 new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1343 new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1344 $str,
1345 array('class' => 'editing_delete')
1349 return $controls;
1353 * @param block_base $block a block that appears on this page.
1354 * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1356 protected function user_can_delete_block($block) {
1357 return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1358 $block->user_can_addto($this->page) &&
1359 !in_array($block->instance->blockname, self::get_undeletable_block_types()) &&
1360 !in_array($block->instance->blockname, self::get_required_by_theme_block_types());
1364 * Process any block actions that were specified in the URL.
1366 * @return boolean true if anything was done. False if not.
1368 public function process_url_actions() {
1369 if (!$this->page->user_is_editing()) {
1370 return false;
1372 return $this->process_url_add() || $this->process_url_delete() ||
1373 $this->process_url_show_hide() || $this->process_url_edit() ||
1374 $this->process_url_move();
1378 * Handle adding a block.
1379 * @return boolean true if anything was done. False if not.
1381 public function process_url_add() {
1382 global $CFG, $PAGE, $OUTPUT;
1384 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1385 if ($blocktype === null) {
1386 return false;
1389 require_sesskey();
1391 if (!$this->page->user_can_edit_blocks()) {
1392 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1395 $addableblocks = $this->get_addable_blocks();
1397 if ($blocktype === '') {
1398 // Display add block selection.
1399 $addpage = new moodle_page();
1400 $addpage->set_pagelayout('admin');
1401 $addpage->blocks->show_only_fake_blocks(true);
1402 $addpage->set_course($this->page->course);
1403 $addpage->set_context($this->page->context);
1404 if ($this->page->cm) {
1405 $addpage->set_cm($this->page->cm);
1408 $addpagebase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1409 $addpageparams = $this->page->url->params();
1410 $addpage->set_url($addpagebase, $addpageparams);
1411 $addpage->set_block_actions_done();
1412 // At this point we are going to display the block selector, overwrite global $PAGE ready for this.
1413 $PAGE = $addpage;
1414 // Some functions use $OUTPUT so we need to replace that too.
1415 $OUTPUT = $addpage->get_renderer('core');
1417 $site = get_site();
1418 $straddblock = get_string('addblock');
1420 $PAGE->navbar->add($straddblock);
1421 $PAGE->set_title($straddblock);
1422 $PAGE->set_heading($site->fullname);
1423 echo $OUTPUT->header();
1424 echo $OUTPUT->heading($straddblock);
1426 if (!$addableblocks) {
1427 echo $OUTPUT->box(get_string('noblockstoaddhere'));
1428 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('back')), 'm-x-3 m-b-1');
1429 } else {
1430 $url = new moodle_url($addpage->url, array('sesskey' => sesskey()));
1431 echo $OUTPUT->render_from_template('core/add_block_body',
1432 ['blocks' => array_values($addableblocks),
1433 'url' => '?' . $url->get_query_string(false)]);
1434 echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('cancel')), 'm-x-3 m-b-1');
1437 echo $OUTPUT->footer();
1438 // Make sure that nothing else happens after we have displayed this form.
1439 exit;
1442 if (!array_key_exists($blocktype, $addableblocks)) {
1443 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1446 $this->add_block_at_end_of_default_region($blocktype);
1448 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1449 $this->page->ensure_param_not_in_url('bui_addblock');
1451 return true;
1455 * Handle deleting a block.
1456 * @return boolean true if anything was done. False if not.
1458 public function process_url_delete() {
1459 global $CFG, $PAGE, $OUTPUT;
1461 $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1462 $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1464 if (!$blockid) {
1465 return false;
1468 require_sesskey();
1469 $block = $this->page->blocks->find_instance($blockid);
1470 if (!$this->user_can_delete_block($block)) {
1471 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1474 if (!$confirmdelete) {
1475 $deletepage = new moodle_page();
1476 $deletepage->set_pagelayout('admin');
1477 $deletepage->blocks->show_only_fake_blocks(true);
1478 $deletepage->set_course($this->page->course);
1479 $deletepage->set_context($this->page->context);
1480 if ($this->page->cm) {
1481 $deletepage->set_cm($this->page->cm);
1484 $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1485 $deleteurlparams = $this->page->url->params();
1486 $deletepage->set_url($deleteurlbase, $deleteurlparams);
1487 $deletepage->set_block_actions_done();
1488 // At this point we are either going to redirect, or display the form, so
1489 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1490 $PAGE = $deletepage;
1491 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1492 $output = $deletepage->get_renderer('core');
1493 $OUTPUT = $output;
1495 $site = get_site();
1496 $blocktitle = $block->get_title();
1497 $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1498 $message = get_string('deleteblockcheck', 'block', $blocktitle);
1500 // If the block is being shown in sub contexts display a warning.
1501 if ($block->instance->showinsubcontexts == 1) {
1502 $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1503 $systemcontext = context_system::instance();
1504 $messagestring = new stdClass();
1505 $messagestring->location = $parentcontext->get_context_name();
1507 // Checking for blocks that may have visibility on the front page and pages added on that.
1508 if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1509 $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1510 } else {
1511 $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1512 $messagestring->pagetype = $block->instance->pagetypepattern;
1513 if (isset($pagetypes[$block->instance->pagetypepattern])) {
1514 $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1518 $message = get_string('deleteblockwarning', 'block', $messagestring);
1521 $PAGE->navbar->add($strdeletecheck);
1522 $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1523 $PAGE->set_heading($site->fullname);
1524 echo $OUTPUT->header();
1525 $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1526 $cancelurl = new moodle_url($deletepage->url);
1527 $yesbutton = new single_button($confirmurl, get_string('yes'));
1528 $nobutton = new single_button($cancelurl, get_string('no'));
1529 echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1530 echo $OUTPUT->footer();
1531 // Make sure that nothing else happens after we have displayed this form.
1532 exit;
1533 } else {
1534 blocks_delete_instance($block->instance);
1535 // bui_deleteid and bui_confirm should not be in the PAGE url.
1536 $this->page->ensure_param_not_in_url('bui_deleteid');
1537 $this->page->ensure_param_not_in_url('bui_confirm');
1538 return true;
1543 * Handle showing or hiding a block.
1544 * @return boolean true if anything was done. False if not.
1546 public function process_url_show_hide() {
1547 if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1548 $newvisibility = 0;
1549 } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1550 $newvisibility = 1;
1551 } else {
1552 return false;
1555 require_sesskey();
1557 $block = $this->page->blocks->find_instance($blockid);
1559 if (!$this->page->user_can_edit_blocks()) {
1560 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1561 } else if (!$block->instance_can_be_hidden()) {
1562 return false;
1565 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1567 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1568 $this->page->ensure_param_not_in_url('bui_hideid');
1569 $this->page->ensure_param_not_in_url('bui_showid');
1571 return true;
1575 * Handle showing/processing the submission from the block editing form.
1576 * @return boolean true if the form was submitted and the new config saved. Does not
1577 * return if the editing form was displayed. False otherwise.
1579 public function process_url_edit() {
1580 global $CFG, $DB, $PAGE, $OUTPUT;
1582 $blockid = optional_param('bui_editid', null, PARAM_INT);
1583 if (!$blockid) {
1584 return false;
1587 require_sesskey();
1588 require_once($CFG->dirroot . '/blocks/edit_form.php');
1590 $block = $this->find_instance($blockid);
1592 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1593 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1596 $editpage = new moodle_page();
1597 $editpage->set_pagelayout('admin');
1598 $editpage->blocks->show_only_fake_blocks(true);
1599 $editpage->set_course($this->page->course);
1600 //$editpage->set_context($block->context);
1601 $editpage->set_context($this->page->context);
1602 if ($this->page->cm) {
1603 $editpage->set_cm($this->page->cm);
1605 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1606 $editurlparams = $this->page->url->params();
1607 $editurlparams['bui_editid'] = $blockid;
1608 $editpage->set_url($editurlbase, $editurlparams);
1609 $editpage->set_block_actions_done();
1610 // At this point we are either going to redirect, or display the form, so
1611 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1612 $PAGE = $editpage;
1613 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1614 $output = $editpage->get_renderer('core');
1615 $OUTPUT = $output;
1617 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1618 if (is_readable($formfile)) {
1619 require_once($formfile);
1620 $classname = 'block_' . $block->name() . '_edit_form';
1621 if (!class_exists($classname)) {
1622 $classname = 'block_edit_form';
1624 } else {
1625 $classname = 'block_edit_form';
1628 $mform = new $classname($editpage->url, $block, $this->page);
1629 $mform->set_data($block->instance);
1631 if ($mform->is_cancelled()) {
1632 redirect($this->page->url);
1634 } else if ($data = $mform->get_data()) {
1635 $bi = new stdClass;
1636 $bi->id = $block->instance->id;
1638 // This may get overwritten by the special case handling below.
1639 $bi->pagetypepattern = $data->bui_pagetypepattern;
1640 $bi->showinsubcontexts = (bool) $data->bui_contexts;
1641 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1642 $bi->subpagepattern = null;
1643 } else {
1644 $bi->subpagepattern = $data->bui_subpagepattern;
1647 $systemcontext = context_system::instance();
1648 $frontpagecontext = context_course::instance(SITEID);
1649 $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1651 // Updating stickiness and contexts. See MDL-21375 for details.
1652 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1654 // Explicitly set the default context
1655 $bi->parentcontextid = $parentcontext->id;
1657 if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
1659 // The interface here is a special case because the pagetype pattern is
1660 // totally derived from the context menu. Here are the excpetions. MDL-30340
1662 switch ($data->bui_contexts) {
1663 case BUI_CONTEXTS_ENTIRE_SITE:
1664 // The user wants to show the block across the entire site
1665 $bi->parentcontextid = $systemcontext->id;
1666 $bi->showinsubcontexts = true;
1667 $bi->pagetypepattern = '*';
1668 break;
1669 case BUI_CONTEXTS_FRONTPAGE_SUBS:
1670 // The user wants the block shown on the front page and all subcontexts
1671 $bi->parentcontextid = $frontpagecontext->id;
1672 $bi->showinsubcontexts = true;
1673 $bi->pagetypepattern = '*';
1674 break;
1675 case BUI_CONTEXTS_FRONTPAGE_ONLY:
1676 // The user want to show the front page on the frontpage only
1677 $bi->parentcontextid = $frontpagecontext->id;
1678 $bi->showinsubcontexts = false;
1679 $bi->pagetypepattern = 'site-index';
1680 // This is the only relevant page type anyway but we'll set it explicitly just
1681 // in case the front page grows site-index-* subpages of its own later
1682 break;
1687 $bits = explode('-', $bi->pagetypepattern);
1688 // hacks for some contexts
1689 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1690 // For course context
1691 // is page type pattern is mod-*, change showinsubcontext to 1
1692 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1693 $bi->showinsubcontexts = 1;
1694 } else {
1695 $bi->showinsubcontexts = 0;
1697 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1698 // for user context
1699 // subpagepattern should be null
1700 if ($bits[0] == 'user' or $bits[0] == 'my') {
1701 // we don't need subpagepattern in usercontext
1702 $bi->subpagepattern = null;
1706 $bi->defaultregion = $data->bui_defaultregion;
1707 $bi->defaultweight = $data->bui_defaultweight;
1708 $DB->update_record('block_instances', $bi);
1710 if (!empty($block->config)) {
1711 $config = clone($block->config);
1712 } else {
1713 $config = new stdClass;
1715 foreach ($data as $configfield => $value) {
1716 if (strpos($configfield, 'config_') !== 0) {
1717 continue;
1719 $field = substr($configfield, 7);
1720 $config->$field = $value;
1722 $block->instance_config_save($config);
1724 $bp = new stdClass;
1725 $bp->visible = $data->bui_visible;
1726 $bp->region = $data->bui_region;
1727 $bp->weight = $data->bui_weight;
1728 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1729 $data->bui_weight != $data->bui_defaultweight;
1731 if ($block->instance->blockpositionid && !$needbprecord) {
1732 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1734 } else if ($block->instance->blockpositionid && $needbprecord) {
1735 $bp->id = $block->instance->blockpositionid;
1736 $DB->update_record('block_positions', $bp);
1738 } else if ($needbprecord) {
1739 $bp->blockinstanceid = $block->instance->id;
1740 $bp->contextid = $this->page->context->id;
1741 $bp->pagetype = $this->page->pagetype;
1742 if ($this->page->subpage) {
1743 $bp->subpage = $this->page->subpage;
1744 } else {
1745 $bp->subpage = '';
1747 $DB->insert_record('block_positions', $bp);
1750 redirect($this->page->url);
1752 } else {
1753 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1754 $editpage->set_title($strheading);
1755 $editpage->set_heading($strheading);
1756 $bits = explode('-', $this->page->pagetype);
1757 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1758 // better navbar for tag pages
1759 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1760 $tag = core_tag_tag::get($this->page->subpage);
1761 // tag search page doesn't have subpageid
1762 if ($tag) {
1763 $editpage->navbar->add($tag->get_display_name(), $tag->get_view_url());
1766 $editpage->navbar->add($block->get_title());
1767 $editpage->navbar->add(get_string('configuration'));
1768 echo $output->header();
1769 echo $output->heading($strheading, 2);
1770 $mform->display();
1771 echo $output->footer();
1772 exit;
1777 * Handle showing/processing the submission from the block editing form.
1778 * @return boolean true if the form was submitted and the new config saved. Does not
1779 * return if the editing form was displayed. False otherwise.
1781 public function process_url_move() {
1782 global $CFG, $DB, $PAGE;
1784 $blockid = optional_param('bui_moveid', null, PARAM_INT);
1785 if (!$blockid) {
1786 return false;
1789 require_sesskey();
1791 $block = $this->find_instance($blockid);
1793 if (!$this->page->user_can_edit_blocks()) {
1794 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1797 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1798 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1799 if (!$newregion || is_null($newweight)) {
1800 // Don't have a valid target position yet, must be just starting the move.
1801 $this->movingblock = $blockid;
1802 $this->page->ensure_param_not_in_url('bui_moveid');
1803 return false;
1806 if (!$this->is_known_region($newregion)) {
1807 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1810 // Move this block. This may involve moving other nearby blocks.
1811 $blocks = $this->birecordsbyregion[$newregion];
1813 $maxweight = self::MAX_WEIGHT;
1814 $minweight = -self::MAX_WEIGHT;
1816 // Initialise the used weights and spareweights array with the default values
1817 $spareweights = array();
1818 $usedweights = array();
1819 for ($i = $minweight; $i <= $maxweight; $i++) {
1820 $spareweights[$i] = $i;
1821 $usedweights[$i] = array();
1824 // Check each block and sort out where we have used weights
1825 foreach ($blocks as $bi) {
1826 if ($bi->weight > $maxweight) {
1827 // If this statement is true then the blocks weight is more than the
1828 // current maximum. To ensure that we can get the best block position
1829 // we will initialise elements within the usedweights and spareweights
1830 // arrays between the blocks weight (which will then be the new max) and
1831 // the current max
1832 $parseweight = $bi->weight;
1833 while (!array_key_exists($parseweight, $usedweights)) {
1834 $usedweights[$parseweight] = array();
1835 $spareweights[$parseweight] = $parseweight;
1836 $parseweight--;
1838 $maxweight = $bi->weight;
1839 } else if ($bi->weight < $minweight) {
1840 // As above except this time the blocks weight is LESS than the
1841 // the current minimum, so we will initialise the array from the
1842 // blocks weight (new minimum) to the current minimum
1843 $parseweight = $bi->weight;
1844 while (!array_key_exists($parseweight, $usedweights)) {
1845 $usedweights[$parseweight] = array();
1846 $spareweights[$parseweight] = $parseweight;
1847 $parseweight++;
1849 $minweight = $bi->weight;
1851 if ($bi->id != $block->instance->id) {
1852 unset($spareweights[$bi->weight]);
1853 $usedweights[$bi->weight][] = $bi->id;
1857 // First we find the nearest gap in the list of weights.
1858 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1859 $bestgap = null;
1860 foreach ($spareweights as $spareweight) {
1861 if (abs($newweight - $spareweight) < $bestdistance) {
1862 $bestdistance = abs($newweight - $spareweight);
1863 $bestgap = $spareweight;
1867 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1868 if (is_null($bestgap)) {
1869 $bestgap = self::MAX_WEIGHT + 1;
1870 while (!empty($usedweights[$bestgap])) {
1871 $bestgap++;
1875 // Now we know the gap we are aiming for, so move all the blocks along.
1876 if ($bestgap < $newweight) {
1877 $newweight = floor($newweight);
1878 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1879 if (array_key_exists($weight, $usedweights)) {
1880 foreach ($usedweights[$weight] as $biid) {
1881 $this->reposition_block($biid, $newregion, $weight - 1);
1885 $this->reposition_block($block->instance->id, $newregion, $newweight);
1886 } else {
1887 $newweight = ceil($newweight);
1888 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1889 if (array_key_exists($weight, $usedweights)) {
1890 foreach ($usedweights[$weight] as $biid) {
1891 $this->reposition_block($biid, $newregion, $weight + 1);
1895 $this->reposition_block($block->instance->id, $newregion, $newweight);
1898 $this->page->ensure_param_not_in_url('bui_moveid');
1899 $this->page->ensure_param_not_in_url('bui_newregion');
1900 $this->page->ensure_param_not_in_url('bui_newweight');
1901 return true;
1905 * Turns the display of normal blocks either on or off.
1907 * @param bool $setting
1909 public function show_only_fake_blocks($setting = true) {
1910 $this->fakeblocksonly = $setting;
1914 /// Helper functions for working with block classes ============================
1917 * Call a class method (one that does not require a block instance) on a block class.
1919 * @param string $blockname the name of the block.
1920 * @param string $method the method name.
1921 * @param array $param parameters to pass to the method.
1922 * @return mixed whatever the method returns.
1924 function block_method_result($blockname, $method, $param = NULL) {
1925 if(!block_load_class($blockname)) {
1926 return NULL;
1928 return call_user_func(array('block_'.$blockname, $method), $param);
1932 * Creates a new instance of the specified block class.
1934 * @param string $blockname the name of the block.
1935 * @param $instance block_instances DB table row (optional).
1936 * @param moodle_page $page the page this block is appearing on.
1937 * @return block_base the requested block instance.
1939 function block_instance($blockname, $instance = NULL, $page = NULL) {
1940 if(!block_load_class($blockname)) {
1941 return false;
1943 $classname = 'block_'.$blockname;
1944 $retval = new $classname;
1945 if($instance !== NULL) {
1946 if (is_null($page)) {
1947 global $PAGE;
1948 $page = $PAGE;
1950 $retval->_load_instance($instance, $page);
1952 return $retval;
1956 * Load the block class for a particular type of block.
1958 * @param string $blockname the name of the block.
1959 * @return boolean success or failure.
1961 function block_load_class($blockname) {
1962 global $CFG;
1964 if(empty($blockname)) {
1965 return false;
1968 $classname = 'block_'.$blockname;
1970 if(class_exists($classname)) {
1971 return true;
1974 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1976 if (file_exists($blockpath)) {
1977 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1978 include_once($blockpath);
1979 }else{
1980 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1981 return false;
1984 return class_exists($classname);
1988 * Given a specific page type, return all the page type patterns that might
1989 * match it.
1991 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1992 * @return array an array of all the page type patterns that might match this page type.
1994 function matching_page_type_patterns($pagetype) {
1995 $patterns = array($pagetype);
1996 $bits = explode('-', $pagetype);
1997 if (count($bits) == 3 && $bits[0] == 'mod') {
1998 if ($bits[2] == 'view') {
1999 $patterns[] = 'mod-*-view';
2000 } else if ($bits[2] == 'index') {
2001 $patterns[] = 'mod-*-index';
2004 while (count($bits) > 0) {
2005 $patterns[] = implode('-', $bits) . '-*';
2006 array_pop($bits);
2008 $patterns[] = '*';
2009 return $patterns;
2013 * Give an specific pattern, return all the page type patterns that would also match it.
2015 * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
2016 * @return array of all the page type patterns matching.
2018 function matching_page_type_patterns_from_pattern($pattern) {
2019 $patterns = array($pattern);
2020 if ($pattern === '*') {
2021 return $patterns;
2024 // Only keep the part before the star because we will append -* to all the bits.
2025 $star = strpos($pattern, '-*');
2026 if ($star !== false) {
2027 $pattern = substr($pattern, 0, $star);
2030 $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
2031 $patterns = array_unique($patterns);
2033 return $patterns;
2037 * Given a specific page type, parent context and currect context, return all the page type patterns
2038 * that might be used by this block.
2040 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
2041 * @param stdClass $parentcontext Block's parent context
2042 * @param stdClass $currentcontext Current context of block
2043 * @return array an array of all the page type patterns that might match this page type.
2045 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
2046 global $CFG; // Required for includes bellow.
2048 $bits = explode('-', $pagetype);
2050 $core = core_component::get_core_subsystems();
2051 $plugins = core_component::get_plugin_types();
2053 //progressively strip pieces off the page type looking for a match
2054 $componentarray = null;
2055 for ($i = count($bits); $i > 0; $i--) {
2056 $possiblecomponentarray = array_slice($bits, 0, $i);
2057 $possiblecomponent = implode('', $possiblecomponentarray);
2059 // Check to see if the component is a core component
2060 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
2061 $libfile = $core[$possiblecomponent].'/lib.php';
2062 if (file_exists($libfile)) {
2063 require_once($libfile);
2064 $function = $possiblecomponent.'_page_type_list';
2065 if (function_exists($function)) {
2066 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2067 break;
2073 //check the plugin directory and look for a callback
2074 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
2076 //We've found a plugin type. Look for a plugin name by getting the next section of page type
2077 if (count($bits) > $i) {
2078 $pluginname = $bits[$i];
2079 $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
2080 if (!empty($directory)){
2081 $libfile = $directory.'/lib.php';
2082 if (file_exists($libfile)) {
2083 require_once($libfile);
2084 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
2085 if (!function_exists($function)) {
2086 $function = $pluginname.'_page_type_list';
2088 if (function_exists($function)) {
2089 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2090 break;
2097 //we'll only get to here if we still don't have any patterns
2098 //the plugin type may have a callback
2099 $directory = $plugins[$possiblecomponent];
2100 $libfile = $directory.'/lib.php';
2101 if (file_exists($libfile)) {
2102 require_once($libfile);
2103 $function = $possiblecomponent.'_page_type_list';
2104 if (function_exists($function)) {
2105 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
2106 break;
2113 if (empty($patterns)) {
2114 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
2117 // Ensure that the * pattern is always available if editing block 'at distance', so
2118 // we always can 'bring back' it to the original context. MDL-30340
2119 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
2120 // TODO: We could change the string here, showing its 'bring back' meaning
2121 $patterns['*'] = get_string('page-x', 'pagetype');
2124 return $patterns;
2128 * Generates a default page type list when a more appropriate callback cannot be decided upon.
2130 * @param string $pagetype
2131 * @param stdClass $parentcontext
2132 * @param stdClass $currentcontext
2133 * @return array
2135 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2136 // Generate page type patterns based on current page type if
2137 // callbacks haven't been defined
2138 $patterns = array($pagetype => $pagetype);
2139 $bits = explode('-', $pagetype);
2140 while (count($bits) > 0) {
2141 $pattern = implode('-', $bits) . '-*';
2142 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
2143 // guessing page type description
2144 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
2145 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
2146 } else {
2147 $patterns[$pattern] = $pattern;
2149 array_pop($bits);
2151 $patterns['*'] = get_string('page-x', 'pagetype');
2152 return $patterns;
2156 * Generates the page type list for the my moodle page
2158 * @param string $pagetype
2159 * @param stdClass $parentcontext
2160 * @param stdClass $currentcontext
2161 * @return array
2163 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2164 return array('my-index' => get_string('page-my-index', 'pagetype'));
2168 * Generates the page type list for a module by either locating and using the modules callback
2169 * or by generating a default list.
2171 * @param string $pagetype
2172 * @param stdClass $parentcontext
2173 * @param stdClass $currentcontext
2174 * @return array
2176 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
2177 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
2178 if (empty($patterns)) {
2179 // if modules don't have callbacks
2180 // generate two default page type patterns for modules only
2181 $bits = explode('-', $pagetype);
2182 $patterns = array($pagetype => $pagetype);
2183 if ($bits[2] == 'view') {
2184 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
2185 } else if ($bits[2] == 'index') {
2186 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
2189 return $patterns;
2191 /// Functions update the blocks if required by the request parameters ==========
2194 * Return a {@link block_contents} representing the add a new block UI, if
2195 * this user is allowed to see it.
2197 * @return block_contents an appropriate block_contents, or null if the user
2198 * cannot add any blocks here.
2200 function block_add_block_ui($page, $output) {
2201 global $CFG, $OUTPUT;
2202 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
2203 return null;
2206 $bc = new block_contents();
2207 $bc->title = get_string('addblock');
2208 $bc->add_class('block_adminblock');
2209 $bc->attributes['data-block'] = 'adminblock';
2211 $missingblocks = $page->blocks->get_addable_blocks();
2212 if (empty($missingblocks)) {
2213 $bc->content = get_string('noblockstoaddhere');
2214 return $bc;
2217 $menu = array();
2218 foreach ($missingblocks as $block) {
2219 $menu[$block->name] = $block->title;
2222 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
2223 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
2224 $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
2225 $bc->content = $OUTPUT->render($select);
2226 return $bc;
2230 * Actually delete from the database any blocks that are currently on this page,
2231 * but which should not be there according to blocks_name_allowed_in_format.
2233 * @todo Write/Fix this function. Currently returns immediately
2234 * @param $course
2236 function blocks_remove_inappropriate($course) {
2237 // TODO
2238 return;
2240 $blockmanager = blocks_get_by_page($page);
2242 if (empty($blockmanager)) {
2243 return;
2246 if (($pageformat = $page->pagetype) == NULL) {
2247 return;
2250 foreach($blockmanager as $region) {
2251 foreach($region as $instance) {
2252 $block = blocks_get_record($instance->blockid);
2253 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
2254 blocks_delete_instance($instance->instance);
2261 * Check that a given name is in a permittable format
2263 * @param string $name
2264 * @param string $pageformat
2265 * @return bool
2267 function blocks_name_allowed_in_format($name, $pageformat) {
2268 $accept = NULL;
2269 $maxdepth = -1;
2270 if (!$bi = block_instance($name)) {
2271 return false;
2274 $formats = $bi->applicable_formats();
2275 if (!$formats) {
2276 $formats = array();
2278 foreach ($formats as $format => $allowed) {
2279 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
2280 $depth = substr_count($format, '-');
2281 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
2282 $maxdepth = $depth;
2283 $accept = $allowed;
2286 if ($accept === NULL) {
2287 $accept = !empty($formats['all']);
2289 return $accept;
2293 * Delete a block, and associated data.
2295 * @param object $instance a row from the block_instances table
2296 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
2297 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
2299 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
2300 global $DB;
2302 // Allow plugins to use this block before we completely delete it.
2303 if ($pluginsfunction = get_plugins_with_function('pre_block_delete')) {
2304 foreach ($pluginsfunction as $plugintype => $plugins) {
2305 foreach ($plugins as $pluginfunction) {
2306 $pluginfunction($instance);
2311 if ($block = block_instance($instance->blockname, $instance)) {
2312 $block->instance_delete();
2314 context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
2316 if (!$skipblockstables) {
2317 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2318 $DB->delete_records('block_instances', array('id' => $instance->id));
2319 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2324 * Delete multiple blocks at once.
2326 * @param array $instanceids A list of block instance ID.
2328 function blocks_delete_instances($instanceids) {
2329 global $DB;
2331 $limit = 1000;
2332 $count = count($instanceids);
2333 $chunks = [$instanceids];
2334 if ($count > $limit) {
2335 $chunks = array_chunk($instanceids, $limit);
2338 // Perform deletion for each chunk.
2339 foreach ($chunks as $chunk) {
2340 $instances = $DB->get_recordset_list('block_instances', 'id', $chunk);
2341 foreach ($instances as $instance) {
2342 blocks_delete_instance($instance, false, true);
2344 $instances->close();
2346 $DB->delete_records_list('block_positions', 'blockinstanceid', $chunk);
2347 $DB->delete_records_list('block_instances', 'id', $chunk);
2349 $preferences = array();
2350 foreach ($chunk as $instanceid) {
2351 $preferences[] = 'block' . $instanceid . 'hidden';
2352 $preferences[] = 'docked_block_instance_' . $instanceid;
2354 $DB->delete_records_list('user_preferences', 'name', $preferences);
2359 * Delete all the blocks that belong to a particular context.
2361 * @param int $contextid the context id.
2363 function blocks_delete_all_for_context($contextid) {
2364 global $DB;
2365 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2366 foreach ($instances as $instance) {
2367 blocks_delete_instance($instance, true);
2369 $instances->close();
2370 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2371 $DB->delete_records('block_positions', array('contextid' => $contextid));
2375 * Set a block to be visible or hidden on a particular page.
2377 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2378 * block_positions table as return by block_manager.
2379 * @param moodle_page $page the back to set the visibility with respect to.
2380 * @param integer $newvisibility 1 for visible, 0 for hidden.
2382 function blocks_set_visibility($instance, $page, $newvisibility) {
2383 global $DB;
2384 if (!empty($instance->blockpositionid)) {
2385 // Already have local information on this page.
2386 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2387 return;
2390 // Create a new block_positions record.
2391 $bp = new stdClass;
2392 $bp->blockinstanceid = $instance->id;
2393 $bp->contextid = $page->context->id;
2394 $bp->pagetype = $page->pagetype;
2395 if ($page->subpage) {
2396 $bp->subpage = $page->subpage;
2398 $bp->visible = $newvisibility;
2399 $bp->region = $instance->defaultregion;
2400 $bp->weight = $instance->defaultweight;
2401 $DB->insert_record('block_positions', $bp);
2405 * Get the block record for a particular blockid - that is, a particular type os block.
2407 * @param $int blockid block type id. If null, an array of all block types is returned.
2408 * @param bool $notusedanymore No longer used.
2409 * @return array|object row from block table, or all rows.
2411 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2412 global $PAGE;
2413 $blocks = $PAGE->blocks->get_installed_blocks();
2414 if ($blockid === NULL) {
2415 return $blocks;
2416 } else if (isset($blocks[$blockid])) {
2417 return $blocks[$blockid];
2418 } else {
2419 return false;
2424 * Find a given block by its blockid within a provide array
2426 * @param int $blockid
2427 * @param array $blocksarray
2428 * @return bool|object Instance if found else false
2430 function blocks_find_block($blockid, $blocksarray) {
2431 if (empty($blocksarray)) {
2432 return false;
2434 foreach($blocksarray as $blockgroup) {
2435 if (empty($blockgroup)) {
2436 continue;
2438 foreach($blockgroup as $instance) {
2439 if($instance->blockid == $blockid) {
2440 return $instance;
2444 return false;
2447 // Functions for programatically adding default blocks to pages ================
2450 * Parse a list of default blocks. See config-dist for a description of the format.
2452 * @param string $blocksstr Determines the starting point that the blocks are added in the region.
2453 * @return array the parsed list of default blocks
2455 function blocks_parse_default_blocks_list($blocksstr) {
2456 $blocks = array();
2457 $bits = explode(':', $blocksstr);
2458 if (!empty($bits)) {
2459 $leftbits = trim(array_shift($bits));
2460 if ($leftbits != '') {
2461 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2464 if (!empty($bits)) {
2465 $rightbits = trim(array_shift($bits));
2466 if ($rightbits != '') {
2467 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2470 return $blocks;
2474 * @return array the blocks that should be added to the site course by default.
2476 function blocks_get_default_site_course_blocks() {
2477 global $CFG;
2479 if (isset($CFG->defaultblocks_site)) {
2480 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2481 } else {
2482 return array(
2483 BLOCK_POS_LEFT => array(),
2484 BLOCK_POS_RIGHT => array()
2490 * Add the default blocks to a course.
2492 * @param object $course a course object.
2494 function blocks_add_default_course_blocks($course) {
2495 global $CFG;
2497 if (isset($CFG->defaultblocks_override)) {
2498 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2500 } else if ($course->id == SITEID) {
2501 $blocknames = blocks_get_default_site_course_blocks();
2503 } else if (isset($CFG->{'defaultblocks_' . $course->format})) {
2504 $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2506 } else {
2507 require_once($CFG->dirroot. '/course/lib.php');
2508 $blocknames = course_get_format($course)->get_default_blocks();
2512 if ($course->id == SITEID) {
2513 $pagetypepattern = 'site-index';
2514 } else {
2515 $pagetypepattern = 'course-view-*';
2517 $page = new moodle_page();
2518 $page->set_course($course);
2519 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2523 * Add the default system-context blocks. E.g. the admin tree.
2525 function blocks_add_default_system_blocks() {
2526 global $DB;
2528 $page = new moodle_page();
2529 $page->set_context(context_system::instance());
2530 // We don't add blocks required by the theme, they will be auto-created.
2531 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2533 if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2534 $subpagepattern = $defaultmypage->id;
2535 } else {
2536 $subpagepattern = null;
2539 $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2540 $newcontent = array('lp', 'course_overview');
2541 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);