Merge branch 'MDL-29542_m21' of git://github.com/rwijaya/moodle into MOODLE_21_STABLE
[moodle.git] / lib / blocklib.php
blobd8a198732cb6d5d6fc924177a232382d90ed84de
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 * @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);
39 /**#@-*/
41 /**#@+
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');
46 /**#@-*/
48 /**#@+
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);
54 /**#@-*/
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);
63 /**
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
69 * @since Moodle 2.0
71 class block_not_on_page_exception extends moodle_exception {
72 /**
73 * Constructor
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) {
78 $a = new stdClass;
79 $a->instanceid = $instanceid;
80 $a->url = $page->url->out();
81 parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
85 /**
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
92 * @since Moodle 2.0
94 class block_manager {
95 /**
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.
105 * @var moodle_page
107 protected $page;
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);
127 * @var array
129 protected $birecordsbyregion = null;
132 * array region-name => array(block objects); populated as necessary by
133 * the ensure_instances_exist method.
134 * @var array
136 protected $blockinstances = array();
139 * array region-name => array(block_contents objects) what actually needs to
140 * be displayed in each region.
141 * @var array
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.
148 * @var array
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.
159 * @var integer|null
161 protected $movingblock = null;
164 * Show only fake blocks
166 protected $fakeblocksonly = false;
168 /// Constructor ================================================================
171 * 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) {
177 $this->page = $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;
219 // Lazy load.
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)) {
248 return false;
251 foreach ($this->blockinstances as $region) {
252 foreach ($region as $instance) {
253 if (empty($instance->instance->blockname)) {
254 continue;
256 if ($instance->instance->blockname == $blockname) {
257 return true;
261 return false;
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)) {
275 return true;
278 return false;
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)) {
346 return false;
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 // If editing is on, we need all the block regions visible, for the
352 // move blocks UI.
353 return true;
355 return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
359 * Get an array of all of the installed blocks.
361 * @return array contents of the block table.
363 public function get_installed_blocks() {
364 global $DB;
365 if (is_null($this->allblocks)) {
366 $this->allblocks = $DB->get_records('block');
368 return $this->allblocks;
371 /// Setter methods =============================================================
374 * Add a region to a page
376 * @param string $region add a named region where blocks may appear on the
377 * current page. This is an internal name, like 'side-pre', not a string to
378 * display in the UI.
380 public function add_region($region) {
381 $this->check_not_yet_loaded();
382 $this->regions[$region] = 1;
386 * Add an array of regions
387 * @see add_region()
389 * @param array $regions this utility method calls add_region for each array element.
391 public function add_regions($regions) {
392 foreach ($regions as $region) {
393 $this->add_region($region);
398 * Set the default region for new blocks on the page
400 * @param string $defaultregion the internal names of the region where new
401 * blocks should be added by default, and where any blocks from an
402 * unrecognised region are shown.
404 public function set_default_region($defaultregion) {
405 $this->check_not_yet_loaded();
406 if ($defaultregion) {
407 $this->check_region_is_known($defaultregion);
409 $this->defaultregion = $defaultregion;
413 * Add something that looks like a block, but which isn't an actual block_instance,
414 * to this page.
416 * @param block_contents $bc the content of the block-like thing.
417 * @param string $region a block region that exists on this page.
419 public function add_fake_block($bc, $region) {
420 $this->page->initialise_theme_and_output();
421 if (!$this->is_known_region($region)) {
422 $region = $this->get_default_region();
424 if (array_key_exists($region, $this->visibleblockcontent)) {
425 throw new coding_exception('block_manager has already prepared the blocks in region ' .
426 $region . 'for output. It is too late to add a fake block.');
428 $this->extracontent[$region][] = $bc;
432 * When the block_manager class was created, the {@link add_fake_block()}
433 * was called add_pretend_block, which is inconsisted with
434 * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
435 * was renamed to add_fake_block. Please update your code.
436 * @param block_contents $bc the content of the block-like thing.
437 * @param string $region a block region that exists on this page.
439 public function add_pretend_block($bc, $region) {
440 debugging(DEBUG_DEVELOPER, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
441 $this->add_fake_block($bc, $region);
445 * Checks to see whether all of the blocks within the given region are docked
447 * @see region_uses_dock
448 * @param string $region
449 * @return bool True if all of the blocks within that region are docked
451 public function region_completely_docked($region, $output) {
452 if (!$this->page->theme->enable_dock) {
453 return false;
455 $this->check_is_loaded();
456 $this->ensure_content_created($region, $output);
457 foreach($this->visibleblockcontent[$region] as $instance) {
458 if (!empty($instance->content) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
459 return false;
462 return true;
466 * Checks to see whether any of the blocks within the given regions are docked
468 * @see region_completely_docked
469 * @param array|string $regions array of regions (or single region)
470 * @return bool True if any of the blocks within that region are docked
472 public function region_uses_dock($regions, $output) {
473 if (!$this->page->theme->enable_dock) {
474 return false;
476 $this->check_is_loaded();
477 foreach((array)$regions as $region) {
478 $this->ensure_content_created($region, $output);
479 foreach($this->visibleblockcontent[$region] as $instance) {
480 if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
481 return true;
485 return false;
488 /// Actions ====================================================================
491 * This method actually loads the blocks for our page from the database.
493 * @param boolean|null $includeinvisible
494 * null (default) - load hidden blocks if $this->page->user_is_editing();
495 * true - load hidden blocks.
496 * false - don't load hidden blocks.
498 public function load_blocks($includeinvisible = null) {
499 global $DB, $CFG;
501 if (!is_null($this->birecordsbyregion)) {
502 // Already done.
503 return;
506 if ($CFG->version < 2009050619) {
507 // Upgrade/install not complete. Don't try too show any blocks.
508 $this->birecordsbyregion = array();
509 return;
512 // Ensure we have been initialised.
513 if (is_null($this->defaultregion)) {
514 $this->page->initialise_theme_and_output();
515 // If there are still no block regions, then there are no blocks on this page.
516 if (empty($this->regions)) {
517 $this->birecordsbyregion = array();
518 return;
522 // Check if we need to load normal blocks
523 if ($this->fakeblocksonly) {
524 $this->birecordsbyregion = $this->prepare_per_region_arrays();
525 return;
528 if (is_null($includeinvisible)) {
529 $includeinvisible = $this->page->user_is_editing();
531 if ($includeinvisible) {
532 $visiblecheck = '';
533 } else {
534 $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
537 $context = $this->page->context;
538 $contexttest = 'bi.parentcontextid = :contextid2';
539 $parentcontextparams = array();
540 $parentcontextids = get_parent_contexts($context);
541 if ($parentcontextids) {
542 list($parentcontexttest, $parentcontextparams) =
543 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
544 $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
547 $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
548 list($pagetypepatterntest, $pagetypepatternparams) =
549 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
551 list($ccselect, $ccjoin) = context_instance_preload_sql('bi.id', CONTEXT_BLOCK, 'ctx');
553 $params = array(
554 'subpage1' => $this->page->subpage,
555 'subpage2' => $this->page->subpage,
556 'contextid1' => $context->id,
557 'contextid2' => $context->id,
558 'pagetype' => $this->page->pagetype,
560 if ($this->page->subpage === '') {
561 $params['subpage1'] = $DB->sql_empty();
562 $params['subpage2'] = $DB->sql_empty();
564 $sql = "SELECT
565 bi.id,
566 bp.id AS blockpositionid,
567 bi.blockname,
568 bi.parentcontextid,
569 bi.showinsubcontexts,
570 bi.pagetypepattern,
571 bi.subpagepattern,
572 bi.defaultregion,
573 bi.defaultweight,
574 COALESCE(bp.visible, 1) AS visible,
575 COALESCE(bp.region, bi.defaultregion) AS region,
576 COALESCE(bp.weight, bi.defaultweight) AS weight,
577 bi.configdata
578 $ccselect
580 FROM {block_instances} bi
581 JOIN {block} b ON bi.blockname = b.name
582 LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
583 AND bp.contextid = :contextid1
584 AND bp.pagetype = :pagetype
585 AND bp.subpage = :subpage1
586 $ccjoin
588 WHERE
589 $contexttest
590 AND bi.pagetypepattern $pagetypepatterntest
591 AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
592 $visiblecheck
593 AND b.visible = 1
595 ORDER BY
596 COALESCE(bp.region, bi.defaultregion),
597 COALESCE(bp.weight, bi.defaultweight),
598 bi.id";
599 $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
601 $this->birecordsbyregion = $this->prepare_per_region_arrays();
602 $unknown = array();
603 foreach ($blockinstances as $bi) {
604 context_instance_preload($bi);
605 if ($this->is_known_region($bi->region)) {
606 $this->birecordsbyregion[$bi->region][] = $bi;
607 } else {
608 $unknown[] = $bi;
612 // Pages don't necessarily have a defaultregion. The one time this can
613 // happen is when there are no theme block regions, but the script itself
614 // has a block region in the main content area.
615 if (!empty($this->defaultregion)) {
616 $this->birecordsbyregion[$this->defaultregion] =
617 array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
622 * Add a block to the current page, or related pages. The block is added to
623 * context $this->page->contextid. If $pagetypepattern $subpagepattern
625 * @param string $blockname The type of block to add.
626 * @param string $region the block region on this page to add the block to.
627 * @param integer $weight determines the order where this block appears in the region.
628 * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
629 * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
630 * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
632 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
633 global $DB;
634 // Allow invisible blocks because this is used when adding default page blocks, which
635 // might include invisible ones if the user makes some default blocks invisible
636 $this->check_known_block_type($blockname, true);
637 $this->check_region_is_known($region);
639 if (empty($pagetypepattern)) {
640 $pagetypepattern = $this->page->pagetype;
643 $blockinstance = new stdClass;
644 $blockinstance->blockname = $blockname;
645 $blockinstance->parentcontextid = $this->page->context->id;
646 $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
647 $blockinstance->pagetypepattern = $pagetypepattern;
648 $blockinstance->subpagepattern = $subpagepattern;
649 $blockinstance->defaultregion = $region;
650 $blockinstance->defaultweight = $weight;
651 $blockinstance->configdata = '';
652 $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
654 // Ensure the block context is created.
655 get_context_instance(CONTEXT_BLOCK, $blockinstance->id);
657 // If the new instance was created, allow it to do additional setup
658 if ($block = block_instance($blockname, $blockinstance)) {
659 $block->instance_create();
663 public function add_block_at_end_of_default_region($blockname) {
664 $defaulregion = $this->get_default_region();
666 $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
667 if ($lastcurrentblock) {
668 $weight = $lastcurrentblock->weight + 1;
669 } else {
670 $weight = 0;
673 if ($this->page->subpage) {
674 $subpage = $this->page->subpage;
675 } else {
676 $subpage = null;
679 // Special case. Course view page type include the course format, but we
680 // want to add the block non-format-specifically.
681 $pagetypepattern = $this->page->pagetype;
682 if (strpos($pagetypepattern, 'course-view') === 0) {
683 $pagetypepattern = 'course-view-*';
686 // We should end using this for ALL the blocks, making always the 1st option
687 // the default one to be used. Until then, this is one hack to avoid the
688 // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
689 // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
690 // (the FIRST $pagetypepattern will be set)
692 // We are applying it to all blocks created in mod pages for now and only if the
693 // default pagetype is not one of the available options
694 if (preg_match('/^mod-.*-/', $pagetypepattern)) {
695 $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
696 // Only go for the first if the pagetype is not a valid option
697 if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
698 $pagetypepattern = key($pagetypelist);
701 // Surely other pages like course-report will need this too, they just are not important
702 // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
704 $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
708 * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
710 * @param array $blocks array with array keys the region names, and values an array of block names.
711 * @param string $pagetypepattern optional. Passed to @see add_block()
712 * @param string $subpagepattern optional. Passed to @see add_block()
714 public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
715 $this->add_regions(array_keys($blocks));
716 foreach ($blocks as $region => $regionblocks) {
717 $weight = 0;
718 foreach ($regionblocks as $blockname) {
719 $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
720 $weight += 1;
726 * Move a block to a new position on this page.
728 * If this block cannot appear on any other pages, then we change defaultposition/weight
729 * in the block_instances table. Otherwise we just set the position on this page.
731 * @param $blockinstanceid the block instance id.
732 * @param $newregion the new region name.
733 * @param $newweight the new weight.
735 public function reposition_block($blockinstanceid, $newregion, $newweight) {
736 global $DB;
738 $this->check_region_is_known($newregion);
739 $inst = $this->find_instance($blockinstanceid);
741 $bi = $inst->instance;
742 if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
743 !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
744 (!$this->page->subpage || $bi->subpagepattern)) {
746 // Set default position
747 $newbi = new stdClass;
748 $newbi->id = $bi->id;
749 $newbi->defaultregion = $newregion;
750 $newbi->defaultweight = $newweight;
751 $DB->update_record('block_instances', $newbi);
753 if ($bi->blockpositionid) {
754 $bp = new stdClass;
755 $bp->id = $bi->blockpositionid;
756 $bp->region = $newregion;
757 $bp->weight = $newweight;
758 $DB->update_record('block_positions', $bp);
761 } else {
762 // Just set position on this page.
763 $bp = new stdClass;
764 $bp->region = $newregion;
765 $bp->weight = $newweight;
767 if ($bi->blockpositionid) {
768 $bp->id = $bi->blockpositionid;
769 $DB->update_record('block_positions', $bp);
771 } else {
772 $bp->blockinstanceid = $bi->id;
773 $bp->contextid = $this->page->context->id;
774 $bp->pagetype = $this->page->pagetype;
775 if ($this->page->subpage) {
776 $bp->subpage = $this->page->subpage;
777 } else {
778 $bp->subpage = '';
780 $bp->visible = $bi->visible;
781 $DB->insert_record('block_positions', $bp);
787 * Find a given block by its instance id
789 * @param integer $instanceid
790 * @return object
792 public function find_instance($instanceid) {
793 foreach ($this->regions as $region => $notused) {
794 $this->ensure_instances_exist($region);
795 foreach($this->blockinstances[$region] as $instance) {
796 if ($instance->instance->id == $instanceid) {
797 return $instance;
801 throw new block_not_on_page_exception($instanceid, $this->page);
804 /// Inner workings =============================================================
807 * Check whether the page blocks have been loaded yet
809 * @return void Throws coding exception if already loaded
811 protected function check_not_yet_loaded() {
812 if (!is_null($this->birecordsbyregion)) {
813 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.');
818 * Check whether the page blocks have been loaded yet
820 * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
822 * @return void Throws coding exception if already loaded
824 protected function check_is_loaded() {
825 if (is_null($this->birecordsbyregion)) {
826 throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
831 * Check if a block type is known and usable
833 * @param string $blockname The block type name to search for
834 * @param bool $includeinvisible Include disabled block types in the initial pass
835 * @return void Coding Exception thrown if unknown or not enabled
837 protected function check_known_block_type($blockname, $includeinvisible = false) {
838 if (!$this->is_known_block_type($blockname, $includeinvisible)) {
839 if ($this->is_known_block_type($blockname, true)) {
840 throw new coding_exception('Unknown block type ' . $blockname);
841 } else {
842 throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
848 * Check if a region is known by its name
850 * @param string $region
851 * @return void Coding Exception thrown if the region is not known
853 protected function check_region_is_known($region) {
854 if (!$this->is_known_region($region)) {
855 throw new coding_exception('Trying to reference an unknown block region ' . $region);
860 * Returns an array of region names as keys and nested arrays for values
862 * @return array an array where the array keys are the region names, and the array
863 * values are empty arrays.
865 protected function prepare_per_region_arrays() {
866 $result = array();
867 foreach ($this->regions as $region => $notused) {
868 $result[$region] = array();
870 return $result;
874 * Create a set of new block instance from a record array
876 * @param array $birecords An array of block instance records
877 * @return array An array of instantiated block_instance objects
879 protected function create_block_instances($birecords) {
880 $results = array();
881 foreach ($birecords as $record) {
882 if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
883 $results[] = $blockobject;
886 return $results;
890 * Create all the block instances for all the blocks that were loaded by
891 * load_blocks. This is used, for example, to ensure that all blocks get a
892 * chance to initialise themselves via the {@link block_base::specialize()}
893 * method, before any output is done.
895 public function create_all_block_instances() {
896 foreach ($this->get_regions() as $region) {
897 $this->ensure_instances_exist($region);
902 * Return an array of content objects from a set of block instances
904 * @param array $instances An array of block instances
905 * @param renderer_base The renderer to use.
906 * @param string $region the region name.
907 * @return array An array of block_content (and possibly block_move_target) objects.
909 protected function create_block_contents($instances, $output, $region) {
910 $results = array();
912 $lastweight = 0;
913 $lastblock = 0;
914 if ($this->movingblock) {
915 $first = reset($instances);
916 if ($first) {
917 $lastweight = $first->instance->weight - 2;
920 $strmoveblockhere = get_string('moveblockhere', 'block');
923 foreach ($instances as $instance) {
924 $content = $instance->get_content_for_output($output);
925 if (empty($content)) {
926 continue;
929 if ($this->movingblock && $lastweight != $instance->instance->weight &&
930 $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
931 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
934 if ($content->blockinstanceid == $this->movingblock) {
935 $content->add_class('beingmoved');
936 $content->annotation .= get_string('movingthisblockcancel', 'block',
937 html_writer::link($this->page->url, get_string('cancel')));
940 $results[] = $content;
941 $lastweight = $instance->instance->weight;
942 $lastblock = $instance->instance->id;
945 if ($this->movingblock && $lastblock != $this->movingblock) {
946 $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1));
948 return $results;
952 * Ensure block instances exist for a given region
954 * @param string $region Check for bi's with the instance with this name
956 protected function ensure_instances_exist($region) {
957 $this->check_region_is_known($region);
958 if (!array_key_exists($region, $this->blockinstances)) {
959 $this->blockinstances[$region] =
960 $this->create_block_instances($this->birecordsbyregion[$region]);
965 * Ensure that there is some content within the given region
967 * @param string $region The name of the region to check
969 protected function ensure_content_created($region, $output) {
970 $this->ensure_instances_exist($region);
971 if (!array_key_exists($region, $this->visibleblockcontent)) {
972 $contents = array();
973 if (array_key_exists($region, $this->extracontent)) {
974 $contents = $this->extracontent[$region];
976 $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
977 if ($region == $this->defaultregion) {
978 $addblockui = block_add_block_ui($this->page, $output);
979 if ($addblockui) {
980 $contents[] = $addblockui;
983 $this->visibleblockcontent[$region] = $contents;
987 /// Process actions from the URL ===============================================
990 * Get the appropriate list of editing icons for a block. This is used
991 * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
993 * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
994 * @return an array in the format for {@link block_contents::$controls}
996 public function edit_controls($block) {
997 global $CFG;
999 if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
1000 $undeletableblocktypes = array('navigation','settings');
1001 } else if (is_string($CFG->undeletableblocktypes)) {
1002 $undeletableblocktypes = explode(',', $CFG->undeletableblocktypes);
1003 } else {
1004 $undeletableblocktypes = $CFG->undeletableblocktypes;
1007 $controls = array();
1008 $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1010 // Assign roles icon.
1011 if (has_capability('moodle/role:assign', $block->context)) {
1012 //TODO: please note it is sloppy to pass urls through page parameters!!
1013 // it is shortened because some web servers (e.g. IIS by default) give
1014 // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1016 $return = $this->page->url->out(false);
1017 $return = str_replace($CFG->wwwroot . '/', '', $return);
1019 $controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin .
1020 '/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return),
1021 'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));
1024 if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1025 // Show/hide icon.
1026 if ($block->instance->visible) {
1027 $controls[] = array('url' => $actionurl . '&bui_hideid=' . $block->instance->id,
1028 'icon' => 't/hide', 'caption' => get_string('hide'));
1029 } else {
1030 $controls[] = array('url' => $actionurl . '&bui_showid=' . $block->instance->id,
1031 'icon' => 't/show', 'caption' => get_string('show'));
1035 if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1036 // Edit config icon - always show - needed for positioning UI.
1037 $controls[] = array('url' => $actionurl . '&bui_editid=' . $block->instance->id,
1038 'icon' => 't/edit', 'caption' => get_string('configuration'));
1041 if ($this->page->user_can_edit_blocks() && $block->user_can_edit() && $block->user_can_addto($this->page)) {
1042 if (!in_array($block->instance->blockname, $undeletableblocktypes)
1043 || !in_array($block->instance->pagetypepattern, array('*', 'site-index'))
1044 || $block->instance->parentcontextid != SITEID) {
1045 // Delete icon.
1046 $controls[] = array('url' => $actionurl . '&bui_deleteid=' . $block->instance->id,
1047 'icon' => 't/delete', 'caption' => get_string('delete'));
1051 if ($this->page->user_can_edit_blocks()) {
1052 // Move icon.
1053 $controls[] = array('url' => $actionurl . '&bui_moveid=' . $block->instance->id,
1054 'icon' => 't/move', 'caption' => get_string('move'));
1057 return $controls;
1061 * Process any block actions that were specified in the URL.
1063 * This can only be done given a valid $page object.
1065 * @param moodle_page $page the page to add blocks to.
1066 * @return boolean true if anything was done. False if not.
1068 public function process_url_actions() {
1069 if (!$this->page->user_is_editing()) {
1070 return false;
1072 return $this->process_url_add() || $this->process_url_delete() ||
1073 $this->process_url_show_hide() || $this->process_url_edit() ||
1074 $this->process_url_move();
1078 * Handle adding a block.
1079 * @return boolean true if anything was done. False if not.
1081 public function process_url_add() {
1082 $blocktype = optional_param('bui_addblock', null, PARAM_SAFEDIR);
1083 if (!$blocktype) {
1084 return false;
1087 require_sesskey();
1089 if (!$this->page->user_can_edit_blocks()) {
1090 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1093 if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1094 throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1097 $this->add_block_at_end_of_default_region($blocktype);
1099 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1100 $this->page->ensure_param_not_in_url('bui_addblock');
1102 return true;
1106 * Handle deleting a block.
1107 * @return boolean true if anything was done. False if not.
1109 public function process_url_delete() {
1110 $blockid = optional_param('bui_deleteid', null, PARAM_INTEGER);
1111 if (!$blockid) {
1112 return false;
1115 require_sesskey();
1117 $block = $this->page->blocks->find_instance($blockid);
1119 if (!$block->user_can_edit() || !$this->page->user_can_edit_blocks() || !$block->user_can_addto($this->page)) {
1120 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1123 blocks_delete_instance($block->instance);
1125 // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1126 $this->page->ensure_param_not_in_url('bui_deleteid');
1128 return true;
1132 * Handle showing or hiding a block.
1133 * @return boolean true if anything was done. False if not.
1135 public function process_url_show_hide() {
1136 if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER)) {
1137 $newvisibility = 0;
1138 } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER)) {
1139 $newvisibility = 1;
1140 } else {
1141 return false;
1144 require_sesskey();
1146 $block = $this->page->blocks->find_instance($blockid);
1148 if (!$this->page->user_can_edit_blocks()) {
1149 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1150 } else if (!$block->instance_can_be_hidden()) {
1151 return false;
1154 blocks_set_visibility($block->instance, $this->page, $newvisibility);
1156 // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1157 $this->page->ensure_param_not_in_url('bui_hideid');
1158 $this->page->ensure_param_not_in_url('bui_showid');
1160 return true;
1164 * Handle showing/processing the submission from the block editing form.
1165 * @return boolean true if the form was submitted and the new config saved. Does not
1166 * return if the editing form was displayed. False otherwise.
1168 public function process_url_edit() {
1169 global $CFG, $DB, $PAGE, $OUTPUT;
1171 $blockid = optional_param('bui_editid', null, PARAM_INTEGER);
1172 if (!$blockid) {
1173 return false;
1176 require_sesskey();
1177 require_once($CFG->dirroot . '/blocks/edit_form.php');
1179 $block = $this->find_instance($blockid);
1181 if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1182 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1185 $editpage = new moodle_page();
1186 $editpage->set_pagelayout('admin');
1187 $editpage->set_course($this->page->course);
1188 //$editpage->set_context($block->context);
1189 $editpage->set_context($this->page->context);
1190 if ($this->page->cm) {
1191 $editpage->set_cm($this->page->cm);
1193 $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1194 $editurlparams = $this->page->url->params();
1195 $editurlparams['bui_editid'] = $blockid;
1196 $editpage->set_url($editurlbase, $editurlparams);
1197 $editpage->set_block_actions_done();
1198 // At this point we are either going to redirect, or display the form, so
1199 // overwrite global $PAGE ready for this. (Formslib refers to it.)
1200 $PAGE = $editpage;
1201 //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1202 $output = $editpage->get_renderer('core');
1203 $OUTPUT = $output;
1205 $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1206 if (is_readable($formfile)) {
1207 require_once($formfile);
1208 $classname = 'block_' . $block->name() . '_edit_form';
1209 if (!class_exists($classname)) {
1210 $classname = 'block_edit_form';
1212 } else {
1213 $classname = 'block_edit_form';
1216 $mform = new $classname($editpage->url, $block, $this->page);
1217 $mform->set_data($block->instance);
1219 if ($mform->is_cancelled()) {
1220 redirect($this->page->url);
1222 } else if ($data = $mform->get_data()) {
1223 $bi = new stdClass;
1224 $bi->id = $block->instance->id;
1225 $bi->pagetypepattern = $data->bui_pagetypepattern;
1226 if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1227 $bi->subpagepattern = null;
1228 } else {
1229 $bi->subpagepattern = $data->bui_subpagepattern;
1232 $parentcontext = get_context_instance_by_id($data->bui_parentcontextid);
1233 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1235 // Updating stickiness and contexts. See MDL-21375 for details.
1236 if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1237 // Explicitly set the context
1238 $bi->parentcontextid = $parentcontext->id;
1240 // If the context type is > 0 then we'll explicitly set the block as sticky, otherwise not
1241 $bi->showinsubcontexts = (int)(!empty($data->bui_contexts));
1243 // If the block wants to be system-wide, then explicitly set that
1244 if ($data->bui_contexts == BUI_CONTEXTS_ENTIRE_SITE) { // Only possible on a frontpage or system page
1245 $bi->parentcontextid = $systemcontext->id;
1246 $bi->showinsubcontexts = BUI_CONTEXTS_CURRENT_SUBS; //show in current and sub contexts
1247 $bi->pagetypepattern = '*';
1249 } else { // The block doesn't want to be system-wide, so let's ensure that
1250 if ($parentcontext->id == $systemcontext->id) { // We need to move it to the front page
1251 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1252 $bi->parentcontextid = $frontpagecontext->id;
1253 $bi->pagetypepattern = 'site-index';
1258 $bits = explode('-', $bi->pagetypepattern);
1259 // hacks for some contexts
1260 if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1261 // For course context
1262 // is page type pattern is mod-*, change showinsubcontext to 1
1263 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1264 $bi->showinsubcontexts = 1;
1265 } else {
1266 $bi->showinsubcontexts = 0;
1268 } else if ($parentcontext->contextlevel == CONTEXT_USER) {
1269 // for user context
1270 // subpagepattern should be null
1271 if ($bits[0] == 'user' or $bits[0] == 'my') {
1272 // we don't need subpagepattern in usercontext
1273 $bi->subpagepattern = null;
1277 $bi->defaultregion = $data->bui_defaultregion;
1278 $bi->defaultweight = $data->bui_defaultweight;
1279 $DB->update_record('block_instances', $bi);
1281 if (!empty($block->config)) {
1282 $config = clone($block->config);
1283 } else {
1284 $config = new stdClass;
1286 foreach ($data as $configfield => $value) {
1287 if (strpos($configfield, 'config_') !== 0) {
1288 continue;
1290 $field = substr($configfield, 7);
1291 $config->$field = $value;
1293 $block->instance_config_save($config);
1295 $bp = new stdClass;
1296 $bp->visible = $data->bui_visible;
1297 $bp->region = $data->bui_region;
1298 $bp->weight = $data->bui_weight;
1299 $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1300 $data->bui_weight != $data->bui_defaultweight;
1302 if ($block->instance->blockpositionid && !$needbprecord) {
1303 $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1305 } else if ($block->instance->blockpositionid && $needbprecord) {
1306 $bp->id = $block->instance->blockpositionid;
1307 $DB->update_record('block_positions', $bp);
1309 } else if ($needbprecord) {
1310 $bp->blockinstanceid = $block->instance->id;
1311 $bp->contextid = $this->page->context->id;
1312 $bp->pagetype = $this->page->pagetype;
1313 if ($this->page->subpage) {
1314 $bp->subpage = $this->page->subpage;
1315 } else {
1316 $bp->subpage = '';
1318 $DB->insert_record('block_positions', $bp);
1321 redirect($this->page->url);
1323 } else {
1324 $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1325 $editpage->set_title($strheading);
1326 $editpage->set_heading($strheading);
1327 $bits = explode('-', $this->page->pagetype);
1328 if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1329 // better navbar for tag pages
1330 $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1331 $tag = tag_get('id', $this->page->subpage, '*');
1332 // tag search page doesn't have subpageid
1333 if ($tag) {
1334 $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1337 $editpage->navbar->add($block->get_title());
1338 $editpage->navbar->add(get_string('configuration'));
1339 echo $output->header();
1340 echo $output->heading($strheading, 2);
1341 $mform->display();
1342 echo $output->footer();
1343 exit;
1348 * Handle showing/processing the submission from the block editing form.
1349 * @return boolean true if the form was submitted and the new config saved. Does not
1350 * return if the editing form was displayed. False otherwise.
1352 public function process_url_move() {
1353 global $CFG, $DB, $PAGE;
1355 $blockid = optional_param('bui_moveid', null, PARAM_INTEGER);
1356 if (!$blockid) {
1357 return false;
1360 require_sesskey();
1362 $block = $this->find_instance($blockid);
1364 if (!$this->page->user_can_edit_blocks()) {
1365 throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1368 $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1369 $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1370 if (!$newregion || is_null($newweight)) {
1371 // Don't have a valid target position yet, must be just starting the move.
1372 $this->movingblock = $blockid;
1373 $this->page->ensure_param_not_in_url('bui_moveid');
1374 return false;
1377 if (!$this->is_known_region($newregion)) {
1378 throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1381 // Move this block. This may involve moving other nearby blocks.
1382 $blocks = $this->birecordsbyregion[$newregion];
1384 $maxweight = self::MAX_WEIGHT;
1385 $minweight = -self::MAX_WEIGHT;
1387 // Initialise the used weights and spareweights array with the default values
1388 $spareweights = array();
1389 $usedweights = array();
1390 for ($i = $minweight; $i <= $maxweight; $i++) {
1391 $spareweights[$i] = $i;
1392 $usedweights[$i] = array();
1395 // Check each block and sort out where we have used weights
1396 foreach ($blocks as $bi) {
1397 if ($bi->weight > $maxweight) {
1398 // If this statement is true then the blocks weight is more than the
1399 // current maximum. To ensure that we can get the best block position
1400 // we will initialise elements within the usedweights and spareweights
1401 // arrays between the blocks weight (which will then be the new max) and
1402 // the current max
1403 $parseweight = $bi->weight;
1404 while (!array_key_exists($parseweight, $usedweights)) {
1405 $usedweights[$parseweight] = array();
1406 $spareweights[$parseweight] = $parseweight;
1407 $parseweight--;
1409 $maxweight = $bi->weight;
1410 } else if ($bi->weight < $minweight) {
1411 // As above except this time the blocks weight is LESS than the
1412 // the current minimum, so we will initialise the array from the
1413 // blocks weight (new minimum) to the current minimum
1414 $parseweight = $bi->weight;
1415 while (!array_key_exists($parseweight, $usedweights)) {
1416 $usedweights[$parseweight] = array();
1417 $spareweights[$parseweight] = $parseweight;
1418 $parseweight++;
1420 $minweight = $bi->weight;
1422 if ($bi->id != $block->instance->id) {
1423 unset($spareweights[$bi->weight]);
1424 $usedweights[$bi->weight][] = $bi->id;
1428 // First we find the nearest gap in the list of weights.
1429 $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1430 $bestgap = null;
1431 foreach ($spareweights as $spareweight) {
1432 if (abs($newweight - $spareweight) < $bestdistance) {
1433 $bestdistance = abs($newweight - $spareweight);
1434 $bestgap = $spareweight;
1438 // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1439 if (is_null($bestgap)) {
1440 $bestgap = self::MAX_WEIGHT + 1;
1441 while (!empty($usedweights[$bestgap])) {
1442 $bestgap++;
1446 // Now we know the gap we are aiming for, so move all the blocks along.
1447 if ($bestgap < $newweight) {
1448 $newweight = floor($newweight);
1449 for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1450 foreach ($usedweights[$weight] as $biid) {
1451 $this->reposition_block($biid, $newregion, $weight - 1);
1454 $this->reposition_block($block->instance->id, $newregion, $newweight);
1455 } else {
1456 $newweight = ceil($newweight);
1457 for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1458 foreach ($usedweights[$weight] as $biid) {
1459 $this->reposition_block($biid, $newregion, $weight + 1);
1462 $this->reposition_block($block->instance->id, $newregion, $newweight);
1465 $this->page->ensure_param_not_in_url('bui_moveid');
1466 $this->page->ensure_param_not_in_url('bui_newregion');
1467 $this->page->ensure_param_not_in_url('bui_newweight');
1468 return true;
1472 * Turns the display of normal blocks either on or off.
1474 * @param bool $setting
1476 public function show_only_fake_blocks($setting = true) {
1477 $this->fakeblocksonly = $setting;
1481 /// Helper functions for working with block classes ============================
1484 * Call a class method (one that does not require a block instance) on a block class.
1486 * @param string $blockname the name of the block.
1487 * @param string $method the method name.
1488 * @param array $param parameters to pass to the method.
1489 * @return mixed whatever the method returns.
1491 function block_method_result($blockname, $method, $param = NULL) {
1492 if(!block_load_class($blockname)) {
1493 return NULL;
1495 return call_user_func(array('block_'.$blockname, $method), $param);
1499 * Creates a new instance of the specified block class.
1501 * @param string $blockname the name of the block.
1502 * @param $instance block_instances DB table row (optional).
1503 * @param moodle_page $page the page this block is appearing on.
1504 * @return block_base the requested block instance.
1506 function block_instance($blockname, $instance = NULL, $page = NULL) {
1507 if(!block_load_class($blockname)) {
1508 return false;
1510 $classname = 'block_'.$blockname;
1511 $retval = new $classname;
1512 if($instance !== NULL) {
1513 if (is_null($page)) {
1514 global $PAGE;
1515 $page = $PAGE;
1517 $retval->_load_instance($instance, $page);
1519 return $retval;
1523 * Load the block class for a particular type of block.
1525 * @param string $blockname the name of the block.
1526 * @return boolean success or failure.
1528 function block_load_class($blockname) {
1529 global $CFG;
1531 if(empty($blockname)) {
1532 return false;
1535 $classname = 'block_'.$blockname;
1537 if(class_exists($classname)) {
1538 return true;
1541 $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1543 if (file_exists($blockpath)) {
1544 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1545 include_once($blockpath);
1546 }else{
1547 //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1548 return false;
1551 return class_exists($classname);
1555 * Given a specific page type, return all the page type patterns that might
1556 * match it.
1558 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1559 * @return array an array of all the page type patterns that might match this page type.
1561 function matching_page_type_patterns($pagetype) {
1562 $patterns = array($pagetype);
1563 $bits = explode('-', $pagetype);
1564 if (count($bits) == 3 && $bits[0] == 'mod') {
1565 if ($bits[2] == 'view') {
1566 $patterns[] = 'mod-*-view';
1567 } else if ($bits[2] == 'index') {
1568 $patterns[] = 'mod-*-index';
1571 while (count($bits) > 0) {
1572 $patterns[] = implode('-', $bits) . '-*';
1573 array_pop($bits);
1575 $patterns[] = '*';
1576 return $patterns;
1580 * Given a specific page type, parent context and currect context, return all the page type patterns
1581 * that might be used by this block.
1583 * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1584 * @param stdClass $parentcontext Block's parent context
1585 * @param stdClass $currentcontext Current context of block
1586 * @return array an array of all the page type patterns that might match this page type.
1588 function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1589 global $CFG;
1591 $bits = explode('-', $pagetype);
1593 $core = get_core_subsystems();
1594 $plugins = get_plugin_types();
1596 //progressively strip pieces off the page type looking for a match
1597 $componentarray = null;
1598 for ($i = count($bits); $i > 0; $i--) {
1599 $possiblecomponentarray = array_slice($bits, 0, $i);
1600 $possiblecomponent = implode('', $possiblecomponentarray);
1602 // Check to see if the component is a core component
1603 if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1604 $libfile = $CFG->dirroot.'/'.$core[$possiblecomponent].'/lib.php';
1605 if (file_exists($libfile)) {
1606 require_once($libfile);
1607 $function = $possiblecomponent.'_page_type_list';
1608 if (function_exists($function)) {
1609 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1610 break;
1616 //check the plugin directory and look for a callback
1617 if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1619 //We've found a plugin type. Look for a plugin name by getting the next section of page type
1620 if (count($bits) > $i) {
1621 $pluginname = $bits[$i];
1622 $directory = get_plugin_directory($possiblecomponent, $pluginname);
1623 if (!empty($directory)){
1624 $libfile = $directory.'/lib.php';
1625 if (file_exists($libfile)) {
1626 require_once($libfile);
1627 $function = $pluginname.'_page_type_list';
1628 if (function_exists($function)) {
1629 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1630 break;
1637 //we'll only get to here if we still don't have any patterns
1638 //the plugin type may have a callback
1639 $directory = get_plugin_directory($possiblecomponent, null);
1640 if (!empty($directory)){
1641 $libfile = $directory.'/lib.php';
1642 if (file_exists($libfile)) {
1643 require_once($libfile);
1644 $function = $possiblecomponent.'_page_type_list';
1645 if (function_exists($function)) {
1646 if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1647 break;
1655 if (empty($patterns)) {
1656 $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1659 return $patterns;
1663 * Generates a default page type list when a more appropriate callback cannot be decided upon.
1665 * @param string $pagetype
1666 * @param stdClass $parentcontext
1667 * @param stdClass $currentcontext
1668 * @return array
1670 function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1671 // Generate page type patterns based on current page type if
1672 // callbacks haven't been defined
1673 $patterns = array($pagetype => $pagetype);
1674 $bits = explode('-', $pagetype);
1675 while (count($bits) > 0) {
1676 $pattern = implode('-', $bits) . '-*';
1677 $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1678 // guessing page type description
1679 if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1680 $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1681 } else {
1682 $patterns[$pattern] = $pattern;
1684 array_pop($bits);
1686 $patterns['*'] = get_string('page-x', 'pagetype');
1687 return $patterns;
1691 * Generates the page type list for the my moodle page
1693 * @param string $pagetype
1694 * @param stdClass $parentcontext
1695 * @param stdClass $currentcontext
1696 * @return array
1698 function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1699 return array('my-index' => 'my-index');
1703 * Generates the page type list for a module by either locating and using the modules callback
1704 * or by generating a default list.
1706 * @param string $pagetype
1707 * @param stdClass $parentcontext
1708 * @param stdClass $currentcontext
1709 * @return array
1711 function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1712 $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1713 if (empty($patterns)) {
1714 // if modules don't have callbacks
1715 // generate two default page type patterns for modules only
1716 $bits = explode('-', $pagetype);
1717 $patterns = array($pagetype => $pagetype);
1718 if ($bits[2] == 'view') {
1719 $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1720 } else if ($bits[2] == 'index') {
1721 $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1724 return $patterns;
1726 /// Functions update the blocks if required by the request parameters ==========
1729 * Return a {@link block_contents} representing the add a new block UI, if
1730 * this user is allowed to see it.
1732 * @return block_contents an appropriate block_contents, or null if the user
1733 * cannot add any blocks here.
1735 function block_add_block_ui($page, $output) {
1736 global $CFG, $OUTPUT;
1737 if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1738 return null;
1741 $bc = new block_contents();
1742 $bc->title = get_string('addblock');
1743 $bc->add_class('block_adminblock');
1745 $missingblocks = $page->blocks->get_addable_blocks();
1746 if (empty($missingblocks)) {
1747 $bc->content = get_string('noblockstoaddhere');
1748 return $bc;
1751 $menu = array();
1752 foreach ($missingblocks as $block) {
1753 $blockobject = block_instance($block->name);
1754 if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1755 $menu[$block->name] = $blockobject->get_title();
1758 textlib_get_instance()->asort($menu);
1760 $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1761 $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1762 $bc->content = $OUTPUT->render($select);
1763 return $bc;
1766 // Functions that have been deprecated by block_manager =======================
1769 * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
1771 * This function returns an array with the IDs of any blocks that you can add to your page.
1772 * Parameters are passed by reference for speed; they are not modified at all.
1774 * @param $page the page object.
1775 * @param $blockmanager Not used.
1776 * @return array of block type ids.
1778 function blocks_get_missing(&$page, &$blockmanager) {
1779 debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER);
1780 $blocks = $page->blocks->get_addable_blocks();
1781 $ids = array();
1782 foreach ($blocks as $block) {
1783 $ids[] = $block->id;
1785 return $ids;
1789 * Actually delete from the database any blocks that are currently on this page,
1790 * but which should not be there according to blocks_name_allowed_in_format.
1792 * @todo Write/Fix this function. Currently returns immediately
1793 * @param $course
1795 function blocks_remove_inappropriate($course) {
1796 // TODO
1797 return;
1799 $blockmanager = blocks_get_by_page($page);
1801 if (empty($blockmanager)) {
1802 return;
1805 if (($pageformat = $page->pagetype) == NULL) {
1806 return;
1809 foreach($blockmanager as $region) {
1810 foreach($region as $instance) {
1811 $block = blocks_get_record($instance->blockid);
1812 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1813 blocks_delete_instance($instance->instance);
1820 * Check that a given name is in a permittable format
1822 * @param string $name
1823 * @param string $pageformat
1824 * @return bool
1826 function blocks_name_allowed_in_format($name, $pageformat) {
1827 $accept = NULL;
1828 $maxdepth = -1;
1829 $formats = block_method_result($name, 'applicable_formats');
1830 if (!$formats) {
1831 $formats = array();
1833 foreach ($formats as $format => $allowed) {
1834 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1835 $depth = substr_count($format, '-');
1836 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1837 $maxdepth = $depth;
1838 $accept = $allowed;
1841 if ($accept === NULL) {
1842 $accept = !empty($formats['all']);
1844 return $accept;
1848 * Delete a block, and associated data.
1850 * @param object $instance a row from the block_instances table
1851 * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
1852 * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
1854 function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
1855 global $DB;
1857 if ($block = block_instance($instance->blockname, $instance)) {
1858 $block->instance_delete();
1860 delete_context(CONTEXT_BLOCK, $instance->id);
1862 if (!$skipblockstables) {
1863 $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
1864 $DB->delete_records('block_instances', array('id' => $instance->id));
1865 $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
1870 * Delete all the blocks that belong to a particular context.
1872 * @param int $contextid the context id.
1874 function blocks_delete_all_for_context($contextid) {
1875 global $DB;
1876 $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
1877 foreach ($instances as $instance) {
1878 blocks_delete_instance($instance, true);
1880 $instances->close();
1881 $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
1882 $DB->delete_records('block_positions', array('contextid' => $contextid));
1886 * Set a block to be visible or hidden on a particular page.
1888 * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
1889 * block_positions table as return by block_manager.
1890 * @param moodle_page $page the back to set the visibility with respect to.
1891 * @param integer $newvisibility 1 for visible, 0 for hidden.
1893 function blocks_set_visibility($instance, $page, $newvisibility) {
1894 global $DB;
1895 if (!empty($instance->blockpositionid)) {
1896 // Already have local information on this page.
1897 $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
1898 return;
1901 // Create a new block_positions record.
1902 $bp = new stdClass;
1903 $bp->blockinstanceid = $instance->id;
1904 $bp->contextid = $page->context->id;
1905 $bp->pagetype = $page->pagetype;
1906 if ($page->subpage) {
1907 $bp->subpage = $page->subpage;
1909 $bp->visible = $newvisibility;
1910 $bp->region = $instance->defaultregion;
1911 $bp->weight = $instance->defaultweight;
1912 $DB->insert_record('block_positions', $bp);
1916 * @deprecated since 2.0
1917 * Delete all the blocks from a particular page.
1919 * @param string $pagetype the page type.
1920 * @param integer $pageid the page id.
1921 * @return bool success or failure.
1923 function blocks_delete_all_on_page($pagetype, $pageid) {
1924 global $DB;
1926 debugging('Call to deprecated function blocks_delete_all_on_page. ' .
1927 'This function cannot work any more. Doing nothing. ' .
1928 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER);
1929 return false;
1933 * Dispite what this function is called, it seems to be mostly used to populate
1934 * the default blocks when a new course (or whatever) is created.
1936 * @deprecated since 2.0
1938 * @param object $page the page to add default blocks to.
1939 * @return boolean success or failure.
1941 function blocks_repopulate_page($page) {
1942 global $CFG;
1944 debugging('Call to deprecated function blocks_repopulate_page. ' .
1945 'Use a more specific method like blocks_add_default_course_blocks, ' .
1946 'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER);
1948 /// If the site override has been defined, it is the only valid one.
1949 if (!empty($CFG->defaultblocks_override)) {
1950 $blocknames = $CFG->defaultblocks_override;
1951 } else {
1952 $blocknames = $page->blocks_get_default();
1955 $blocks = blocks_parse_default_blocks_list($blocknames);
1956 $page->blocks->add_blocks($blocks);
1958 return true;
1962 * Get the block record for a particular blockid - that is, a particular type os block.
1964 * @param $int blockid block type id. If null, an array of all block types is returned.
1965 * @param bool $notusedanymore No longer used.
1966 * @return array|object row from block table, or all rows.
1968 function blocks_get_record($blockid = NULL, $notusedanymore = false) {
1969 global $PAGE;
1970 $blocks = $PAGE->blocks->get_installed_blocks();
1971 if ($blockid === NULL) {
1972 return $blocks;
1973 } else if (isset($blocks[$blockid])) {
1974 return $blocks[$blockid];
1975 } else {
1976 return false;
1981 * Find a given block by its blockid within a provide array
1983 * @param int $blockid
1984 * @param array $blocksarray
1985 * @return bool|object Instance if found else false
1987 function blocks_find_block($blockid, $blocksarray) {
1988 if (empty($blocksarray)) {
1989 return false;
1991 foreach($blocksarray as $blockgroup) {
1992 if (empty($blockgroup)) {
1993 continue;
1995 foreach($blockgroup as $instance) {
1996 if($instance->blockid == $blockid) {
1997 return $instance;
2001 return false;
2004 // Functions for programatically adding default blocks to pages ================
2007 * Parse a list of default blocks. See config-dist for a description of the format.
2009 * @param string $blocksstr
2010 * @return array
2012 function blocks_parse_default_blocks_list($blocksstr) {
2013 $blocks = array();
2014 $bits = explode(':', $blocksstr);
2015 if (!empty($bits)) {
2016 $leftbits = trim(array_shift($bits));
2017 if ($leftbits != '') {
2018 $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2021 if (!empty($bits)) {
2022 $rightbits =trim(array_shift($bits));
2023 if ($rightbits != '') {
2024 $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2027 return $blocks;
2031 * @return array the blocks that should be added to the site course by default.
2033 function blocks_get_default_site_course_blocks() {
2034 global $CFG;
2036 if (!empty($CFG->defaultblocks_site)) {
2037 return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2038 } else {
2039 return array(
2040 BLOCK_POS_LEFT => array('site_main_menu'),
2041 BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2047 * Add the default blocks to a course.
2049 * @param object $course a course object.
2051 function blocks_add_default_course_blocks($course) {
2052 global $CFG;
2054 if (!empty($CFG->defaultblocks_override)) {
2055 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2057 } else if ($course->id == SITEID) {
2058 $blocknames = blocks_get_default_site_course_blocks();
2060 } else {
2061 $defaultblocks = 'defaultblocks_' . $course->format;
2062 if (!empty($CFG->$defaultblocks)) {
2063 $blocknames = blocks_parse_default_blocks_list($CFG->$defaultblocks);
2065 } else {
2066 $formatconfig = $CFG->dirroot.'/course/format/'.$course->format.'/config.php';
2067 $format = array(); // initialize array in external file
2068 if (is_readable($formatconfig)) {
2069 include($formatconfig);
2071 if (!empty($format['defaultblocks'])) {
2072 $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']);
2074 } else if (!empty($CFG->defaultblocks)){
2075 $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks);
2077 } else {
2078 $blocknames = array(
2079 BLOCK_POS_LEFT => array(),
2080 BLOCK_POS_RIGHT => array('search_forums', 'news_items', 'calendar_upcoming', 'recent_activity')
2086 if ($course->id == SITEID) {
2087 $pagetypepattern = 'site-index';
2088 } else {
2089 $pagetypepattern = 'course-view-*';
2091 $page = new moodle_page();
2092 $page->set_course($course);
2093 $page->blocks->add_blocks($blocknames, $pagetypepattern);
2097 * Add the default system-context blocks. E.g. the admin tree.
2099 function blocks_add_default_system_blocks() {
2100 global $DB;
2102 $page = new moodle_page();
2103 $page->set_context(get_context_instance(CONTEXT_SYSTEM));
2104 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2105 $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2107 if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
2108 $subpagepattern = $defaultmypage->id;
2109 } else {
2110 $subpagepattern = null;
2113 $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);