[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/ -> blocklib.php (source)

   1  <?php
   2  
   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.
  14  //
  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/>.
  17  
  18  /**
  19   * Block Class and Functions
  20   *
  21   * This file defines the {@link block_manager} class,
  22   *
  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
  27   */
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**#@+
  32   * Default names for the block regions in the standard theme.
  33   */
  34  define('BLOCK_POS_LEFT',  'side-pre');
  35  define('BLOCK_POS_RIGHT', 'side-post');
  36  /**#@-*/
  37  
  38  define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
  39  define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
  40  define('BUI_CONTEXTS_ENTIRE_SITE', 2);
  41  
  42  define('BUI_CONTEXTS_CURRENT', 0);
  43  define('BUI_CONTEXTS_CURRENT_SUBS', 1);
  44  
  45  /**
  46   * Exception thrown when someone tried to do something with a block that does
  47   * not exist on a page.
  48   *
  49   * @copyright 2009 Tim Hunt
  50   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  51   * @since     Moodle 2.0
  52   */
  53  class block_not_on_page_exception extends moodle_exception {
  54      /**
  55       * Constructor
  56       * @param int $instanceid the block instance id of the block that was looked for.
  57       * @param object $page the current page.
  58       */
  59      public function __construct($instanceid, $page) {
  60          $a = new stdClass;
  61          $a->instanceid = $instanceid;
  62          $a->url = $page->url->out();
  63          parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
  64      }
  65  }
  66  
  67  /**
  68   * This class keeps track of the block that should appear on a moodle_page.
  69   *
  70   * The page to work with as passed to the constructor.
  71   *
  72   * @copyright 2009 Tim Hunt
  73   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  74   * @since     Moodle 2.0
  75   */
  76  class block_manager {
  77      /**
  78       * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
  79       * although other weights are valid.
  80       */
  81      const MAX_WEIGHT = 10;
  82  
  83  /// Field declarations =========================================================
  84  
  85      /**
  86       * the moodle_page we are managing blocks for.
  87       * @var moodle_page
  88       */
  89      protected $page;
  90  
  91      /** @var array region name => 1.*/
  92      protected $regions = array();
  93  
  94      /** @var string the region where new blocks are added.*/
  95      protected $defaultregion = null;
  96  
  97      /** @var array will be $DB->get_records('blocks') */
  98      protected $allblocks = null;
  99  
 100      /**
 101       * @var array blocks that this user can add to this page. Will be a subset
 102       * of $allblocks, but with array keys block->name. Access this via the
 103       * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
 104       */
 105      protected $addableblocks = null;
 106  
 107      /**
 108       * Will be an array region-name => array(db rows loaded in load_blocks);
 109       * @var array
 110       */
 111      protected $birecordsbyregion = null;
 112  
 113      /**
 114       * array region-name => array(block objects); populated as necessary by
 115       * the ensure_instances_exist method.
 116       * @var array
 117       */
 118      protected $blockinstances = array();
 119  
 120      /**
 121       * array region-name => array(block_contents objects) what actually needs to
 122       * be displayed in each region.
 123       * @var array
 124       */
 125      protected $visibleblockcontent = array();
 126  
 127      /**
 128       * array region-name => array(block_contents objects) extra block-like things
 129       * to be displayed in each region, before the real blocks.
 130       * @var array
 131       */
 132      protected $extracontent = array();
 133  
 134      /**
 135       * Used by the block move id, to track whether a block is currently being moved.
 136       *
 137       * When you click on the move icon of a block, first the page needs to reload with
 138       * extra UI for choosing a new position for a particular block. In that situation
 139       * this field holds the id of the block being moved.
 140       *
 141       * @var integer|null
 142       */
 143      protected $movingblock = null;
 144  
 145      /**
 146       * Show only fake blocks
 147       */
 148      protected $fakeblocksonly = false;
 149  
 150  /// Constructor ================================================================
 151  
 152      /**
 153       * Constructor.
 154       * @param object $page the moodle_page object object we are managing the blocks for,
 155       * or a reasonable faxilimily. (See the comment at the top of this class
 156       * and {@link http://en.wikipedia.org/wiki/Duck_typing})
 157       */
 158      public function __construct($page) {
 159          $this->page = $page;
 160      }
 161  
 162  /// Getter methods =============================================================
 163  
 164      /**
 165       * Get an array of all region names on this page where a block may appear
 166       *
 167       * @return array the internal names of the regions on this page where block may appear.
 168       */
 169      public function get_regions() {
 170          if (is_null($this->defaultregion)) {
 171              $this->page->initialise_theme_and_output();
 172          }
 173          return array_keys($this->regions);
 174      }
 175  
 176      /**
 177       * Get the region name of the region blocks are added to by default
 178       *
 179       * @return string the internal names of the region where new blocks are added
 180       * by default, and where any blocks from an unrecognised region are shown.
 181       * (Imagine that blocks were added with one theme selected, then you switched
 182       * to a theme with different block positions.)
 183       */
 184      public function get_default_region() {
 185          $this->page->initialise_theme_and_output();
 186          return $this->defaultregion;
 187      }
 188  
 189      /**
 190       * The list of block types that may be added to this page.
 191       *
 192       * @return array block name => record from block table.
 193       */
 194      public function get_addable_blocks() {
 195          $this->check_is_loaded();
 196  
 197          if (!is_null($this->addableblocks)) {
 198              return $this->addableblocks;
 199          }
 200  
 201          // Lazy load.
 202          $this->addableblocks = array();
 203  
 204          $allblocks = blocks_get_record();
 205          if (empty($allblocks)) {
 206              return $this->addableblocks;
 207          }
 208  
 209          $unaddableblocks = self::get_undeletable_block_types();
 210          $pageformat = $this->page->pagetype;
 211          foreach($allblocks as $block) {
 212              if (!$bi = block_instance($block->name)) {
 213                  continue;
 214              }
 215              if ($block->visible && !in_array($block->name, $unaddableblocks) &&
 216                      ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
 217                      blocks_name_allowed_in_format($block->name, $pageformat) &&
 218                      $bi->user_can_addto($this->page)) {
 219                  $this->addableblocks[$block->name] = $block;
 220              }
 221          }
 222  
 223          return $this->addableblocks;
 224      }
 225  
 226      /**
 227       * Given a block name, find out of any of them are currently present in the page
 228  
 229       * @param string $blockname - the basic name of a block (eg "navigation")
 230       * @return boolean - is there one of these blocks in the current page?
 231       */
 232      public function is_block_present($blockname) {
 233          if (empty($this->blockinstances)) {
 234              return false;
 235          }
 236  
 237          foreach ($this->blockinstances as $region) {
 238              foreach ($region as $instance) {
 239                  if (empty($instance->instance->blockname)) {
 240                      continue;
 241                  }
 242                  if ($instance->instance->blockname == $blockname) {
 243                      return true;
 244                  }
 245              }
 246          }
 247          return false;
 248      }
 249  
 250      /**
 251       * Find out if a block type is known by the system
 252       *
 253       * @param string $blockname the name of the type of block.
 254       * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
 255       * @return boolean true if this block in installed.
 256       */
 257      public function is_known_block_type($blockname, $includeinvisible = false) {
 258          $blocks = $this->get_installed_blocks();
 259          foreach ($blocks as $block) {
 260              if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
 261                  return true;
 262              }
 263          }
 264          return false;
 265      }
 266  
 267      /**
 268       * Find out if a region exists on a page
 269       *
 270       * @param string $region a region name
 271       * @return boolean true if this region exists on this page.
 272       */
 273      public function is_known_region($region) {
 274          return array_key_exists($region, $this->regions);
 275      }
 276  
 277      /**
 278       * Get an array of all blocks within a given region
 279       *
 280       * @param string $region a block region that exists on this page.
 281       * @return array of block instances.
 282       */
 283      public function get_blocks_for_region($region) {
 284          $this->check_is_loaded();
 285          $this->ensure_instances_exist($region);
 286          return $this->blockinstances[$region];
 287      }
 288  
 289      /**
 290       * Returns an array of block content objects that exist in a region
 291       *
 292       * @param string $region a block region that exists on this page.
 293       * @return array of block block_contents objects for all the blocks in a region.
 294       */
 295      public function get_content_for_region($region, $output) {
 296          $this->check_is_loaded();
 297          $this->ensure_content_created($region, $output);
 298          return $this->visibleblockcontent[$region];
 299      }
 300  
 301      /**
 302       * Helper method used by get_content_for_region.
 303       * @param string $region region name
 304       * @param float $weight weight. May be fractional, since you may want to move a block
 305       * between ones with weight 2 and 3, say ($weight would be 2.5).
 306       * @return string URL for moving block $this->movingblock to this position.
 307       */
 308      protected function get_move_target_url($region, $weight) {
 309          return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
 310                  'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
 311      }
 312  
 313      /**
 314       * Determine whether a region contains anything. (Either any real blocks, or
 315       * the add new block UI.)
 316       *
 317       * (You may wonder why the $output parameter is required. Unfortunately,
 318       * because of the way that blocks work, the only reliable way to find out
 319       * if a block will be visible is to get the content for output, and to
 320       * get the content, you need a renderer. Fortunately, this is not a
 321       * performance problem, because we cache the output that is generated, and
 322       * in almost every case where we call region_has_content, we are about to
 323       * output the blocks anyway, so we are not doing wasted effort.)
 324       *
 325       * @param string $region a block region that exists on this page.
 326       * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
 327       * @return boolean Whether there is anything in this region.
 328       */
 329      public function region_has_content($region, $output) {
 330  
 331          if (!$this->is_known_region($region)) {
 332              return false;
 333          }
 334          $this->check_is_loaded();
 335          $this->ensure_content_created($region, $output);
 336          // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
 337          // Mark Nielsen's patch - part 1
 338          if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
 339              // If editing is on, we need all the block regions visible, for the
 340              // move blocks UI.
 341              return true;
 342          }
 343          return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
 344      }
 345  
 346      /**
 347       * Get an array of all of the installed blocks.
 348       *
 349       * @return array contents of the block table.
 350       */
 351      public function get_installed_blocks() {
 352          global $DB;
 353          if (is_null($this->allblocks)) {
 354              $this->allblocks = $DB->get_records('block');
 355          }
 356          return $this->allblocks;
 357      }
 358  
 359      /**
 360       * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
 361       */
 362      public static function get_undeletable_block_types() {
 363          global $CFG;
 364  
 365          if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
 366              return array('navigation','settings');
 367          } else if (is_string($CFG->undeletableblocktypes)) {
 368              return explode(',', $CFG->undeletableblocktypes);
 369          } else {
 370              return $CFG->undeletableblocktypes;
 371          }
 372      }
 373  
 374  /// Setter methods =============================================================
 375  
 376      /**
 377       * Add a region to a page
 378       *
 379       * @param string $region add a named region where blocks may appear on the current page.
 380       *      This is an internal name, like 'side-pre', not a string to display in the UI.
 381       * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
 382       */
 383      public function add_region($region, $custom = true) {
 384          global $SESSION;
 385          $this->check_not_yet_loaded();
 386          if ($custom) {
 387              if (array_key_exists($region, $this->regions)) {
 388                  // This here is EXACTLY why we should not be adding block regions into a page. It should
 389                  // ALWAYS be done in a theme layout.
 390                  debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
 391              }
 392              // We need to register this custom region against the page type being used.
 393              // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
 394              $type = $this->page->pagetype;
 395              if (!isset($SESSION->custom_block_regions)) {
 396                  $SESSION->custom_block_regions = array($type => array($region));
 397              } else if (!isset($SESSION->custom_block_regions[$type])) {
 398                  $SESSION->custom_block_regions[$type] = array($region);
 399              } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
 400                  $SESSION->custom_block_regions[$type][] = $region;
 401              }
 402          }
 403          $this->regions[$region] = 1;
 404      }
 405  
 406      /**
 407       * Add an array of regions
 408       * @see add_region()
 409       *
 410       * @param array $regions this utility method calls add_region for each array element.
 411       */
 412      public function add_regions($regions, $custom = true) {
 413          foreach ($regions as $region) {
 414              $this->add_region($region, $custom);
 415          }
 416      }
 417  
 418      /**
 419       * Finds custom block regions associated with a page type and registers them with this block manager.
 420       *
 421       * @param string $pagetype
 422       */
 423      public function add_custom_regions_for_pagetype($pagetype) {
 424          global $SESSION;
 425          if (isset($SESSION->custom_block_regions[$pagetype])) {
 426              foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
 427                  $this->add_region($customregion, false);
 428              }
 429          }
 430      }
 431  
 432      /**
 433       * Set the default region for new blocks on the page
 434       *
 435       * @param string $defaultregion the internal names of the region where new
 436       * blocks should be added by default, and where any blocks from an
 437       * unrecognised region are shown.
 438       */
 439      public function set_default_region($defaultregion) {
 440          $this->check_not_yet_loaded();
 441          if ($defaultregion) {
 442              $this->check_region_is_known($defaultregion);
 443          }
 444          $this->defaultregion = $defaultregion;
 445      }
 446  
 447      /**
 448       * Add something that looks like a block, but which isn't an actual block_instance,
 449       * to this page.
 450       *
 451       * @param block_contents $bc the content of the block-like thing.
 452       * @param string $region a block region that exists on this page.
 453       */
 454      public function add_fake_block($bc, $region) {
 455          $this->page->initialise_theme_and_output();
 456          if (!$this->is_known_region($region)) {
 457              $region = $this->get_default_region();
 458          }
 459          if (array_key_exists($region, $this->visibleblockcontent)) {
 460              throw new coding_exception('block_manager has already prepared the blocks in region ' .
 461                      $region . 'for output. It is too late to add a fake block.');
 462          }
 463          if (!isset($bc->attributes['data-block'])) {
 464              $bc->attributes['data-block'] = '_fake';
 465          }
 466          $bc->attributes['class'] .= ' block_fake';
 467          $this->extracontent[$region][] = $bc;
 468      }
 469  
 470      /**
 471       * Checks to see whether all of the blocks within the given region are docked
 472       *
 473       * @see region_uses_dock
 474       * @param string $region
 475       * @return bool True if all of the blocks within that region are docked
 476       */
 477      public function region_completely_docked($region, $output) {
 478          global $CFG;
 479          // If theme doesn't allow docking or allowblockstodock is not set, then return.
 480          if (!$this->page->theme->enable_dock || empty($CFG->allowblockstodock)) {
 481              return false;
 482          }
 483  
 484          // Do not dock the region when the user attemps to move a block.
 485          if ($this->movingblock) {
 486              return false;
 487          }
 488  
 489          $this->check_is_loaded();
 490          $this->ensure_content_created($region, $output);
 491          if (!$this->region_has_content($region, $output)) {
 492              // If the region has no content then nothing is docked at all of course.
 493              return false;
 494          }
 495          foreach ($this->visibleblockcontent[$region] as $instance) {
 496              if (!empty($instance->content) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
 497                  return false;
 498              }
 499          }
 500          return true;
 501      }
 502  
 503      /**
 504       * Checks to see whether any of the blocks within the given regions are docked
 505       *
 506       * @see region_completely_docked
 507       * @param array|string $regions array of regions (or single region)
 508       * @return bool True if any of the blocks within that region are docked
 509       */
 510      public function region_uses_dock($regions, $output) {
 511          if (!$this->page->theme->enable_dock) {
 512              return false;
 513          }
 514          $this->check_is_loaded();
 515          foreach((array)$regions as $region) {
 516              $this->ensure_content_created($region, $output);
 517              foreach($this->visibleblockcontent[$region] as $instance) {
 518                  if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
 519                      return true;
 520                  }
 521              }
 522          }
 523          return false;
 524      }
 525  
 526  /// Actions ====================================================================
 527  
 528      /**
 529       * This method actually loads the blocks for our page from the database.
 530       *
 531       * @param boolean|null $includeinvisible
 532       *      null (default) - load hidden blocks if $this->page->user_is_editing();
 533       *      true - load hidden blocks.
 534       *      false - don't load hidden blocks.
 535       */
 536      public function load_blocks($includeinvisible = null) {
 537          global $DB, $CFG;
 538  
 539          if (!is_null($this->birecordsbyregion)) {
 540              // Already done.
 541              return;
 542          }
 543  
 544          if ($CFG->version < 2009050619) {
 545              // Upgrade/install not complete. Don't try too show any blocks.
 546              $this->birecordsbyregion = array();
 547              return;
 548          }
 549  
 550          // Ensure we have been initialised.
 551          if (is_null($this->defaultregion)) {
 552              $this->page->initialise_theme_and_output();
 553              // If there are still no block regions, then there are no blocks on this page.
 554              if (empty($this->regions)) {
 555                  $this->birecordsbyregion = array();
 556                  return;
 557              }
 558          }
 559  
 560          // Check if we need to load normal blocks
 561          if ($this->fakeblocksonly) {
 562              $this->birecordsbyregion = $this->prepare_per_region_arrays();
 563              return;
 564          }
 565  
 566          if (is_null($includeinvisible)) {
 567              $includeinvisible = $this->page->user_is_editing();
 568          }
 569          if ($includeinvisible) {
 570              $visiblecheck = '';
 571          } else {
 572              $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
 573          }
 574  
 575          $context = $this->page->context;
 576          $contexttest = 'bi.parentcontextid = :contextid2';
 577          $parentcontextparams = array();
 578          $parentcontextids = $context->get_parent_context_ids();
 579          if ($parentcontextids) {
 580              list($parentcontexttest, $parentcontextparams) =
 581                      $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
 582              $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
 583          }
 584  
 585          $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
 586          list($pagetypepatterntest, $pagetypepatternparams) =
 587                  $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
 588  
 589          $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 590          $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
 591  
 592          $params = array(
 593              'contextlevel' => CONTEXT_BLOCK,
 594              'subpage1' => $this->page->subpage,
 595              'subpage2' => $this->page->subpage,
 596              'contextid1' => $context->id,
 597              'contextid2' => $context->id,
 598              'pagetype' => $this->page->pagetype,
 599          );
 600          if ($this->page->subpage === '') {
 601              $params['subpage1'] = '';
 602              $params['subpage2'] = '';
 603          }
 604          $sql = "SELECT
 605                      bi.id,
 606                      bp.id AS blockpositionid,
 607                      bi.blockname,
 608                      bi.parentcontextid,
 609                      bi.showinsubcontexts,
 610                      bi.pagetypepattern,
 611                      bi.subpagepattern,
 612                      bi.defaultregion,
 613                      bi.defaultweight,
 614                      COALESCE(bp.visible, 1) AS visible,
 615                      COALESCE(bp.region, bi.defaultregion) AS region,
 616                      COALESCE(bp.weight, bi.defaultweight) AS weight,
 617                      bi.configdata
 618                      $ccselect
 619  
 620                  FROM {block_instances} bi
 621                  JOIN {block} b ON bi.blockname = b.name
 622                  LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
 623                                                    AND bp.contextid = :contextid1
 624                                                    AND bp.pagetype = :pagetype
 625                                                    AND bp.subpage = :subpage1
 626                  $ccjoin
 627  
 628                  WHERE
 629                  $contexttest
 630                  AND bi.pagetypepattern $pagetypepatterntest
 631                  AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
 632                  $visiblecheck
 633                  AND b.visible = 1
 634  
 635                  ORDER BY
 636                      COALESCE(bp.region, bi.defaultregion),
 637                      COALESCE(bp.weight, bi.defaultweight),
 638                      bi.id";
 639          $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
 640  
 641          $this->birecordsbyregion = $this->prepare_per_region_arrays();
 642          $unknown = array();
 643          foreach ($blockinstances as $bi) {
 644              context_helper::preload_from_record($bi);
 645              if ($this->is_known_region($bi->region)) {
 646                  $this->birecordsbyregion[$bi->region][] = $bi;
 647              } else {
 648                  $unknown[] = $bi;
 649              }
 650          }
 651  
 652          // Pages don't necessarily have a defaultregion. The  one time this can
 653          // happen is when there are no theme block regions, but the script itself
 654          // has a block region in the main content area.
 655          if (!empty($this->defaultregion)) {
 656              $this->birecordsbyregion[$this->defaultregion] =
 657                      array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
 658          }
 659      }
 660  
 661      /**
 662       * Add a block to the current page, or related pages. The block is added to
 663       * context $this->page->contextid. If $pagetypepattern $subpagepattern
 664       *
 665       * @param string $blockname The type of block to add.
 666       * @param string $region the block region on this page to add the block to.
 667       * @param integer $weight determines the order where this block appears in the region.
 668       * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
 669       * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
 670       * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
 671       */
 672      public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
 673          global $DB;
 674          // Allow invisible blocks because this is used when adding default page blocks, which
 675          // might include invisible ones if the user makes some default blocks invisible
 676          $this->check_known_block_type($blockname, true);
 677          $this->check_region_is_known($region);
 678  
 679          if (empty($pagetypepattern)) {
 680              $pagetypepattern = $this->page->pagetype;
 681          }
 682  
 683          $blockinstance = new stdClass;
 684          $blockinstance->blockname = $blockname;
 685          $blockinstance->parentcontextid = $this->page->context->id;
 686          $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
 687          $blockinstance->pagetypepattern = $pagetypepattern;
 688          $blockinstance->subpagepattern = $subpagepattern;
 689          $blockinstance->defaultregion = $region;
 690          $blockinstance->defaultweight = $weight;
 691          $blockinstance->configdata = '';
 692          $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
 693  
 694          // Ensure the block context is created.
 695          context_block::instance($blockinstance->id);
 696  
 697          // If the new instance was created, allow it to do additional setup
 698          if ($block = block_instance($blockname, $blockinstance)) {
 699              $block->instance_create();
 700          }
 701      }
 702  
 703      public function add_block_at_end_of_default_region($blockname) {
 704          $defaulregion = $this->get_default_region();
 705  
 706          $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
 707          if ($lastcurrentblock) {
 708              $weight = $lastcurrentblock->weight + 1;
 709          } else {
 710              $weight = 0;
 711          }
 712  
 713          if ($this->page->subpage) {
 714              $subpage = $this->page->subpage;
 715          } else {
 716              $subpage = null;
 717          }
 718  
 719          // Special case. Course view page type include the course format, but we
 720          // want to add the block non-format-specifically.
 721          $pagetypepattern = $this->page->pagetype;
 722          if (strpos($pagetypepattern, 'course-view') === 0) {
 723              $pagetypepattern = 'course-view-*';
 724          }
 725  
 726          // We should end using this for ALL the blocks, making always the 1st option
 727          // the default one to be used. Until then, this is one hack to avoid the
 728          // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
 729          // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
 730          // (the FIRST $pagetypepattern will be set)
 731  
 732          // We are applying it to all blocks created in mod pages for now and only if the
 733          // default pagetype is not one of the available options
 734          if (preg_match('/^mod-.*-/', $pagetypepattern)) {
 735              $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
 736              // Only go for the first if the pagetype is not a valid option
 737              if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
 738                  $pagetypepattern = key($pagetypelist);
 739              }
 740          }
 741          // Surely other pages like course-report will need this too, they just are not important
 742          // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
 743  
 744          $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
 745      }
 746  
 747      /**
 748       * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
 749       *
 750       * @param array $blocks array with array keys the region names, and values an array of block names.
 751       * @param string $pagetypepattern optional. Passed to @see add_block()
 752       * @param string $subpagepattern optional. Passed to @see add_block()
 753       */
 754      public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
 755          $this->add_regions(array_keys($blocks), false);
 756          foreach ($blocks as $region => $regionblocks) {
 757              $weight = 0;
 758              foreach ($regionblocks as $blockname) {
 759                  $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
 760                  $weight += 1;
 761              }
 762          }
 763      }
 764  
 765      /**
 766       * Move a block to a new position on this page.
 767       *
 768       * If this block cannot appear on any other pages, then we change defaultposition/weight
 769       * in the block_instances table. Otherwise we just set the position on this page.
 770       *
 771       * @param $blockinstanceid the block instance id.
 772       * @param $newregion the new region name.
 773       * @param $newweight the new weight.
 774       */
 775      public function reposition_block($blockinstanceid, $newregion, $newweight) {
 776          global $DB;
 777  
 778          $this->check_region_is_known($newregion);
 779          $inst = $this->find_instance($blockinstanceid);
 780  
 781          $bi = $inst->instance;
 782          if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
 783                  !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
 784                  (!$this->page->subpage || $bi->subpagepattern)) {
 785  
 786              // Set default position
 787              $newbi = new stdClass;
 788              $newbi->id = $bi->id;
 789              $newbi->defaultregion = $newregion;
 790              $newbi->defaultweight = $newweight;
 791              $DB->update_record('block_instances', $newbi);
 792  
 793              if ($bi->blockpositionid) {
 794                  $bp = new stdClass;
 795                  $bp->id = $bi->blockpositionid;
 796                  $bp->region = $newregion;
 797                  $bp->weight = $newweight;
 798                  $DB->update_record('block_positions', $bp);
 799              }
 800  
 801          } else {
 802              // Just set position on this page.
 803              $bp = new stdClass;
 804              $bp->region = $newregion;
 805              $bp->weight = $newweight;
 806  
 807              if ($bi->blockpositionid) {
 808                  $bp->id = $bi->blockpositionid;
 809                  $DB->update_record('block_positions', $bp);
 810  
 811              } else {
 812                  $bp->blockinstanceid = $bi->id;
 813                  $bp->contextid = $this->page->context->id;
 814                  $bp->pagetype = $this->page->pagetype;
 815                  if ($this->page->subpage) {
 816                      $bp->subpage = $this->page->subpage;
 817                  } else {
 818                      $bp->subpage = '';
 819                  }
 820                  $bp->visible = $bi->visible;
 821                  $DB->insert_record('block_positions', $bp);
 822              }
 823          }
 824      }
 825  
 826      /**
 827       * Find a given block by its instance id
 828       *
 829       * @param integer $instanceid
 830       * @return block_base
 831       */
 832      public function find_instance($instanceid) {
 833          foreach ($this->regions as $region => $notused) {
 834              $this->ensure_instances_exist($region);
 835              foreach($this->blockinstances[$region] as $instance) {
 836                  if ($instance->instance->id == $instanceid) {
 837                      return $instance;
 838                  }
 839              }
 840          }
 841          throw new block_not_on_page_exception($instanceid, $this->page);
 842      }
 843  
 844  /// Inner workings =============================================================
 845  
 846      /**
 847       * Check whether the page blocks have been loaded yet
 848       *
 849       * @return void Throws coding exception if already loaded
 850       */
 851      protected function check_not_yet_loaded() {
 852          if (!is_null($this->birecordsbyregion)) {
 853              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.');
 854          }
 855      }
 856  
 857      /**
 858       * Check whether the page blocks have been loaded yet
 859       *
 860       * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
 861       *
 862       * @return void Throws coding exception if already loaded
 863       */
 864      protected function check_is_loaded() {
 865          if (is_null($this->birecordsbyregion)) {
 866              throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
 867          }
 868      }
 869  
 870      /**
 871       * Check if a block type is known and usable
 872       *
 873       * @param string $blockname The block type name to search for
 874       * @param bool $includeinvisible Include disabled block types in the initial pass
 875       * @return void Coding Exception thrown if unknown or not enabled
 876       */
 877      protected function check_known_block_type($blockname, $includeinvisible = false) {
 878          if (!$this->is_known_block_type($blockname, $includeinvisible)) {
 879              if ($this->is_known_block_type($blockname, true)) {
 880                  throw new coding_exception('Unknown block type ' . $blockname);
 881              } else {
 882                  throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
 883              }
 884          }
 885      }
 886  
 887      /**
 888       * Check if a region is known by its name
 889       *
 890       * @param string $region
 891       * @return void Coding Exception thrown if the region is not known
 892       */
 893      protected function check_region_is_known($region) {
 894          if (!$this->is_known_region($region)) {
 895              throw new coding_exception('Trying to reference an unknown block region ' . $region);
 896          }
 897      }
 898  
 899      /**
 900       * Returns an array of region names as keys and nested arrays for values
 901       *
 902       * @return array an array where the array keys are the region names, and the array
 903       * values are empty arrays.
 904       */
 905      protected function prepare_per_region_arrays() {
 906          $result = array();
 907          foreach ($this->regions as $region => $notused) {
 908              $result[$region] = array();
 909          }
 910          return $result;
 911      }
 912  
 913      /**
 914       * Create a set of new block instance from a record array
 915       *
 916       * @param array $birecords An array of block instance records
 917       * @return array An array of instantiated block_instance objects
 918       */
 919      protected function create_block_instances($birecords) {
 920          $results = array();
 921          foreach ($birecords as $record) {
 922              if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
 923                  $results[] = $blockobject;
 924              }
 925          }
 926          return $results;
 927      }
 928  
 929      /**
 930       * Create all the block instances for all the blocks that were loaded by
 931       * load_blocks. This is used, for example, to ensure that all blocks get a
 932       * chance to initialise themselves via the {@link block_base::specialize()}
 933       * method, before any output is done.
 934       */
 935      public function create_all_block_instances() {
 936          foreach ($this->get_regions() as $region) {
 937              $this->ensure_instances_exist($region);
 938          }
 939      }
 940  
 941      /**
 942       * Return an array of content objects from a set of block instances
 943       *
 944       * @param array $instances An array of block instances
 945       * @param renderer_base The renderer to use.
 946       * @param string $region the region name.
 947       * @return array An array of block_content (and possibly block_move_target) objects.
 948       */
 949      protected function create_block_contents($instances, $output, $region) {
 950          $results = array();
 951  
 952          $lastweight = 0;
 953          $lastblock = 0;
 954          if ($this->movingblock) {
 955              $first = reset($instances);
 956              if ($first) {
 957                  $lastweight = $first->instance->weight - 2;
 958              }
 959          }
 960  
 961          foreach ($instances as $instance) {
 962              $content = $instance->get_content_for_output($output);
 963              if (empty($content)) {
 964                  continue;
 965              }
 966  
 967              if ($this->movingblock && $lastweight != $instance->instance->weight &&
 968                      $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
 969                  $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
 970              }
 971  
 972              if ($content->blockinstanceid == $this->movingblock) {
 973                  $content->add_class('beingmoved');
 974                  $content->annotation .= get_string('movingthisblockcancel', 'block',
 975                          html_writer::link($this->page->url, get_string('cancel')));
 976              }
 977  
 978              $results[] = $content;
 979              $lastweight = $instance->instance->weight;
 980              $lastblock = $instance->instance->id;
 981          }
 982  
 983          if ($this->movingblock && $lastblock != $this->movingblock) {
 984              $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
 985          }
 986          return $results;
 987      }
 988  
 989      /**
 990       * Ensure block instances exist for a given region
 991       *
 992       * @param string $region Check for bi's with the instance with this name
 993       */
 994      protected function ensure_instances_exist($region) {
 995          $this->check_region_is_known($region);
 996          if (!array_key_exists($region, $this->blockinstances)) {
 997              $this->blockinstances[$region] =
 998                      $this->create_block_instances($this->birecordsbyregion[$region]);
 999          }
1000      }
1001  
1002      /**
1003       * Ensure that there is some content within the given region
1004       *
1005       * @param string $region The name of the region to check
1006       */
1007      public function ensure_content_created($region, $output) {
1008          $this->ensure_instances_exist($region);
1009          if (!array_key_exists($region, $this->visibleblockcontent)) {
1010              $contents = array();
1011              if (array_key_exists($region, $this->extracontent)) {
1012                  $contents = $this->extracontent[$region];
1013              }
1014              $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
1015              if ($region == $this->defaultregion) {
1016                  $addblockui = block_add_block_ui($this->page, $output);
1017                  if ($addblockui) {
1018                      $contents[] = $addblockui;
1019                  }
1020              }
1021              $this->visibleblockcontent[$region] = $contents;
1022          }
1023      }
1024  
1025  /// Process actions from the URL ===============================================
1026  
1027      /**
1028       * Get the appropriate list of editing icons for a block. This is used
1029       * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
1030       *
1031       * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
1032       * @return an array in the format for {@link block_contents::$controls}
1033       */
1034      public function edit_controls($block) {
1035          global $CFG;
1036  
1037          $controls = array();
1038          $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
1039          $blocktitle = $block->title;
1040          if (empty($blocktitle)) {
1041              $blocktitle = $block->arialabel;
1042          }
1043  
1044          if ($this->page->user_can_edit_blocks()) {
1045              // Move icon.
1046              $str = new lang_string('moveblock', 'block', $blocktitle);
1047              $controls[] = new action_menu_link_primary(
1048                  new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
1049                  new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1050                  $str,
1051                  array('class' => 'editing_move')
1052              );
1053  
1054          }
1055  
1056          if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
1057              // Edit config icon - always show - needed for positioning UI.
1058              $str = new lang_string('configureblock', 'block', $blocktitle);
1059              $controls[] = new action_menu_link_secondary(
1060                  new moodle_url($actionurl, array('bui_editid' => $block->instance->id)),
1061                  new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1062                  $str,
1063                  array('class' => 'editing_edit')
1064              );
1065  
1066          }
1067  
1068          if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
1069              // Show/hide icon.
1070              if ($block->instance->visible) {
1071                  $str = new lang_string('hideblock', 'block', $blocktitle);
1072                  $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
1073                  $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1074                  $attributes = array('class' => 'editing_hide');
1075              } else {
1076                  $str = new lang_string('showblock', 'block', $blocktitle);
1077                  $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
1078                  $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
1079                  $attributes = array('class' => 'editing_show');
1080              }
1081              $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
1082          }
1083  
1084          // Assign roles icon.
1085          if (has_capability('moodle/role:assign', $block->context)) {
1086              //TODO: please note it is sloppy to pass urls through page parameters!!
1087              //      it is shortened because some web servers (e.g. IIS by default) give
1088              //      a 'security' error if you try to pass a full URL as a GET parameter in another URL.
1089              $return = $this->page->url->out(false);
1090              $return = str_replace($CFG->wwwroot . '/', '', $return);
1091  
1092              $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid'=>$block->context->id,
1093                                                                           'returnurl'=>$return));
1094              // Delete icon.
1095              $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
1096              $controls[] = new action_menu_link_secondary(
1097                  $rolesurl,
1098                  new pix_icon('t/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1099                  $str,
1100                  array('class' => 'editing_roles')
1101              );
1102          }
1103  
1104          if ($this->user_can_delete_block($block)) {
1105              // Delete icon.
1106              $str = new lang_string('deleteblock', 'block', $blocktitle);
1107              $controls[] = new action_menu_link_secondary(
1108                  new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)),
1109                  new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1110                  $str,
1111                  array('class' => 'editing_delete')
1112              );
1113          }
1114  
1115          return $controls;
1116      }
1117  
1118      /**
1119       * @param block_base $block a block that appears on this page.
1120       * @return boolean boolean whether the currently logged in user is allowed to delete this block.
1121       */
1122      protected function user_can_delete_block($block) {
1123          return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
1124                  $block->user_can_addto($this->page) &&
1125                  !in_array($block->instance->blockname, self::get_undeletable_block_types());
1126      }
1127  
1128      /**
1129       * Process any block actions that were specified in the URL.
1130       *
1131       * @return boolean true if anything was done. False if not.
1132       */
1133      public function process_url_actions() {
1134          if (!$this->page->user_is_editing()) {
1135              return false;
1136          }
1137          return $this->process_url_add() || $this->process_url_delete() ||
1138              $this->process_url_show_hide() || $this->process_url_edit() ||
1139              $this->process_url_move();
1140      }
1141  
1142      /**
1143       * Handle adding a block.
1144       * @return boolean true if anything was done. False if not.
1145       */
1146      public function process_url_add() {
1147          $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
1148          if (!$blocktype) {
1149              return false;
1150          }
1151  
1152          require_sesskey();
1153  
1154          if (!$this->page->user_can_edit_blocks()) {
1155              throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
1156          }
1157  
1158          if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
1159              throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
1160          }
1161  
1162          $this->add_block_at_end_of_default_region($blocktype);
1163  
1164          // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
1165          $this->page->ensure_param_not_in_url('bui_addblock');
1166  
1167          return true;
1168      }
1169  
1170      /**
1171       * Handle deleting a block.
1172       * @return boolean true if anything was done. False if not.
1173       */
1174      public function process_url_delete() {
1175          global $CFG, $PAGE, $OUTPUT;
1176  
1177          $blockid = optional_param('bui_deleteid', null, PARAM_INT);
1178          $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
1179  
1180          if (!$blockid) {
1181              return false;
1182          }
1183  
1184          require_sesskey();
1185          $block = $this->page->blocks->find_instance($blockid);
1186          if (!$this->user_can_delete_block($block)) {
1187              throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
1188          }
1189  
1190          if (!$confirmdelete) {
1191              $deletepage = new moodle_page();
1192              $deletepage->set_pagelayout('admin');
1193              $deletepage->set_course($this->page->course);
1194              $deletepage->set_context($this->page->context);
1195              if ($this->page->cm) {
1196                  $deletepage->set_cm($this->page->cm);
1197              }
1198  
1199              $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1200              $deleteurlparams = $this->page->url->params();
1201              $deletepage->set_url($deleteurlbase, $deleteurlparams);
1202              $deletepage->set_block_actions_done();
1203              // At this point we are either going to redirect, or display the form, so
1204              // overwrite global $PAGE ready for this. (Formslib refers to it.)
1205              $PAGE = $deletepage;
1206              //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
1207              $output = $deletepage->get_renderer('core');
1208              $OUTPUT = $output;
1209  
1210              $site = get_site();
1211              $blocktitle = $block->get_title();
1212              $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
1213              $message = get_string('deleteblockcheck', 'block', $blocktitle);
1214  
1215              // If the block is being shown in sub contexts display a warning.
1216              if ($block->instance->showinsubcontexts == 1) {
1217                  $parentcontext = context::instance_by_id($block->instance->parentcontextid);
1218                  $systemcontext = context_system::instance();
1219                  $messagestring = new stdClass();
1220                  $messagestring->location = $parentcontext->get_context_name();
1221  
1222                  // Checking for blocks that may have visibility on the front page and pages added on that.
1223                  if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
1224                      $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
1225                  } else {
1226                      $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
1227                      $messagestring->pagetype = $block->instance->pagetypepattern;
1228                      if (isset($pagetypes[$block->instance->pagetypepattern])) {
1229                          $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
1230                      }
1231                  }
1232  
1233                  $message = get_string('deleteblockwarning', 'block', $messagestring);
1234              }
1235  
1236              $PAGE->navbar->add($strdeletecheck);
1237              $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
1238              $PAGE->set_heading($site->fullname);
1239              echo $OUTPUT->header();
1240              $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
1241              $cancelurl = new moodle_url($deletepage->url);
1242              $yesbutton = new single_button($confirmurl, get_string('yes'));
1243              $nobutton = new single_button($cancelurl, get_string('no'));
1244              echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
1245              echo $OUTPUT->footer();
1246              // Make sure that nothing else happens after we have displayed this form.
1247              exit;
1248          } else {
1249              blocks_delete_instance($block->instance);
1250              // bui_deleteid and bui_confirm should not be in the PAGE url.
1251              $this->page->ensure_param_not_in_url('bui_deleteid');
1252              $this->page->ensure_param_not_in_url('bui_confirm');
1253              return true;
1254          }
1255      }
1256  
1257      /**
1258       * Handle showing or hiding a block.
1259       * @return boolean true if anything was done. False if not.
1260       */
1261      public function process_url_show_hide() {
1262          if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
1263              $newvisibility = 0;
1264          } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
1265              $newvisibility = 1;
1266          } else {
1267              return false;
1268          }
1269  
1270          require_sesskey();
1271  
1272          $block = $this->page->blocks->find_instance($blockid);
1273  
1274          if (!$this->page->user_can_edit_blocks()) {
1275              throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
1276          } else if (!$block->instance_can_be_hidden()) {
1277              return false;
1278          }
1279  
1280          blocks_set_visibility($block->instance, $this->page, $newvisibility);
1281  
1282          // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
1283          $this->page->ensure_param_not_in_url('bui_hideid');
1284          $this->page->ensure_param_not_in_url('bui_showid');
1285  
1286          return true;
1287      }
1288  
1289      /**
1290       * Handle showing/processing the submission from the block editing form.
1291       * @return boolean true if the form was submitted and the new config saved. Does not
1292       *      return if the editing form was displayed. False otherwise.
1293       */
1294      public function process_url_edit() {
1295          global $CFG, $DB, $PAGE, $OUTPUT;
1296  
1297          $blockid = optional_param('bui_editid', null, PARAM_INT);
1298          if (!$blockid) {
1299              return false;
1300          }
1301  
1302          require_sesskey();
1303          require_once($CFG->dirroot . '/blocks/edit_form.php');
1304  
1305          $block = $this->find_instance($blockid);
1306  
1307          if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
1308              throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1309          }
1310  
1311          $editpage = new moodle_page();
1312          $editpage->set_pagelayout('admin');
1313          $editpage->set_course($this->page->course);
1314          //$editpage->set_context($block->context);
1315          $editpage->set_context($this->page->context);
1316          if ($this->page->cm) {
1317              $editpage->set_cm($this->page->cm);
1318          }
1319          $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
1320          $editurlparams = $this->page->url->params();
1321          $editurlparams['bui_editid'] = $blockid;
1322          $editpage->set_url($editurlbase, $editurlparams);
1323          $editpage->set_block_actions_done();
1324          // At this point we are either going to redirect, or display the form, so
1325          // overwrite global $PAGE ready for this. (Formslib refers to it.)
1326          $PAGE = $editpage;
1327          //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
1328          $output = $editpage->get_renderer('core');
1329          $OUTPUT = $output;
1330  
1331          $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
1332          if (is_readable($formfile)) {
1333              require_once($formfile);
1334              $classname = 'block_' . $block->name() . '_edit_form';
1335              if (!class_exists($classname)) {
1336                  $classname = 'block_edit_form';
1337              }
1338          } else {
1339              $classname = 'block_edit_form';
1340          }
1341  
1342          $mform = new $classname($editpage->url, $block, $this->page);
1343          $mform->set_data($block->instance);
1344  
1345          if ($mform->is_cancelled()) {
1346              redirect($this->page->url);
1347  
1348          } else if ($data = $mform->get_data()) {
1349              $bi = new stdClass;
1350              $bi->id = $block->instance->id;
1351  
1352              // This may get overwritten by the special case handling below.
1353              $bi->pagetypepattern = $data->bui_pagetypepattern;
1354              $bi->showinsubcontexts = (bool) $data->bui_contexts;
1355              if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
1356                  $bi->subpagepattern = null;
1357              } else {
1358                  $bi->subpagepattern = $data->bui_subpagepattern;
1359              }
1360  
1361              $systemcontext = context_system::instance();
1362              $frontpagecontext = context_course::instance(SITEID);
1363              $parentcontext = context::instance_by_id($data->bui_parentcontextid);
1364  
1365              // Updating stickiness and contexts.  See MDL-21375 for details.
1366              if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
1367  
1368                  // Explicitly set the default context
1369                  $bi->parentcontextid = $parentcontext->id;
1370  
1371                  if ($data->bui_editingatfrontpage) {   // The block is being edited on the front page
1372  
1373                      // The interface here is a special case because the pagetype pattern is
1374                      // totally derived from the context menu.  Here are the excpetions.   MDL-30340
1375  
1376                      switch ($data->bui_contexts) {
1377                          case BUI_CONTEXTS_ENTIRE_SITE:
1378                              // The user wants to show the block across the entire site
1379                              $bi->parentcontextid = $systemcontext->id;
1380                              $bi->showinsubcontexts = true;
1381                              $bi->pagetypepattern  = '*';
1382                              break;
1383                          case BUI_CONTEXTS_FRONTPAGE_SUBS:
1384                              // The user wants the block shown on the front page and all subcontexts
1385                              $bi->parentcontextid = $frontpagecontext->id;
1386                              $bi->showinsubcontexts = true;
1387                              $bi->pagetypepattern  = '*';
1388                              break;
1389                          case BUI_CONTEXTS_FRONTPAGE_ONLY:
1390                              // The user want to show the front page on the frontpage only
1391                              $bi->parentcontextid = $frontpagecontext->id;
1392                              $bi->showinsubcontexts = false;
1393                              $bi->pagetypepattern  = 'site-index';
1394                              // This is the only relevant page type anyway but we'll set it explicitly just
1395                              // in case the front page grows site-index-* subpages of its own later
1396                              break;
1397                      }
1398                  }
1399              }
1400  
1401              $bits = explode('-', $bi->pagetypepattern);
1402              // hacks for some contexts
1403              if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
1404                  // For course context
1405                  // is page type pattern is mod-*, change showinsubcontext to 1
1406                  if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
1407                      $bi->showinsubcontexts = 1;
1408                  } else {
1409                      $bi->showinsubcontexts = 0;
1410                  }
1411              } else  if ($parentcontext->contextlevel == CONTEXT_USER) {
1412                  // for user context
1413                  // subpagepattern should be null
1414                  if ($bits[0] == 'user' or $bits[0] == 'my') {
1415                      // we don't need subpagepattern in usercontext
1416                      $bi->subpagepattern = null;
1417                  }
1418              }
1419  
1420              $bi->defaultregion = $data->bui_defaultregion;
1421              $bi->defaultweight = $data->bui_defaultweight;
1422              $DB->update_record('block_instances', $bi);
1423  
1424              if (!empty($block->config)) {
1425                  $config = clone($block->config);
1426              } else {
1427                  $config = new stdClass;
1428              }
1429              foreach ($data as $configfield => $value) {
1430                  if (strpos($configfield, 'config_') !== 0) {
1431                      continue;
1432                  }
1433                  $field = substr($configfield, 7);
1434                  $config->$field = $value;
1435              }
1436              $block->instance_config_save($config);
1437  
1438              $bp = new stdClass;
1439              $bp->visible = $data->bui_visible;
1440              $bp->region = $data->bui_region;
1441              $bp->weight = $data->bui_weight;
1442              $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
1443                      $data->bui_weight != $data->bui_defaultweight;
1444  
1445              if ($block->instance->blockpositionid && !$needbprecord) {
1446                  $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
1447  
1448              } else if ($block->instance->blockpositionid && $needbprecord) {
1449                  $bp->id = $block->instance->blockpositionid;
1450                  $DB->update_record('block_positions', $bp);
1451  
1452              } else if ($needbprecord) {
1453                  $bp->blockinstanceid = $block->instance->id;
1454                  $bp->contextid = $this->page->context->id;
1455                  $bp->pagetype = $this->page->pagetype;
1456                  if ($this->page->subpage) {
1457                      $bp->subpage = $this->page->subpage;
1458                  } else {
1459                      $bp->subpage = '';
1460                  }
1461                  $DB->insert_record('block_positions', $bp);
1462              }
1463  
1464              redirect($this->page->url);
1465  
1466          } else {
1467              $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
1468              $editpage->set_title($strheading);
1469              $editpage->set_heading($strheading);
1470              $bits = explode('-', $this->page->pagetype);
1471              if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
1472                  // better navbar for tag pages
1473                  $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
1474                  $tag = tag_get('id', $this->page->subpage, '*');
1475                  // tag search page doesn't have subpageid
1476                  if ($tag) {
1477                      $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
1478                  }
1479              }
1480              $editpage->navbar->add($block->get_title());
1481              $editpage->navbar->add(get_string('configuration'));
1482              echo $output->header();
1483              echo $output->heading($strheading, 2);
1484              $mform->display();
1485              echo $output->footer();
1486              exit;
1487          }
1488      }
1489  
1490      /**
1491       * Handle showing/processing the submission from the block editing form.
1492       * @return boolean true if the form was submitted and the new config saved. Does not
1493       *      return if the editing form was displayed. False otherwise.
1494       */
1495      public function process_url_move() {
1496          global $CFG, $DB, $PAGE;
1497  
1498          $blockid = optional_param('bui_moveid', null, PARAM_INT);
1499          if (!$blockid) {
1500              return false;
1501          }
1502  
1503          require_sesskey();
1504  
1505          $block = $this->find_instance($blockid);
1506  
1507          if (!$this->page->user_can_edit_blocks()) {
1508              throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
1509          }
1510  
1511          $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
1512          $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
1513          if (!$newregion || is_null($newweight)) {
1514              // Don't have a valid target position yet, must be just starting the move.
1515              $this->movingblock = $blockid;
1516              $this->page->ensure_param_not_in_url('bui_moveid');
1517              return false;
1518          }
1519  
1520          if (!$this->is_known_region($newregion)) {
1521              throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
1522          }
1523  
1524          // Move this block. This may involve moving other nearby blocks.
1525          $blocks = $this->birecordsbyregion[$newregion];
1526  
1527          $maxweight = self::MAX_WEIGHT;
1528          $minweight = -self::MAX_WEIGHT;
1529  
1530          // Initialise the used weights and spareweights array with the default values
1531          $spareweights = array();
1532          $usedweights = array();
1533          for ($i = $minweight; $i <= $maxweight; $i++) {
1534              $spareweights[$i] = $i;
1535              $usedweights[$i] = array();
1536          }
1537  
1538          // Check each block and sort out where we have used weights
1539          foreach ($blocks as $bi) {
1540              if ($bi->weight > $maxweight) {
1541                  // If this statement is true then the blocks weight is more than the
1542                  // current maximum. To ensure that we can get the best block position
1543                  // we will initialise elements within the usedweights and spareweights
1544                  // arrays between the blocks weight (which will then be the new max) and
1545                  // the current max
1546                  $parseweight = $bi->weight;
1547                  while (!array_key_exists($parseweight, $usedweights)) {
1548                      $usedweights[$parseweight] = array();
1549                      $spareweights[$parseweight] = $parseweight;
1550                      $parseweight--;
1551                  }
1552                  $maxweight = $bi->weight;
1553              } else if ($bi->weight < $minweight) {
1554                  // As above except this time the blocks weight is LESS than the
1555                  // the current minimum, so we will initialise the array from the
1556                  // blocks weight (new minimum) to the current minimum
1557                  $parseweight = $bi->weight;
1558                  while (!array_key_exists($parseweight, $usedweights)) {
1559                      $usedweights[$parseweight] = array();
1560                      $spareweights[$parseweight] = $parseweight;
1561                      $parseweight++;
1562                  }
1563                  $minweight = $bi->weight;
1564              }
1565              if ($bi->id != $block->instance->id) {
1566                  unset($spareweights[$bi->weight]);
1567                  $usedweights[$bi->weight][] = $bi->id;
1568              }
1569          }
1570  
1571          // First we find the nearest gap in the list of weights.
1572          $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
1573          $bestgap = null;
1574          foreach ($spareweights as $spareweight) {
1575              if (abs($newweight - $spareweight) < $bestdistance) {
1576                  $bestdistance = abs($newweight - $spareweight);
1577                  $bestgap = $spareweight;
1578              }
1579          }
1580  
1581          // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
1582          if (is_null($bestgap)) {
1583              $bestgap = self::MAX_WEIGHT + 1;
1584              while (!empty($usedweights[$bestgap])) {
1585                  $bestgap++;
1586              }
1587          }
1588  
1589          // Now we know the gap we are aiming for, so move all the blocks along.
1590          if ($bestgap < $newweight) {
1591              $newweight = floor($newweight);
1592              for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
1593                  foreach ($usedweights[$weight] as $biid) {
1594                      $this->reposition_block($biid, $newregion, $weight - 1);
1595                  }
1596              }
1597              $this->reposition_block($block->instance->id, $newregion, $newweight);
1598          } else {
1599              $newweight = ceil($newweight);
1600              for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
1601                  if (array_key_exists($weight, $usedweights)) {
1602                      foreach ($usedweights[$weight] as $biid) {
1603                          $this->reposition_block($biid, $newregion, $weight + 1);
1604                      }
1605                  }
1606              }
1607              $this->reposition_block($block->instance->id, $newregion, $newweight);
1608          }
1609  
1610          $this->page->ensure_param_not_in_url('bui_moveid');
1611          $this->page->ensure_param_not_in_url('bui_newregion');
1612          $this->page->ensure_param_not_in_url('bui_newweight');
1613          return true;
1614      }
1615  
1616      /**
1617       * Turns the display of normal blocks either on or off.
1618       *
1619       * @param bool $setting
1620       */
1621      public function show_only_fake_blocks($setting = true) {
1622          $this->fakeblocksonly = $setting;
1623      }
1624  }
1625  
1626  /// Helper functions for working with block classes ============================
1627  
1628  /**
1629   * Call a class method (one that does not require a block instance) on a block class.
1630   *
1631   * @param string $blockname the name of the block.
1632   * @param string $method the method name.
1633   * @param array $param parameters to pass to the method.
1634   * @return mixed whatever the method returns.
1635   */
1636  function block_method_result($blockname, $method, $param = NULL) {
1637      if(!block_load_class($blockname)) {
1638          return NULL;
1639      }
1640      return call_user_func(array('block_'.$blockname, $method), $param);
1641  }
1642  
1643  /**
1644   * Creates a new instance of the specified block class.
1645   *
1646   * @param string $blockname the name of the block.
1647   * @param $instance block_instances DB table row (optional).
1648   * @param moodle_page $page the page this block is appearing on.
1649   * @return block_base the requested block instance.
1650   */
1651  function block_instance($blockname, $instance = NULL, $page = NULL) {
1652      if(!block_load_class($blockname)) {
1653          return false;
1654      }
1655      $classname = 'block_'.$blockname;
1656      $retval = new $classname;
1657      if($instance !== NULL) {
1658          if (is_null($page)) {
1659              global $PAGE;
1660              $page = $PAGE;
1661          }
1662          $retval->_load_instance($instance, $page);
1663      }
1664      return $retval;
1665  }
1666  
1667  /**
1668   * Load the block class for a particular type of block.
1669   *
1670   * @param string $blockname the name of the block.
1671   * @return boolean success or failure.
1672   */
1673  function block_load_class($blockname) {
1674      global $CFG;
1675  
1676      if(empty($blockname)) {
1677          return false;
1678      }
1679  
1680      $classname = 'block_'.$blockname;
1681  
1682      if(class_exists($classname)) {
1683          return true;
1684      }
1685  
1686      $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
1687  
1688      if (file_exists($blockpath)) {
1689          require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1690          include_once($blockpath);
1691      }else{
1692          //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
1693          return false;
1694      }
1695  
1696      return class_exists($classname);
1697  }
1698  
1699  /**
1700   * Given a specific page type, return all the page type patterns that might
1701   * match it.
1702   *
1703   * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1704   * @return array an array of all the page type patterns that might match this page type.
1705   */
1706  function matching_page_type_patterns($pagetype) {
1707      $patterns = array($pagetype);
1708      $bits = explode('-', $pagetype);
1709      if (count($bits) == 3 && $bits[0] == 'mod') {
1710          if ($bits[2] == 'view') {
1711              $patterns[] = 'mod-*-view';
1712          } else if ($bits[2] == 'index') {
1713              $patterns[] = 'mod-*-index';
1714          }
1715      }
1716      while (count($bits) > 0) {
1717          $patterns[] = implode('-', $bits) . '-*';
1718          array_pop($bits);
1719      }
1720      $patterns[] = '*';
1721      return $patterns;
1722  }
1723  
1724  /**
1725   * Given a specific page type, parent context and currect context, return all the page type patterns
1726   * that might be used by this block.
1727   *
1728   * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
1729   * @param stdClass $parentcontext Block's parent context
1730   * @param stdClass $currentcontext Current context of block
1731   * @return array an array of all the page type patterns that might match this page type.
1732   */
1733  function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
1734      global $CFG; // Required for includes bellow.
1735  
1736      $bits = explode('-', $pagetype);
1737  
1738      $core = core_component::get_core_subsystems();
1739      $plugins = core_component::get_plugin_types();
1740  
1741      //progressively strip pieces off the page type looking for a match
1742      $componentarray = null;
1743      for ($i = count($bits); $i > 0; $i--) {
1744          $possiblecomponentarray = array_slice($bits, 0, $i);
1745          $possiblecomponent = implode('', $possiblecomponentarray);
1746  
1747          // Check to see if the component is a core component
1748          if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
1749              $libfile = $core[$possiblecomponent].'/lib.php';
1750              if (file_exists($libfile)) {
1751                  require_once($libfile);
1752                  $function = $possiblecomponent.'_page_type_list';
1753                  if (function_exists($function)) {
1754                      if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1755                          break;
1756                      }
1757                  }
1758              }
1759          }
1760  
1761          //check the plugin directory and look for a callback
1762          if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
1763  
1764              //We've found a plugin type. Look for a plugin name by getting the next section of page type
1765              if (count($bits) > $i) {
1766                  $pluginname = $bits[$i];
1767                  $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
1768                  if (!empty($directory)){
1769                      $libfile = $directory.'/lib.php';
1770                      if (file_exists($libfile)) {
1771                          require_once($libfile);
1772                          $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
1773                          if (!function_exists($function)) {
1774                              $function = $pluginname.'_page_type_list';
1775                          }
1776                          if (function_exists($function)) {
1777                              if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1778                                  break;
1779                              }
1780                          }
1781                      }
1782                  }
1783              }
1784  
1785              //we'll only get to here if we still don't have any patterns
1786              //the plugin type may have a callback
1787              $directory = $plugins[$possiblecomponent];
1788              $libfile = $directory.'/lib.php';
1789              if (file_exists($libfile)) {
1790                  require_once($libfile);
1791                  $function = $possiblecomponent.'_page_type_list';
1792                  if (function_exists($function)) {
1793                      if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
1794                          break;
1795                      }
1796                  }
1797              }
1798          }
1799      }
1800  
1801      if (empty($patterns)) {
1802          $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
1803      }
1804  
1805      // Ensure that the * pattern is always available if editing block 'at distance', so
1806      // we always can 'bring back' it to the original context. MDL-30340
1807      if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
1808          // TODO: We could change the string here, showing its 'bring back' meaning
1809          $patterns['*'] = get_string('page-x', 'pagetype');
1810      }
1811  
1812      return $patterns;
1813  }
1814  
1815  /**
1816   * Generates a default page type list when a more appropriate callback cannot be decided upon.
1817   *
1818   * @param string $pagetype
1819   * @param stdClass $parentcontext
1820   * @param stdClass $currentcontext
1821   * @return array
1822   */
1823  function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1824      // Generate page type patterns based on current page type if
1825      // callbacks haven't been defined
1826      $patterns = array($pagetype => $pagetype);
1827      $bits = explode('-', $pagetype);
1828      while (count($bits) > 0) {
1829          $pattern = implode('-', $bits) . '-*';
1830          $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
1831          // guessing page type description
1832          if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
1833              $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
1834          } else {
1835              $patterns[$pattern] = $pattern;
1836          }
1837          array_pop($bits);
1838      }
1839      $patterns['*'] = get_string('page-x', 'pagetype');
1840      return $patterns;
1841  }
1842  
1843  /**
1844   * Generates the page type list for the my moodle page
1845   *
1846   * @param string $pagetype
1847   * @param stdClass $parentcontext
1848   * @param stdClass $currentcontext
1849   * @return array
1850   */
1851  function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1852      return array('my-index' => get_string('page-my-index', 'pagetype'));
1853  }
1854  
1855  /**
1856   * Generates the page type list for a module by either locating and using the modules callback
1857   * or by generating a default list.
1858   *
1859   * @param string $pagetype
1860   * @param stdClass $parentcontext
1861   * @param stdClass $currentcontext
1862   * @return array
1863   */
1864  function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
1865      $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
1866      if (empty($patterns)) {
1867          // if modules don't have callbacks
1868          // generate two default page type patterns for modules only
1869          $bits = explode('-', $pagetype);
1870          $patterns = array($pagetype => $pagetype);
1871          if ($bits[2] == 'view') {
1872              $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
1873          } else if ($bits[2] == 'index') {
1874              $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
1875          }
1876      }
1877      return $patterns;
1878  }
1879  /// Functions update the blocks if required by the request parameters ==========
1880  
1881  /**
1882   * Return a {@link block_contents} representing the add a new block UI, if
1883   * this user is allowed to see it.
1884   *
1885   * @return block_contents an appropriate block_contents, or null if the user
1886   * cannot add any blocks here.
1887   */
1888  function block_add_block_ui($page, $output) {
1889      global $CFG, $OUTPUT;
1890      if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
1891          return null;
1892      }
1893  
1894      $bc = new block_contents();
1895      $bc->title = get_string('addblock');
1896      $bc->add_class('block_adminblock');
1897      $bc->attributes['data-block'] = 'adminblock';
1898  
1899      $missingblocks = $page->blocks->get_addable_blocks();
1900      if (empty($missingblocks)) {
1901          $bc->content = get_string('noblockstoaddhere');
1902          return $bc;
1903      }
1904  
1905      $menu = array();
1906      foreach ($missingblocks as $block) {
1907          $blockobject = block_instance($block->name);
1908          if ($blockobject !== false && $blockobject->user_can_addto($page)) {
1909              $menu[$block->name] = $blockobject->get_title();
1910          }
1911      }
1912      core_collator::asort($menu);
1913  
1914      $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
1915      $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
1916      $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
1917      $bc->content = $OUTPUT->render($select);
1918      return $bc;
1919  }
1920  
1921  /**
1922   * Actually delete from the database any blocks that are currently on this page,
1923   * but which should not be there according to blocks_name_allowed_in_format.
1924   *
1925   * @todo Write/Fix this function. Currently returns immediately
1926   * @param $course
1927   */
1928  function blocks_remove_inappropriate($course) {
1929      // TODO
1930      return;
1931      /*
1932      $blockmanager = blocks_get_by_page($page);
1933  
1934      if (empty($blockmanager)) {
1935          return;
1936      }
1937  
1938      if (($pageformat = $page->pagetype) == NULL) {
1939          return;
1940      }
1941  
1942      foreach($blockmanager as $region) {
1943          foreach($region as $instance) {
1944              $block = blocks_get_record($instance->blockid);
1945              if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
1946                 blocks_delete_instance($instance->instance);
1947              }
1948          }
1949      }*/
1950  }
1951  
1952  /**
1953   * Check that a given name is in a permittable format
1954   *
1955   * @param string $name
1956   * @param string $pageformat
1957   * @return bool
1958   */
1959  function blocks_name_allowed_in_format($name, $pageformat) {
1960      $accept = NULL;
1961      $maxdepth = -1;
1962      if (!$bi = block_instance($name)) {
1963          return false;
1964      }
1965  
1966      $formats = $bi->applicable_formats();
1967      if (!$formats) {
1968          $formats = array();
1969      }
1970      foreach ($formats as $format => $allowed) {
1971          $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
1972          $depth = substr_count($format, '-');
1973          if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
1974              $maxdepth = $depth;
1975              $accept = $allowed;
1976          }
1977      }
1978      if ($accept === NULL) {
1979          $accept = !empty($formats['all']);
1980      }
1981      return $accept;
1982  }
1983  
1984  /**
1985   * Delete a block, and associated data.
1986   *
1987   * @param object $instance a row from the block_instances table
1988   * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
1989   * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
1990   */
1991  function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
1992      global $DB;
1993  
1994      if ($block = block_instance($instance->blockname, $instance)) {
1995          $block->instance_delete();
1996      }
1997      context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
1998  
1999      if (!$skipblockstables) {
2000          $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
2001          $DB->delete_records('block_instances', array('id' => $instance->id));
2002          $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
2003      }
2004  }
2005  
2006  /**
2007   * Delete all the blocks that belong to a particular context.
2008   *
2009   * @param int $contextid the context id.
2010   */
2011  function blocks_delete_all_for_context($contextid) {
2012      global $DB;
2013      $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
2014      foreach ($instances as $instance) {
2015          blocks_delete_instance($instance, true);
2016      }
2017      $instances->close();
2018      $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
2019      $DB->delete_records('block_positions', array('contextid' => $contextid));
2020  }
2021  
2022  /**
2023   * Set a block to be visible or hidden on a particular page.
2024   *
2025   * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
2026   *      block_positions table as return by block_manager.
2027   * @param moodle_page $page the back to set the visibility with respect to.
2028   * @param integer $newvisibility 1 for visible, 0 for hidden.
2029   */
2030  function blocks_set_visibility($instance, $page, $newvisibility) {
2031      global $DB;
2032      if (!empty($instance->blockpositionid)) {
2033          // Already have local information on this page.
2034          $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
2035          return;
2036      }
2037  
2038      // Create a new block_positions record.
2039      $bp = new stdClass;
2040      $bp->blockinstanceid = $instance->id;
2041      $bp->contextid = $page->context->id;
2042      $bp->pagetype = $page->pagetype;
2043      if ($page->subpage) {
2044          $bp->subpage = $page->subpage;
2045      }
2046      $bp->visible = $newvisibility;
2047      $bp->region = $instance->defaultregion;
2048      $bp->weight = $instance->defaultweight;
2049      $DB->insert_record('block_positions', $bp);
2050  }
2051  
2052  /**
2053   * Get the block record for a particular blockid - that is, a particular type os block.
2054   *
2055   * @param $int blockid block type id. If null, an array of all block types is returned.
2056   * @param bool $notusedanymore No longer used.
2057   * @return array|object row from block table, or all rows.
2058   */
2059  function blocks_get_record($blockid = NULL, $notusedanymore = false) {
2060      global $PAGE;
2061      $blocks = $PAGE->blocks->get_installed_blocks();
2062      if ($blockid === NULL) {
2063          return $blocks;
2064      } else if (isset($blocks[$blockid])) {
2065          return $blocks[$blockid];
2066      } else {
2067          return false;
2068      }
2069  }
2070  
2071  /**
2072   * Find a given block by its blockid within a provide array
2073   *
2074   * @param int $blockid
2075   * @param array $blocksarray
2076   * @return bool|object Instance if found else false
2077   */
2078  function blocks_find_block($blockid, $blocksarray) {
2079      if (empty($blocksarray)) {
2080          return false;
2081      }
2082      foreach($blocksarray as $blockgroup) {
2083          if (empty($blockgroup)) {
2084              continue;
2085          }
2086          foreach($blockgroup as $instance) {
2087              if($instance->blockid == $blockid) {
2088                  return $instance;
2089              }
2090          }
2091      }
2092      return false;
2093  }
2094  
2095  // Functions for programatically adding default blocks to pages ================
2096  
2097  /**
2098   * Parse a list of default blocks. See config-dist for a description of the format.
2099   *
2100   * @param string $blocksstr
2101   * @return array
2102   */
2103  function blocks_parse_default_blocks_list($blocksstr) {
2104      $blocks = array();
2105      $bits = explode(':', $blocksstr);
2106      if (!empty($bits)) {
2107          $leftbits = trim(array_shift($bits));
2108          if ($leftbits != '') {
2109              $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
2110          }
2111      }
2112      if (!empty($bits)) {
2113          $rightbits =trim(array_shift($bits));
2114          if ($rightbits != '') {
2115              $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
2116          }
2117      }
2118      return $blocks;
2119  }
2120  
2121  /**
2122   * @return array the blocks that should be added to the site course by default.
2123   */
2124  function blocks_get_default_site_course_blocks() {
2125      global $CFG;
2126  
2127      if (!empty($CFG->defaultblocks_site)) {
2128          return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
2129      } else {
2130          return array(
2131              BLOCK_POS_LEFT => array('site_main_menu'),
2132              BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
2133          );
2134      }
2135  }
2136  
2137  /**
2138   * Add the default blocks to a course.
2139   *
2140   * @param object $course a course object.
2141   */
2142  function blocks_add_default_course_blocks($course) {
2143      global $CFG;
2144  
2145      if (!empty($CFG->defaultblocks_override)) {
2146          $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
2147  
2148      } else if ($course->id == SITEID) {
2149          $blocknames = blocks_get_default_site_course_blocks();
2150  
2151      } else if (!empty($CFG->{'defaultblocks_' . $course->format})) {
2152          $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
2153  
2154      } else {
2155          require_once($CFG->dirroot. '/course/lib.php');
2156          $blocknames = course_get_format($course)->get_default_blocks();
2157  
2158      }
2159  
2160      if ($course->id == SITEID) {
2161          $pagetypepattern = 'site-index';
2162      } else {
2163          $pagetypepattern = 'course-view-*';
2164      }
2165      $page = new moodle_page();
2166      $page->set_course($course);
2167      $page->blocks->add_blocks($blocknames, $pagetypepattern);
2168  }
2169  
2170  /**
2171   * Add the default system-context blocks. E.g. the admin tree.
2172   */
2173  function blocks_add_default_system_blocks() {
2174      global $DB;
2175  
2176      $page = new moodle_page();
2177      $page->set_context(context_system::instance());
2178      $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
2179      $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
2180  
2181      if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
2182          $subpagepattern = $defaultmypage->id;
2183      } else {
2184          $subpagepattern = null;
2185      }
2186  
2187      $newblocks = array('private_files', 'online_users', 'badges', 'calendar_month', 'calendar_upcoming');
2188      $newcontent = array('course_overview');
2189      $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => $newblocks, 'content' => $newcontent), 'my-index', $subpagepattern);
2190  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1