3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Block Class and Functions
21 * This file defines the {@link block_manager} class,
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * @deprecated since Moodle 2.0. No longer used.
34 define('BLOCK_MOVE_LEFT', 0x01);
35 define('BLOCK_MOVE_RIGHT', 0x02);
36 define('BLOCK_MOVE_UP', 0x04);
37 define('BLOCK_MOVE_DOWN', 0x08);
38 define('BLOCK_CONFIGURE', 0x10);
42 * Default names for the block regions in the standard theme.
44 define('BLOCK_POS_LEFT', 'side-pre');
45 define('BLOCK_POS_RIGHT', 'side-post');
49 * @deprecated since Moodle 2.0. No longer used.
51 define('BLOCKS_PINNED_TRUE',0);
52 define('BLOCKS_PINNED_FALSE',1);
53 define('BLOCKS_PINNED_BOTH',2);
56 define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
57 define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
58 define('BUI_CONTEXTS_ENTIRE_SITE', 2);
60 define('BUI_CONTEXTS_CURRENT', 0);
61 define('BUI_CONTEXTS_CURRENT_SUBS', 1);
64 * Exception thrown when someone tried to do something with a block that does
65 * not exist on a page.
67 * @copyright 2009 Tim Hunt
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
71 class block_not_on_page_exception
extends moodle_exception
{
74 * @param int $instanceid the block instance id of the block that was looked for.
75 * @param object $page the current page.
77 public function __construct($instanceid, $page) {
79 $a->instanceid
= $instanceid;
80 $a->url
= $page->url
->out();
81 parent
::__construct('blockdoesnotexistonpage', '', $page->url
->out(), $a);
86 * This class keeps track of the block that should appear on a moodle_page.
88 * The page to work with as passed to the constructor.
90 * @copyright 2009 Tim Hunt
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
96 * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
97 * although other weights are valid.
99 const MAX_WEIGHT
= 10;
101 /// Field declarations =========================================================
104 * the moodle_page we are managing blocks for.
109 /** @var array region name => 1.*/
110 protected $regions = array();
112 /** @var string the region where new blocks are added.*/
113 protected $defaultregion = null;
115 /** @var array will be $DB->get_records('blocks') */
116 protected $allblocks = null;
119 * @var array blocks that this user can add to this page. Will be a subset
120 * of $allblocks, but with array keys block->name. Access this via the
121 * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
123 protected $addableblocks = null;
126 * Will be an array region-name => array(db rows loaded in load_blocks);
129 protected $birecordsbyregion = null;
132 * array region-name => array(block objects); populated as necessary by
133 * the ensure_instances_exist method.
136 protected $blockinstances = array();
139 * array region-name => array(block_contents objects) what actually needs to
140 * be displayed in each region.
143 protected $visibleblockcontent = array();
146 * array region-name => array(block_contents objects) extra block-like things
147 * to be displayed in each region, before the real blocks.
150 protected $extracontent = array();
153 * Used by the block move id, to track whether a block is currently being moved.
155 * When you click on the move icon of a block, first the page needs to reload with
156 * extra UI for choosing a new position for a particular block. In that situation
157 * this field holds the id of the block being moved.
161 protected $movingblock = null;
164 * Show only fake blocks
166 protected $fakeblocksonly = false;
168 /// Constructor ================================================================
172 * @param object $page the moodle_page object object we are managing the blocks for,
173 * or a reasonable faxilimily. (See the comment at the top of this class
174 * and {@link http://en.wikipedia.org/wiki/Duck_typing})
176 public function __construct($page) {
180 /// Getter methods =============================================================
183 * Get an array of all region names on this page where a block may appear
185 * @return array the internal names of the regions on this page where block may appear.
187 public function get_regions() {
188 if (is_null($this->defaultregion
)) {
189 $this->page
->initialise_theme_and_output();
191 return array_keys($this->regions
);
195 * Get the region name of the region blocks are added to by default
197 * @return string the internal names of the region where new blocks are added
198 * by default, and where any blocks from an unrecognised region are shown.
199 * (Imagine that blocks were added with one theme selected, then you switched
200 * to a theme with different block positions.)
202 public function get_default_region() {
203 $this->page
->initialise_theme_and_output();
204 return $this->defaultregion
;
208 * The list of block types that may be added to this page.
210 * @return array block name => record from block table.
212 public function get_addable_blocks() {
213 $this->check_is_loaded();
215 if (!is_null($this->addableblocks
)) {
216 return $this->addableblocks
;
220 $this->addableblocks
= array();
222 $allblocks = blocks_get_record();
223 if (empty($allblocks)) {
224 return $this->addableblocks
;
227 $pageformat = $this->page
->pagetype
;
228 foreach($allblocks as $block) {
229 if ($block->visible
&&
230 (block_method_result($block->name
, 'instance_allow_multiple') ||
!$this->is_block_present($block->name
)) &&
231 blocks_name_allowed_in_format($block->name
, $pageformat) &&
232 block_method_result($block->name
, 'user_can_addto', $this->page
)) {
233 $this->addableblocks
[$block->name
] = $block;
237 return $this->addableblocks
;
241 * Given a block name, find out of any of them are currently present in the page
243 * @param string $blockname - the basic name of a block (eg "navigation")
244 * @return boolean - is there one of these blocks in the current page?
246 public function is_block_present($blockname) {
247 if (empty($this->blockinstances
)) {
251 foreach ($this->blockinstances
as $region) {
252 foreach ($region as $instance) {
253 if (empty($instance->instance
->blockname
)) {
256 if ($instance->instance
->blockname
== $blockname) {
265 * Find out if a block type is known by the system
267 * @param string $blockname the name of the type of block.
268 * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
269 * @return boolean true if this block in installed.
271 public function is_known_block_type($blockname, $includeinvisible = false) {
272 $blocks = $this->get_installed_blocks();
273 foreach ($blocks as $block) {
274 if ($block->name
== $blockname && ($includeinvisible ||
$block->visible
)) {
282 * Find out if a region exists on a page
284 * @param string $region a region name
285 * @return boolean true if this region exists on this page.
287 public function is_known_region($region) {
288 return array_key_exists($region, $this->regions
);
292 * Get an array of all blocks within a given region
294 * @param string $region a block region that exists on this page.
295 * @return array of block instances.
297 public function get_blocks_for_region($region) {
298 $this->check_is_loaded();
299 $this->ensure_instances_exist($region);
300 return $this->blockinstances
[$region];
304 * Returns an array of block content objects that exist in a region
306 * @param string $region a block region that exists on this page.
307 * @return array of block block_contents objects for all the blocks in a region.
309 public function get_content_for_region($region, $output) {
310 $this->check_is_loaded();
311 $this->ensure_content_created($region, $output);
312 return $this->visibleblockcontent
[$region];
316 * Helper method used by get_content_for_region.
317 * @param string $region region name
318 * @param float $weight weight. May be fractional, since you may want to move a block
319 * between ones with weight 2 and 3, say ($weight would be 2.5).
320 * @return string URL for moving block $this->movingblock to this position.
322 protected function get_move_target_url($region, $weight) {
323 return new moodle_url($this->page
->url
, array('bui_moveid' => $this->movingblock
,
324 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
328 * Determine whether a region contains anything. (Either any real blocks, or
329 * the add new block UI.)
331 * (You may wonder why the $output parameter is required. Unfortunately,
332 * because of the way that blocks work, the only reliable way to find out
333 * if a block will be visible is to get the content for output, and to
334 * get the content, you need a renderer. Fortunately, this is not a
335 * performance problem, because we cache the output that is generated, and
336 * in almost every case where we call region_has_content, we are about to
337 * output the blocks anyway, so we are not doing wasted effort.)
339 * @param string $region a block region that exists on this page.
340 * @param object $output a core_renderer. normally the global $OUTPUT.
341 * @return boolean Whether there is anything in this region.
343 public function region_has_content($region, $output) {
345 if (!$this->is_known_region($region)) {
348 $this->check_is_loaded();
349 $this->ensure_content_created($region, $output);
350 // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
351 // Mark Nielsen's patch - part 1
352 if ($this->page
->user_is_editing() && $this->page
->user_can_edit_blocks() && $this->movingblock
) {
353 // If editing is on, we need all the block regions visible, for the
357 return !empty($this->visibleblockcontent
[$region]) ||
!empty($this->extracontent
[$region]);
361 * Get an array of all of the installed blocks.
363 * @return array contents of the block table.
365 public function get_installed_blocks() {
367 if (is_null($this->allblocks
)) {
368 $this->allblocks
= $DB->get_records('block');
370 return $this->allblocks
;
373 /// Setter methods =============================================================
376 * Add a region to a page
378 * @param string $region add a named region where blocks may appear on the
379 * current page. This is an internal name, like 'side-pre', not a string to
382 public function add_region($region) {
383 $this->check_not_yet_loaded();
384 $this->regions
[$region] = 1;
388 * Add an array of regions
391 * @param array $regions this utility method calls add_region for each array element.
393 public function add_regions($regions) {
394 foreach ($regions as $region) {
395 $this->add_region($region);
400 * Set the default region for new blocks on the page
402 * @param string $defaultregion the internal names of the region where new
403 * blocks should be added by default, and where any blocks from an
404 * unrecognised region are shown.
406 public function set_default_region($defaultregion) {
407 $this->check_not_yet_loaded();
408 if ($defaultregion) {
409 $this->check_region_is_known($defaultregion);
411 $this->defaultregion
= $defaultregion;
415 * Add something that looks like a block, but which isn't an actual block_instance,
418 * @param block_contents $bc the content of the block-like thing.
419 * @param string $region a block region that exists on this page.
421 public function add_fake_block($bc, $region) {
422 $this->page
->initialise_theme_and_output();
423 if (!$this->is_known_region($region)) {
424 $region = $this->get_default_region();
426 if (array_key_exists($region, $this->visibleblockcontent
)) {
427 throw new coding_exception('block_manager has already prepared the blocks in region ' .
428 $region . 'for output. It is too late to add a fake block.');
430 $this->extracontent
[$region][] = $bc;
434 * When the block_manager class was created, the {@link add_fake_block()}
435 * was called add_pretend_block, which is inconsisted with
436 * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
437 * was renamed to add_fake_block. Please update your code.
438 * @param block_contents $bc the content of the block-like thing.
439 * @param string $region a block region that exists on this page.
441 public function add_pretend_block($bc, $region) {
442 debugging(DEBUG_DEVELOPER
, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
443 $this->add_fake_block($bc, $region);
447 * Checks to see whether all of the blocks within the given region are docked
449 * @see region_uses_dock
450 * @param string $region
451 * @return bool True if all of the blocks within that region are docked
453 public function region_completely_docked($region, $output) {
454 if (!$this->page
->theme
->enable_dock
) {
458 // Do not dock the region when the user attemps to move a block.
459 if ($this->movingblock
) {
463 $this->check_is_loaded();
464 $this->ensure_content_created($region, $output);
465 foreach($this->visibleblockcontent
[$region] as $instance) {
466 if (!empty($instance->content
) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
474 * Checks to see whether any of the blocks within the given regions are docked
476 * @see region_completely_docked
477 * @param array|string $regions array of regions (or single region)
478 * @return bool True if any of the blocks within that region are docked
480 public function region_uses_dock($regions, $output) {
481 if (!$this->page
->theme
->enable_dock
) {
484 $this->check_is_loaded();
485 foreach((array)$regions as $region) {
486 $this->ensure_content_created($region, $output);
487 foreach($this->visibleblockcontent
[$region] as $instance) {
488 if(!empty($instance->content
) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid
, 0)) {
496 /// Actions ====================================================================
499 * This method actually loads the blocks for our page from the database.
501 * @param boolean|null $includeinvisible
502 * null (default) - load hidden blocks if $this->page->user_is_editing();
503 * true - load hidden blocks.
504 * false - don't load hidden blocks.
506 public function load_blocks($includeinvisible = null) {
509 if (!is_null($this->birecordsbyregion
)) {
514 if ($CFG->version
< 2009050619) {
515 // Upgrade/install not complete. Don't try too show any blocks.
516 $this->birecordsbyregion
= array();
520 // Ensure we have been initialised.
521 if (is_null($this->defaultregion
)) {
522 $this->page
->initialise_theme_and_output();
523 // If there are still no block regions, then there are no blocks on this page.
524 if (empty($this->regions
)) {
525 $this->birecordsbyregion
= array();
530 // Check if we need to load normal blocks
531 if ($this->fakeblocksonly
) {
532 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
536 if (is_null($includeinvisible)) {
537 $includeinvisible = $this->page
->user_is_editing();
539 if ($includeinvisible) {
542 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
545 $context = $this->page
->context
;
546 $contexttest = 'bi.parentcontextid = :contextid2';
547 $parentcontextparams = array();
548 $parentcontextids = get_parent_contexts($context);
549 if ($parentcontextids) {
550 list($parentcontexttest, $parentcontextparams) =
551 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
, 'parentcontext');
552 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
555 $pagetypepatterns = matching_page_type_patterns($this->page
->pagetype
);
556 list($pagetypepatterntest, $pagetypepatternparams) =
557 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
, 'pagetypepatterntest');
559 list($ccselect, $ccjoin) = context_instance_preload_sql('bi.id', CONTEXT_BLOCK
, 'ctx');
562 'subpage1' => $this->page
->subpage
,
563 'subpage2' => $this->page
->subpage
,
564 'contextid1' => $context->id
,
565 'contextid2' => $context->id
,
566 'pagetype' => $this->page
->pagetype
,
568 if ($this->page
->subpage
=== '') {
569 $params['subpage1'] = $DB->sql_empty();
570 $params['subpage2'] = $DB->sql_empty();
574 bp.id AS blockpositionid,
577 bi.showinsubcontexts,
582 COALESCE(bp.visible, 1) AS visible,
583 COALESCE(bp.region, bi.defaultregion) AS region,
584 COALESCE(bp.weight, bi.defaultweight) AS weight,
588 FROM {block_instances} bi
589 JOIN {block} b ON bi.blockname = b.name
590 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
591 AND bp.contextid = :contextid1
592 AND bp.pagetype = :pagetype
593 AND bp.subpage = :subpage1
598 AND bi.pagetypepattern $pagetypepatterntest
599 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
604 COALESCE(bp.region, bi.defaultregion),
605 COALESCE(bp.weight, bi.defaultweight),
607 $blockinstances = $DB->get_recordset_sql($sql, $params +
$parentcontextparams +
$pagetypepatternparams);
609 $this->birecordsbyregion
= $this->prepare_per_region_arrays();
611 foreach ($blockinstances as $bi) {
612 context_instance_preload($bi);
613 if ($this->is_known_region($bi->region
)) {
614 $this->birecordsbyregion
[$bi->region
][] = $bi;
620 // Pages don't necessarily have a defaultregion. The one time this can
621 // happen is when there are no theme block regions, but the script itself
622 // has a block region in the main content area.
623 if (!empty($this->defaultregion
)) {
624 $this->birecordsbyregion
[$this->defaultregion
] =
625 array_merge($this->birecordsbyregion
[$this->defaultregion
], $unknown);
630 * Add a block to the current page, or related pages. The block is added to
631 * context $this->page->contextid. If $pagetypepattern $subpagepattern
633 * @param string $blockname The type of block to add.
634 * @param string $region the block region on this page to add the block to.
635 * @param integer $weight determines the order where this block appears in the region.
636 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
637 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
638 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
640 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
642 // Allow invisible blocks because this is used when adding default page blocks, which
643 // might include invisible ones if the user makes some default blocks invisible
644 $this->check_known_block_type($blockname, true);
645 $this->check_region_is_known($region);
647 if (empty($pagetypepattern)) {
648 $pagetypepattern = $this->page
->pagetype
;
651 $blockinstance = new stdClass
;
652 $blockinstance->blockname
= $blockname;
653 $blockinstance->parentcontextid
= $this->page
->context
->id
;
654 $blockinstance->showinsubcontexts
= !empty($showinsubcontexts);
655 $blockinstance->pagetypepattern
= $pagetypepattern;
656 $blockinstance->subpagepattern
= $subpagepattern;
657 $blockinstance->defaultregion
= $region;
658 $blockinstance->defaultweight
= $weight;
659 $blockinstance->configdata
= '';
660 $blockinstance->id
= $DB->insert_record('block_instances', $blockinstance);
662 // Ensure the block context is created.
663 get_context_instance(CONTEXT_BLOCK
, $blockinstance->id
);
665 // If the new instance was created, allow it to do additional setup
666 if ($block = block_instance($blockname, $blockinstance)) {
667 $block->instance_create();
671 public function add_block_at_end_of_default_region($blockname) {
672 $defaulregion = $this->get_default_region();
674 $lastcurrentblock = end($this->birecordsbyregion
[$defaulregion]);
675 if ($lastcurrentblock) {
676 $weight = $lastcurrentblock->weight +
1;
681 if ($this->page
->subpage
) {
682 $subpage = $this->page
->subpage
;
687 // Special case. Course view page type include the course format, but we
688 // want to add the block non-format-specifically.
689 $pagetypepattern = $this->page
->pagetype
;
690 if (strpos($pagetypepattern, 'course-view') === 0) {
691 $pagetypepattern = 'course-view-*';
694 // We should end using this for ALL the blocks, making always the 1st option
695 // the default one to be used. Until then, this is one hack to avoid the
696 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
697 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
698 // (the FIRST $pagetypepattern will be set)
700 // We are applying it to all blocks created in mod pages for now and only if the
701 // default pagetype is not one of the available options
702 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
703 $pagetypelist = generate_page_type_patterns($this->page
->pagetype
, null, $this->page
->context
);
704 // Only go for the first if the pagetype is not a valid option
705 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
706 $pagetypepattern = key($pagetypelist);
709 // Surely other pages like course-report will need this too, they just are not important
710 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
712 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
716 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
718 * @param array $blocks array with array keys the region names, and values an array of block names.
719 * @param string $pagetypepattern optional. Passed to @see add_block()
720 * @param string $subpagepattern optional. Passed to @see add_block()
722 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
723 $this->add_regions(array_keys($blocks));
724 foreach ($blocks as $region => $regionblocks) {
726 foreach ($regionblocks as $blockname) {
727 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
734 * Move a block to a new position on this page.
736 * If this block cannot appear on any other pages, then we change defaultposition/weight
737 * in the block_instances table. Otherwise we just set the position on this page.
739 * @param $blockinstanceid the block instance id.
740 * @param $newregion the new region name.
741 * @param $newweight the new weight.
743 public function reposition_block($blockinstanceid, $newregion, $newweight) {
746 $this->check_region_is_known($newregion);
747 $inst = $this->find_instance($blockinstanceid);
749 $bi = $inst->instance
;
750 if ($bi->weight
== $bi->defaultweight
&& $bi->region
== $bi->defaultregion
&&
751 !$bi->showinsubcontexts
&& strpos($bi->pagetypepattern
, '*') === false &&
752 (!$this->page
->subpage ||
$bi->subpagepattern
)) {
754 // Set default position
755 $newbi = new stdClass
;
756 $newbi->id
= $bi->id
;
757 $newbi->defaultregion
= $newregion;
758 $newbi->defaultweight
= $newweight;
759 $DB->update_record('block_instances', $newbi);
761 if ($bi->blockpositionid
) {
763 $bp->id
= $bi->blockpositionid
;
764 $bp->region
= $newregion;
765 $bp->weight
= $newweight;
766 $DB->update_record('block_positions', $bp);
770 // Just set position on this page.
772 $bp->region
= $newregion;
773 $bp->weight
= $newweight;
775 if ($bi->blockpositionid
) {
776 $bp->id
= $bi->blockpositionid
;
777 $DB->update_record('block_positions', $bp);
780 $bp->blockinstanceid
= $bi->id
;
781 $bp->contextid
= $this->page
->context
->id
;
782 $bp->pagetype
= $this->page
->pagetype
;
783 if ($this->page
->subpage
) {
784 $bp->subpage
= $this->page
->subpage
;
788 $bp->visible
= $bi->visible
;
789 $DB->insert_record('block_positions', $bp);
795 * Find a given block by its instance id
797 * @param integer $instanceid
800 public function find_instance($instanceid) {
801 foreach ($this->regions
as $region => $notused) {
802 $this->ensure_instances_exist($region);
803 foreach($this->blockinstances
[$region] as $instance) {
804 if ($instance->instance
->id
== $instanceid) {
809 throw new block_not_on_page_exception($instanceid, $this->page
);
812 /// Inner workings =============================================================
815 * Check whether the page blocks have been loaded yet
817 * @return void Throws coding exception if already loaded
819 protected function check_not_yet_loaded() {
820 if (!is_null($this->birecordsbyregion
)) {
821 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.');
826 * Check whether the page blocks have been loaded yet
828 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
830 * @return void Throws coding exception if already loaded
832 protected function check_is_loaded() {
833 if (is_null($this->birecordsbyregion
)) {
834 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
839 * Check if a block type is known and usable
841 * @param string $blockname The block type name to search for
842 * @param bool $includeinvisible Include disabled block types in the initial pass
843 * @return void Coding Exception thrown if unknown or not enabled
845 protected function check_known_block_type($blockname, $includeinvisible = false) {
846 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
847 if ($this->is_known_block_type($blockname, true)) {
848 throw new coding_exception('Unknown block type ' . $blockname);
850 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
856 * Check if a region is known by its name
858 * @param string $region
859 * @return void Coding Exception thrown if the region is not known
861 protected function check_region_is_known($region) {
862 if (!$this->is_known_region($region)) {
863 throw new coding_exception('Trying to reference an unknown block region ' . $region);
868 * Returns an array of region names as keys and nested arrays for values
870 * @return array an array where the array keys are the region names, and the array
871 * values are empty arrays.
873 protected function prepare_per_region_arrays() {
875 foreach ($this->regions
as $region => $notused) {
876 $result[$region] = array();
882 * Create a set of new block instance from a record array
884 * @param array $birecords An array of block instance records
885 * @return array An array of instantiated block_instance objects
887 protected function create_block_instances($birecords) {
889 foreach ($birecords as $record) {
890 if ($blockobject = block_instance($record->blockname
, $record, $this->page
)) {
891 $results[] = $blockobject;
898 * Create all the block instances for all the blocks that were loaded by
899 * load_blocks. This is used, for example, to ensure that all blocks get a
900 * chance to initialise themselves via the {@link block_base::specialize()}
901 * method, before any output is done.
903 public function create_all_block_instances() {
904 foreach ($this->get_regions() as $region) {
905 $this->ensure_instances_exist($region);
910 * Return an array of content objects from a set of block instances
912 * @param array $instances An array of block instances
913 * @param renderer_base The renderer to use.
914 * @param string $region the region name.
915 * @return array An array of block_content (and possibly block_move_target) objects.
917 protected function create_block_contents($instances, $output, $region) {
922 if ($this->movingblock
) {
923 $first = reset($instances);
925 $lastweight = $first->instance
->weight
- 2;
928 $strmoveblockhere = get_string('moveblockhere', 'block');
931 foreach ($instances as $instance) {
932 $content = $instance->get_content_for_output($output);
933 if (empty($content)) {
937 if ($this->movingblock
&& $lastweight != $instance->instance
->weight
&&
938 $content->blockinstanceid
!= $this->movingblock
&& $lastblock != $this->movingblock
) {
939 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, ($lastweight +
$instance->instance
->weight
)/2));
942 if ($content->blockinstanceid
== $this->movingblock
) {
943 $content->add_class('beingmoved');
944 $content->annotation
.= get_string('movingthisblockcancel', 'block',
945 html_writer
::link($this->page
->url
, get_string('cancel')));
948 $results[] = $content;
949 $lastweight = $instance->instance
->weight
;
950 $lastblock = $instance->instance
->id
;
953 if ($this->movingblock
&& $lastblock != $this->movingblock
) {
954 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight +
1));
960 * Ensure block instances exist for a given region
962 * @param string $region Check for bi's with the instance with this name
964 protected function ensure_instances_exist($region) {
965 $this->check_region_is_known($region);
966 if (!array_key_exists($region, $this->blockinstances
)) {
967 $this->blockinstances
[$region] =
968 $this->create_block_instances($this->birecordsbyregion
[$region]);
973 * Ensure that there is some content within the given region
975 * @param string $region The name of the region to check
977 protected function ensure_content_created($region, $output) {
978 $this->ensure_instances_exist($region);
979 if (!array_key_exists($region, $this->visibleblockcontent
)) {
981 if (array_key_exists($region, $this->extracontent
)) {
982 $contents = $this->extracontent
[$region];
984 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances
[$region], $output, $region));
985 if ($region == $this->defaultregion
) {
986 $addblockui = block_add_block_ui($this->page
, $output);
988 $contents[] = $addblockui;
991 $this->visibleblockcontent
[$region] = $contents;
995 /// Process actions from the URL ===============================================
998 * Get the appropriate list of editing icons for a block. This is used
999 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1001 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1002 * @return an array in the format for {@link block_contents::$controls}
1004 public function edit_controls($block) {
1007 if (!isset($CFG->undeletableblocktypes
) ||
(!is_array($CFG->undeletableblocktypes
) && !is_string($CFG->undeletableblocktypes
))) {
1008 $undeletableblocktypes = array('navigation','settings');
1009 } else if (is_string($CFG->undeletableblocktypes
)) {
1010 $undeletableblocktypes = explode(',', $CFG->undeletableblocktypes
);
1012 $undeletableblocktypes = $CFG->undeletableblocktypes
;
1015 $controls = array();
1016 $actionurl = $this->page
->url
->out(false, array('sesskey'=> sesskey()));
1018 if ($this->page
->user_can_edit_blocks()) {
1020 $controls[] = array('url' => $actionurl . '&bui_moveid=' . $block->instance
->id
,
1021 'icon' => 't/move', 'caption' => get_string('move'));
1024 if ($this->page
->user_can_edit_blocks() ||
$block->user_can_edit()) {
1025 // Edit config icon - always show - needed for positioning UI.
1026 $controls[] = array('url' => $actionurl . '&bui_editid=' . $block->instance
->id
,
1027 'icon' => 't/edit', 'caption' => get_string('configuration'));
1030 if ($this->page
->user_can_edit_blocks() && $block->user_can_edit() && $block->user_can_addto($this->page
)) {
1031 if (!in_array($block->instance
->blockname
, $undeletableblocktypes)
1032 ||
!in_array($block->instance
->pagetypepattern
, array('*', 'site-index'))
1033 ||
$block->instance
->parentcontextid
!= SITEID
) {
1035 $controls[] = array('url' => $actionurl . '&bui_deleteid=' . $block->instance
->id
,
1036 'icon' => 't/delete', 'caption' => get_string('delete'));
1040 if ($this->page
->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1042 if ($block->instance
->visible
) {
1043 $controls[] = array('url' => $actionurl . '&bui_hideid=' . $block->instance
->id
,
1044 'icon' => 't/hide', 'caption' => get_string('hide'));
1046 $controls[] = array('url' => $actionurl . '&bui_showid=' . $block->instance
->id
,
1047 'icon' => 't/show', 'caption' => get_string('show'));
1051 // Assign roles icon.
1052 if (has_capability('moodle/role:assign', $block->context
)) {
1053 //TODO: please note it is sloppy to pass urls through page parameters!!
1054 // it is shortened because some web servers (e.g. IIS by default) give
1055 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1056 $return = $this->page
->url
->out(false);
1057 $return = str_replace($CFG->wwwroot
. '/', '', $return);
1059 $controls[] = array('url' => $CFG->wwwroot
. '/' . $CFG->admin
.
1060 '/roles/assign.php?contextid=' . $block->context
->id
. '&returnurl=' . urlencode($return),
1061 'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));
1068 * Process any block actions that were specified in the URL.
1070 * @return boolean true if anything was done. False if not.
1072 public function process_url_actions() {
1073 if (!$this->page
->user_is_editing()) {
1076 return $this->process_url_add() ||
$this->process_url_delete() ||
1077 $this->process_url_show_hide() ||
$this->process_url_edit() ||
1078 $this->process_url_move();
1082 * Handle adding a block.
1083 * @return boolean true if anything was done. False if not.
1085 public function process_url_add() {
1086 $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN
);
1093 if (!$this->page
->user_can_edit_blocks()) {
1094 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('addblock'));
1097 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1098 throw new moodle_exception('cannotaddthisblocktype', '', $this->page
->url
->out(), $blocktype);
1101 $this->add_block_at_end_of_default_region($blocktype);
1103 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1104 $this->page
->ensure_param_not_in_url('bui_addblock');
1110 * Handle deleting a block.
1111 * @return boolean true if anything was done. False if not.
1113 public function process_url_delete() {
1114 $blockid = optional_param('bui_deleteid', null, PARAM_INTEGER
);
1121 $block = $this->page
->blocks
->find_instance($blockid);
1123 if (!$block->user_can_edit() ||
!$this->page
->user_can_edit_blocks() ||
!$block->user_can_addto($this->page
)) {
1124 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('deleteablock'));
1127 blocks_delete_instance($block->instance
);
1129 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1130 $this->page
->ensure_param_not_in_url('bui_deleteid');
1136 * Handle showing or hiding a block.
1137 * @return boolean true if anything was done. False if not.
1139 public function process_url_show_hide() {
1140 if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER
)) {
1142 } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER
)) {
1150 $block = $this->page
->blocks
->find_instance($blockid);
1152 if (!$this->page
->user_can_edit_blocks()) {
1153 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('hideshowblocks'));
1154 } else if (!$block->instance_can_be_hidden()) {
1158 blocks_set_visibility($block->instance
, $this->page
, $newvisibility);
1160 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1161 $this->page
->ensure_param_not_in_url('bui_hideid');
1162 $this->page
->ensure_param_not_in_url('bui_showid');
1168 * Handle showing/processing the submission from the block editing form.
1169 * @return boolean true if the form was submitted and the new config saved. Does not
1170 * return if the editing form was displayed. False otherwise.
1172 public function process_url_edit() {
1173 global $CFG, $DB, $PAGE, $OUTPUT;
1175 $blockid = optional_param('bui_editid', null, PARAM_INTEGER
);
1181 require_once($CFG->dirroot
. '/blocks/edit_form.php');
1183 $block = $this->find_instance($blockid);
1185 if (!$block->user_can_edit() && !$this->page
->user_can_edit_blocks()) {
1186 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1189 $editpage = new moodle_page();
1190 $editpage->set_pagelayout('admin');
1191 $editpage->set_course($this->page
->course
);
1192 //$editpage->set_context($block->context);
1193 $editpage->set_context($this->page
->context
);
1194 if ($this->page
->cm
) {
1195 $editpage->set_cm($this->page
->cm
);
1197 $editurlbase = str_replace($CFG->wwwroot
. '/', '/', $this->page
->url
->out_omit_querystring());
1198 $editurlparams = $this->page
->url
->params();
1199 $editurlparams['bui_editid'] = $blockid;
1200 $editpage->set_url($editurlbase, $editurlparams);
1201 $editpage->set_block_actions_done();
1202 // At this point we are either going to redirect, or display the form, so
1203 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1205 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1206 $output = $editpage->get_renderer('core');
1209 $formfile = $CFG->dirroot
. '/blocks/' . $block->name() . '/edit_form.php';
1210 if (is_readable($formfile)) {
1211 require_once($formfile);
1212 $classname = 'block_' . $block->name() . '_edit_form';
1213 if (!class_exists($classname)) {
1214 $classname = 'block_edit_form';
1217 $classname = 'block_edit_form';
1220 $mform = new $classname($editpage->url
, $block, $this->page
);
1221 $mform->set_data($block->instance
);
1223 if ($mform->is_cancelled()) {
1224 redirect($this->page
->url
);
1226 } else if ($data = $mform->get_data()) {
1228 $bi->id
= $block->instance
->id
;
1229 $bi->pagetypepattern
= $data->bui_pagetypepattern
;
1230 if (empty($data->bui_subpagepattern
) ||
$data->bui_subpagepattern
== '%@NULL@%') {
1231 $bi->subpagepattern
= null;
1233 $bi->subpagepattern
= $data->bui_subpagepattern
;
1236 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1237 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1238 $parentcontext = get_context_instance_by_id($data->bui_parentcontextid
);
1240 // Updating stickiness and contexts. See MDL-21375 for details.
1241 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1243 // Explicitly set the default context
1244 $bi->parentcontextid
= $parentcontext->id
;
1246 if ($data->bui_editingatfrontpage
) { // The block is being edited on the front page
1248 // The interface here is a special case because the pagetype pattern is
1249 // totally derived from the context menu. Here are the excpetions. MDL-30340
1251 switch ($data->bui_contexts
) {
1252 case BUI_CONTEXTS_ENTIRE_SITE
:
1253 // The user wants to show the block across the entire site
1254 $bi->parentcontextid
= $systemcontext->id
;
1255 $bi->showinsubcontexts
= true;
1256 $bi->pagetypepattern
= '*';
1258 case BUI_CONTEXTS_FRONTPAGE_SUBS
:
1259 // The user wants the block shown on the front page and all subcontexts
1260 $bi->parentcontextid
= $frontpagecontext->id
;
1261 $bi->showinsubcontexts
= true;
1262 $bi->pagetypepattern
= '*';
1264 case BUI_CONTEXTS_FRONTPAGE_ONLY
:
1265 // The user want to show the front page on the frontpage only
1266 $bi->parentcontextid
= $frontpagecontext->id
;
1267 $bi->showinsubcontexts
= false;
1268 $bi->pagetypepattern
= 'site-index';
1269 // This is the only relevant page type anyway but we'll set it explicitly just
1270 // in case the front page grows site-index-* subpages of its own later
1276 $bits = explode('-', $bi->pagetypepattern
);
1277 // hacks for some contexts
1278 if (($parentcontext->contextlevel
== CONTEXT_COURSE
) && ($parentcontext->instanceid
!= SITEID
)) {
1279 // For course context
1280 // is page type pattern is mod-*, change showinsubcontext to 1
1281 if ($bits[0] == 'mod' ||
$bi->pagetypepattern
== '*') {
1282 $bi->showinsubcontexts
= 1;
1284 $bi->showinsubcontexts
= 0;
1286 } else if ($parentcontext->contextlevel
== CONTEXT_USER
) {
1288 // subpagepattern should be null
1289 if ($bits[0] == 'user' or $bits[0] == 'my') {
1290 // we don't need subpagepattern in usercontext
1291 $bi->subpagepattern
= null;
1295 $bi->defaultregion
= $data->bui_defaultregion
;
1296 $bi->defaultweight
= $data->bui_defaultweight
;
1297 $DB->update_record('block_instances', $bi);
1299 if (!empty($block->config
)) {
1300 $config = clone($block->config
);
1302 $config = new stdClass
;
1304 foreach ($data as $configfield => $value) {
1305 if (strpos($configfield, 'config_') !== 0) {
1308 $field = substr($configfield, 7);
1309 $config->$field = $value;
1311 $block->instance_config_save($config);
1314 $bp->visible
= $data->bui_visible
;
1315 $bp->region
= $data->bui_region
;
1316 $bp->weight
= $data->bui_weight
;
1317 $needbprecord = !$data->bui_visible ||
$data->bui_region
!= $data->bui_defaultregion ||
1318 $data->bui_weight
!= $data->bui_defaultweight
;
1320 if ($block->instance
->blockpositionid
&& !$needbprecord) {
1321 $DB->delete_records('block_positions', array('id' => $block->instance
->blockpositionid
));
1323 } else if ($block->instance
->blockpositionid
&& $needbprecord) {
1324 $bp->id
= $block->instance
->blockpositionid
;
1325 $DB->update_record('block_positions', $bp);
1327 } else if ($needbprecord) {
1328 $bp->blockinstanceid
= $block->instance
->id
;
1329 $bp->contextid
= $this->page
->context
->id
;
1330 $bp->pagetype
= $this->page
->pagetype
;
1331 if ($this->page
->subpage
) {
1332 $bp->subpage
= $this->page
->subpage
;
1336 $DB->insert_record('block_positions', $bp);
1339 redirect($this->page
->url
);
1342 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1343 $editpage->set_title($strheading);
1344 $editpage->set_heading($strheading);
1345 $bits = explode('-', $this->page
->pagetype
);
1346 if ($bits[0] == 'tag' && !empty($this->page
->subpage
)) {
1347 // better navbar for tag pages
1348 $editpage->navbar
->add(get_string('tags'), new moodle_url('/tag/'));
1349 $tag = tag_get('id', $this->page
->subpage
, '*');
1350 // tag search page doesn't have subpageid
1352 $editpage->navbar
->add($tag->name
, new moodle_url('/tag/index.php', array('id'=>$tag->id
)));
1355 $editpage->navbar
->add($block->get_title());
1356 $editpage->navbar
->add(get_string('configuration'));
1357 echo $output->header();
1358 echo $output->heading($strheading, 2);
1360 echo $output->footer();
1366 * Handle showing/processing the submission from the block editing form.
1367 * @return boolean true if the form was submitted and the new config saved. Does not
1368 * return if the editing form was displayed. False otherwise.
1370 public function process_url_move() {
1371 global $CFG, $DB, $PAGE;
1373 $blockid = optional_param('bui_moveid', null, PARAM_INTEGER
);
1380 $block = $this->find_instance($blockid);
1382 if (!$this->page
->user_can_edit_blocks()) {
1383 throw new moodle_exception('nopermissions', '', $this->page
->url
->out(), get_string('editblock'));
1386 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT
);
1387 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT
);
1388 if (!$newregion ||
is_null($newweight)) {
1389 // Don't have a valid target position yet, must be just starting the move.
1390 $this->movingblock
= $blockid;
1391 $this->page
->ensure_param_not_in_url('bui_moveid');
1395 if (!$this->is_known_region($newregion)) {
1396 throw new moodle_exception('unknownblockregion', '', $this->page
->url
, $newregion);
1399 // Move this block. This may involve moving other nearby blocks.
1400 $blocks = $this->birecordsbyregion
[$newregion];
1402 $maxweight = self
::MAX_WEIGHT
;
1403 $minweight = -self
::MAX_WEIGHT
;
1405 // Initialise the used weights and spareweights array with the default values
1406 $spareweights = array();
1407 $usedweights = array();
1408 for ($i = $minweight; $i <= $maxweight; $i++
) {
1409 $spareweights[$i] = $i;
1410 $usedweights[$i] = array();
1413 // Check each block and sort out where we have used weights
1414 foreach ($blocks as $bi) {
1415 if ($bi->weight
> $maxweight) {
1416 // If this statement is true then the blocks weight is more than the
1417 // current maximum. To ensure that we can get the best block position
1418 // we will initialise elements within the usedweights and spareweights
1419 // arrays between the blocks weight (which will then be the new max) and
1421 $parseweight = $bi->weight
;
1422 while (!array_key_exists($parseweight, $usedweights)) {
1423 $usedweights[$parseweight] = array();
1424 $spareweights[$parseweight] = $parseweight;
1427 $maxweight = $bi->weight
;
1428 } else if ($bi->weight
< $minweight) {
1429 // As above except this time the blocks weight is LESS than the
1430 // the current minimum, so we will initialise the array from the
1431 // blocks weight (new minimum) to the current minimum
1432 $parseweight = $bi->weight
;
1433 while (!array_key_exists($parseweight, $usedweights)) {
1434 $usedweights[$parseweight] = array();
1435 $spareweights[$parseweight] = $parseweight;
1438 $minweight = $bi->weight
;
1440 if ($bi->id
!= $block->instance
->id
) {
1441 unset($spareweights[$bi->weight
]);
1442 $usedweights[$bi->weight
][] = $bi->id
;
1446 // First we find the nearest gap in the list of weights.
1447 $bestdistance = max(abs($newweight - self
::MAX_WEIGHT
), abs($newweight + self
::MAX_WEIGHT
)) +
1;
1449 foreach ($spareweights as $spareweight) {
1450 if (abs($newweight - $spareweight) < $bestdistance) {
1451 $bestdistance = abs($newweight - $spareweight);
1452 $bestgap = $spareweight;
1456 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1457 if (is_null($bestgap)) {
1458 $bestgap = self
::MAX_WEIGHT +
1;
1459 while (!empty($usedweights[$bestgap])) {
1464 // Now we know the gap we are aiming for, so move all the blocks along.
1465 if ($bestgap < $newweight) {
1466 $newweight = floor($newweight);
1467 for ($weight = $bestgap +
1; $weight <= $newweight; $weight++
) {
1468 foreach ($usedweights[$weight] as $biid) {
1469 $this->reposition_block($biid, $newregion, $weight - 1);
1472 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1474 $newweight = ceil($newweight);
1475 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1476 if (array_key_exists($weight, $usedweights)) {
1477 foreach ($usedweights[$weight] as $biid) {
1478 $this->reposition_block($biid, $newregion, $weight +
1);
1482 $this->reposition_block($block->instance
->id
, $newregion, $newweight);
1485 $this->page
->ensure_param_not_in_url('bui_moveid');
1486 $this->page
->ensure_param_not_in_url('bui_newregion');
1487 $this->page
->ensure_param_not_in_url('bui_newweight');
1492 * Turns the display of normal blocks either on or off.
1494 * @param bool $setting
1496 public function show_only_fake_blocks($setting = true) {
1497 $this->fakeblocksonly
= $setting;
1501 /// Helper functions for working with block classes ============================
1504 * Call a class method (one that does not require a block instance) on a block class.
1506 * @param string $blockname the name of the block.
1507 * @param string $method the method name.
1508 * @param array $param parameters to pass to the method.
1509 * @return mixed whatever the method returns.
1511 function block_method_result($blockname, $method, $param = NULL) {
1512 if(!block_load_class($blockname)) {
1515 return call_user_func(array('block_'.$blockname, $method), $param);
1519 * Creates a new instance of the specified block class.
1521 * @param string $blockname the name of the block.
1522 * @param $instance block_instances DB table row (optional).
1523 * @param moodle_page $page the page this block is appearing on.
1524 * @return block_base the requested block instance.
1526 function block_instance($blockname, $instance = NULL, $page = NULL) {
1527 if(!block_load_class($blockname)) {
1530 $classname = 'block_'.$blockname;
1531 $retval = new $classname;
1532 if($instance !== NULL) {
1533 if (is_null($page)) {
1537 $retval->_load_instance($instance, $page);
1543 * Load the block class for a particular type of block.
1545 * @param string $blockname the name of the block.
1546 * @return boolean success or failure.
1548 function block_load_class($blockname) {
1551 if(empty($blockname)) {
1555 $classname = 'block_'.$blockname;
1557 if(class_exists($classname)) {
1561 $blockpath = $CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1563 if (file_exists($blockpath)) {
1564 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1565 include_once($blockpath);
1567 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1571 return class_exists($classname);
1575 * Given a specific page type, return all the page type patterns that might
1578 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1579 * @return array an array of all the page type patterns that might match this page type.
1581 function matching_page_type_patterns($pagetype) {
1582 $patterns = array($pagetype);
1583 $bits = explode('-', $pagetype);
1584 if (count($bits) == 3 && $bits[0] == 'mod') {
1585 if ($bits[2] == 'view') {
1586 $patterns[] = 'mod-*-view';
1587 } else if ($bits[2] == 'index') {
1588 $patterns[] = 'mod-*-index';
1591 while (count($bits) > 0) {
1592 $patterns[] = implode('-', $bits) . '-*';
1600 * Given a specific page type, parent context and currect context, return all the page type patterns
1601 * that might be used by this block.
1603 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1604 * @param stdClass $parentcontext Block's parent context
1605 * @param stdClass $currentcontext Current context of block
1606 * @return array an array of all the page type patterns that might match this page type.
1608 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1611 $bits = explode('-', $pagetype);
1613 $core = get_core_subsystems();
1614 $plugins = get_plugin_types();
1616 //progressively strip pieces off the page type looking for a match
1617 $componentarray = null;
1618 for ($i = count($bits); $i > 0; $i--) {
1619 $possiblecomponentarray = array_slice($bits, 0, $i);
1620 $possiblecomponent = implode('', $possiblecomponentarray);
1622 // Check to see if the component is a core component
1623 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1624 $libfile = $CFG->dirroot
.'/'.$core[$possiblecomponent].'/lib.php';
1625 if (file_exists($libfile)) {
1626 require_once($libfile);
1627 $function = $possiblecomponent.'_page_type_list';
1628 if (function_exists($function)) {
1629 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1636 //check the plugin directory and look for a callback
1637 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1639 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1640 if (count($bits) > $i) {
1641 $pluginname = $bits[$i];
1642 $directory = get_plugin_directory($possiblecomponent, $pluginname);
1643 if (!empty($directory)){
1644 $libfile = $directory.'/lib.php';
1645 if (file_exists($libfile)) {
1646 require_once($libfile);
1647 $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1648 if (!function_exists($function)) {
1649 $function = $pluginname.'_page_type_list';
1651 if (function_exists($function)) {
1652 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1660 //we'll only get to here if we still don't have any patterns
1661 //the plugin type may have a callback
1662 $directory = get_plugin_directory($possiblecomponent, null);
1663 if (!empty($directory)){
1664 $libfile = $directory.'/lib.php';
1665 if (file_exists($libfile)) {
1666 require_once($libfile);
1667 $function = $possiblecomponent.'_page_type_list';
1668 if (function_exists($function)) {
1669 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1678 if (empty($patterns)) {
1679 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1682 // Ensure that the * pattern is always available if editing block 'at distance', so
1683 // we always can 'bring back' it to the original context. MDL-30340
1684 if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id
!= $parentcontext->id
) && !isset($patterns['*'])) {
1685 // TODO: We could change the string here, showing its 'bring back' meaning
1686 $patterns['*'] = get_string('page-x', 'pagetype');
1693 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1695 * @param string $pagetype
1696 * @param stdClass $parentcontext
1697 * @param stdClass $currentcontext
1700 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1701 // Generate page type patterns based on current page type if
1702 // callbacks haven't been defined
1703 $patterns = array($pagetype => $pagetype);
1704 $bits = explode('-', $pagetype);
1705 while (count($bits) > 0) {
1706 $pattern = implode('-', $bits) . '-*';
1707 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1708 // guessing page type description
1709 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1710 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1712 $patterns[$pattern] = $pattern;
1716 $patterns['*'] = get_string('page-x', 'pagetype');
1721 * Generates the page type list for the my moodle page
1723 * @param string $pagetype
1724 * @param stdClass $parentcontext
1725 * @param stdClass $currentcontext
1728 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1729 return array('my-index' => get_string('page-my-index', 'pagetype'));
1733 * Generates the page type list for a module by either locating and using the modules callback
1734 * or by generating a default list.
1736 * @param string $pagetype
1737 * @param stdClass $parentcontext
1738 * @param stdClass $currentcontext
1741 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1742 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1743 if (empty($patterns)) {
1744 // if modules don't have callbacks
1745 // generate two default page type patterns for modules only
1746 $bits = explode('-', $pagetype);
1747 $patterns = array($pagetype => $pagetype);
1748 if ($bits[2] == 'view') {
1749 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1750 } else if ($bits[2] == 'index') {
1751 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1756 /// Functions update the blocks if required by the request parameters ==========
1759 * Return a {@link block_contents} representing the add a new block UI, if
1760 * this user is allowed to see it.
1762 * @return block_contents an appropriate block_contents, or null if the user
1763 * cannot add any blocks here.
1765 function block_add_block_ui($page, $output) {
1766 global $CFG, $OUTPUT;
1767 if (!$page->user_is_editing() ||
!$page->user_can_edit_blocks()) {
1771 $bc = new block_contents();
1772 $bc->title
= get_string('addblock');
1773 $bc->add_class('block_adminblock');
1775 $missingblocks = $page->blocks
->get_addable_blocks();
1776 if (empty($missingblocks)) {
1777 $bc->content
= get_string('noblockstoaddhere');
1782 foreach ($missingblocks as $block) {
1783 $blockobject = block_instance($block->name
);
1784 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1785 $menu[$block->name
] = $blockobject->get_title();
1788 collatorlib
::asort($menu);
1790 $actionurl = new moodle_url($page->url
, array('sesskey'=>sesskey()));
1791 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1792 $bc->content
= $OUTPUT->render($select);
1796 // Functions that have been deprecated by block_manager =======================
1799 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1801 * This function returns an array with the IDs of any blocks that you can add to your page.
1802 * Parameters are passed by reference for speed; they are not modified at all.
1804 * @param $page the page object.
1805 * @param $blockmanager Not used.
1806 * @return array of block type ids.
1808 function blocks_get_missing(&$page, &$blockmanager) {
1809 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER
);
1810 $blocks = $page->blocks
->get_addable_blocks();
1812 foreach ($blocks as $block) {
1813 $ids[] = $block->id
;
1819 * Actually delete from the database any blocks that are currently on this page,
1820 * but which should not be there according to blocks_name_allowed_in_format.
1822 * @todo Write/Fix this function. Currently returns immediately
1825 function blocks_remove_inappropriate($course) {
1829 $blockmanager = blocks_get_by_page($page);
1831 if (empty($blockmanager)) {
1835 if (($pageformat = $page->pagetype) == NULL) {
1839 foreach($blockmanager as $region) {
1840 foreach($region as $instance) {
1841 $block = blocks_get_record($instance->blockid);
1842 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1843 blocks_delete_instance($instance->instance);
1850 * Check that a given name is in a permittable format
1852 * @param string $name
1853 * @param string $pageformat
1856 function blocks_name_allowed_in_format($name, $pageformat) {
1859 $formats = block_method_result($name, 'applicable_formats');
1863 foreach ($formats as $format => $allowed) {
1864 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1865 $depth = substr_count($format, '-');
1866 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1871 if ($accept === NULL) {
1872 $accept = !empty($formats['all']);
1878 * Delete a block, and associated data.
1880 * @param object $instance a row from the block_instances table
1881 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
1882 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
1884 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
1887 if ($block = block_instance($instance->blockname
, $instance)) {
1888 $block->instance_delete();
1890 delete_context(CONTEXT_BLOCK
, $instance->id
);
1892 if (!$skipblockstables) {
1893 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id
));
1894 $DB->delete_records('block_instances', array('id' => $instance->id
));
1895 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id
.'hidden','docked_block_instance_'.$instance->id
));
1900 * Delete all the blocks that belong to a particular context.
1902 * @param int $contextid the context id.
1904 function blocks_delete_all_for_context($contextid) {
1906 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
1907 foreach ($instances as $instance) {
1908 blocks_delete_instance($instance, true);
1910 $instances->close();
1911 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
1912 $DB->delete_records('block_positions', array('contextid' => $contextid));
1916 * Set a block to be visible or hidden on a particular page.
1918 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
1919 * block_positions table as return by block_manager.
1920 * @param moodle_page $page the back to set the visibility with respect to.
1921 * @param integer $newvisibility 1 for visible, 0 for hidden.
1923 function blocks_set_visibility($instance, $page, $newvisibility) {
1925 if (!empty($instance->blockpositionid
)) {
1926 // Already have local information on this page.
1927 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid
));
1931 // Create a new block_positions record.
1933 $bp->blockinstanceid
= $instance->id
;
1934 $bp->contextid
= $page->context
->id
;
1935 $bp->pagetype
= $page->pagetype
;
1936 if ($page->subpage
) {
1937 $bp->subpage
= $page->subpage
;
1939 $bp->visible
= $newvisibility;
1940 $bp->region
= $instance->defaultregion
;
1941 $bp->weight
= $instance->defaultweight
;
1942 $DB->insert_record('block_positions', $bp);
1946 * @deprecated since 2.0
1947 * Delete all the blocks from a particular page.
1949 * @param string $pagetype the page type.
1950 * @param integer $pageid the page id.
1951 * @return bool success or failure.
1953 function blocks_delete_all_on_page($pagetype, $pageid) {
1956 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
1957 'This function cannot work any more. Doing nothing. ' .
1958 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER
);
1963 * Dispite what this function is called, it seems to be mostly used to populate
1964 * the default blocks when a new course (or whatever) is created.
1966 * @deprecated since 2.0
1968 * @param object $page the page to add default blocks to.
1969 * @return boolean success or failure.
1971 function blocks_repopulate_page($page) {
1974 debugging('Call to deprecated function blocks_repopulate_page. ' .
1975 'Use a more specific method like blocks_add_default_course_blocks, ' .
1976 'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER
);
1978 /// If the site override has been defined, it is the only valid one.
1979 if (!empty($CFG->defaultblocks_override
)) {
1980 $blocknames = $CFG->defaultblocks_override
;
1982 $blocknames = $page->blocks_get_default();
1985 $blocks = blocks_parse_default_blocks_list($blocknames);
1986 $page->blocks
->add_blocks($blocks);
1992 * Get the block record for a particular blockid - that is, a particular type os block.
1994 * @param $int blockid block type id. If null, an array of all block types is returned.
1995 * @param bool $notusedanymore No longer used.
1996 * @return array|object row from block table, or all rows.
1998 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2000 $blocks = $PAGE->blocks
->get_installed_blocks();
2001 if ($blockid === NULL) {
2003 } else if (isset($blocks[$blockid])) {
2004 return $blocks[$blockid];
2011 * Find a given block by its blockid within a provide array
2013 * @param int $blockid
2014 * @param array $blocksarray
2015 * @return bool|object Instance if found else false
2017 function blocks_find_block($blockid, $blocksarray) {
2018 if (empty($blocksarray)) {
2021 foreach($blocksarray as $blockgroup) {
2022 if (empty($blockgroup)) {
2025 foreach($blockgroup as $instance) {
2026 if($instance->blockid
== $blockid) {
2034 // Functions for programatically adding default blocks to pages ================
2037 * Parse a list of default blocks. See config-dist for a description of the format.
2039 * @param string $blocksstr
2042 function blocks_parse_default_blocks_list($blocksstr) {
2044 $bits = explode(':', $blocksstr);
2045 if (!empty($bits)) {
2046 $leftbits = trim(array_shift($bits));
2047 if ($leftbits != '') {
2048 $blocks[BLOCK_POS_LEFT
] = explode(',', $leftbits);
2051 if (!empty($bits)) {
2052 $rightbits =trim(array_shift($bits));
2053 if ($rightbits != '') {
2054 $blocks[BLOCK_POS_RIGHT
] = explode(',', $rightbits);
2061 * @return array the blocks that should be added to the site course by default.
2063 function blocks_get_default_site_course_blocks() {
2066 if (!empty($CFG->defaultblocks_site
)) {
2067 return blocks_parse_default_blocks_list($CFG->defaultblocks_site
);
2070 BLOCK_POS_LEFT
=> array('site_main_menu'),
2071 BLOCK_POS_RIGHT
=> array('course_summary', 'calendar_month')
2077 * Add the default blocks to a course.
2079 * @param object $course a course object.
2081 function blocks_add_default_course_blocks($course) {
2084 if (!empty($CFG->defaultblocks_override
)) {
2085 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override
);
2087 } else if ($course->id
== SITEID
) {
2088 $blocknames = blocks_get_default_site_course_blocks();
2091 $defaultblocks = 'defaultblocks_' . $course->format
;
2092 if (!empty($CFG->$defaultblocks)) {
2093 $blocknames = blocks_parse_default_blocks_list($CFG->$defaultblocks);
2096 $formatconfig = $CFG->dirroot
.'/course/format/'.$course->format
.'/config.php';
2097 $format = array(); // initialize array in external file
2098 if (is_readable($formatconfig)) {
2099 include($formatconfig);
2101 if (!empty($format['defaultblocks'])) {
2102 $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']);
2104 } else if (!empty($CFG->defaultblocks
)){
2105 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks
);
2108 $blocknames = array(
2109 BLOCK_POS_LEFT
=> array(),
2110 BLOCK_POS_RIGHT
=> array('search_forums', 'news_items', 'calendar_upcoming', 'recent_activity')
2116 if ($course->id
== SITEID
) {
2117 $pagetypepattern = 'site-index';
2119 $pagetypepattern = 'course-view-*';
2121 $page = new moodle_page();
2122 $page->set_course($course);
2123 $page->blocks
->add_blocks($blocknames, $pagetypepattern);
2127 * Add the default system-context blocks. E.g. the admin tree.
2129 function blocks_add_default_system_blocks() {
2132 $page = new moodle_page();
2133 $page->set_context(get_context_instance(CONTEXT_SYSTEM
));
2134 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('navigation', 'settings')), '*', null, true);
2135 $page->blocks
->add_blocks(array(BLOCK_POS_LEFT
=> array('admin_bookmarks')), 'admin-*', null, null, 2);
2137 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2138 $subpagepattern = $defaultmypage->id
;
2140 $subpagepattern = null;
2143 $page->blocks
->add_blocks(array(BLOCK_POS_RIGHT
=> array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);