PageRenderTime 70ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/blocklib.php

https://github.com/mylescarrick/moodle
PHP | 1899 lines | 1075 code | 228 blank | 596 comment | 243 complexity | 6aab7701867d04f9455bb8dd34c340b8 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Block Class and Functions
  18. *
  19. * This file defines the {@link block_manager} class,
  20. *
  21. * @package core
  22. * @subpackage block
  23. * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
  24. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25. */
  26. defined('MOODLE_INTERNAL') || die();
  27. /**#@+
  28. * @deprecated since Moodle 2.0. No longer used.
  29. */
  30. define('BLOCK_MOVE_LEFT', 0x01);
  31. define('BLOCK_MOVE_RIGHT', 0x02);
  32. define('BLOCK_MOVE_UP', 0x04);
  33. define('BLOCK_MOVE_DOWN', 0x08);
  34. define('BLOCK_CONFIGURE', 0x10);
  35. /**#@-*/
  36. /**#@+
  37. * Default names for the block regions in the standard theme.
  38. */
  39. define('BLOCK_POS_LEFT', 'side-pre');
  40. define('BLOCK_POS_RIGHT', 'side-post');
  41. /**#@-*/
  42. /**#@+
  43. * @deprecated since Moodle 2.0. No longer used.
  44. */
  45. define('BLOCKS_PINNED_TRUE',0);
  46. define('BLOCKS_PINNED_FALSE',1);
  47. define('BLOCKS_PINNED_BOTH',2);
  48. /**#@-*/
  49. /**
  50. * Exception thrown when someone tried to do something with a block that does
  51. * not exist on a page.
  52. *
  53. * @copyright 2009 Tim Hunt
  54. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  55. * @since Moodle 2.0
  56. */
  57. class block_not_on_page_exception extends moodle_exception {
  58. /**
  59. * Constructor
  60. * @param int $instanceid the block instance id of the block that was looked for.
  61. * @param object $page the current page.
  62. */
  63. public function __construct($instanceid, $page) {
  64. $a = new stdClass;
  65. $a->instanceid = $instanceid;
  66. $a->url = $page->url->out();
  67. parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
  68. }
  69. }
  70. /**
  71. * This class keeps track of the block that should appear on a moodle_page.
  72. *
  73. * The page to work with as passed to the constructor.
  74. *
  75. * @copyright 2009 Tim Hunt
  76. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  77. * @since Moodle 2.0
  78. */
  79. class block_manager {
  80. /**
  81. * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
  82. * although other weights are valid.
  83. */
  84. const MAX_WEIGHT = 10;
  85. /// Field declarations =========================================================
  86. /**
  87. * the moodle_page we are managing blocks for.
  88. * @var moodle_page
  89. */
  90. protected $page;
  91. /** @var array region name => 1.*/
  92. protected $regions = array();
  93. /** @var string the region where new blocks are added.*/
  94. protected $defaultregion = null;
  95. /** @var array will be $DB->get_records('blocks') */
  96. protected $allblocks = null;
  97. /**
  98. * @var array blocks that this user can add to this page. Will be a subset
  99. * of $allblocks, but with array keys block->name. Access this via the
  100. * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
  101. */
  102. protected $addableblocks = null;
  103. /**
  104. * Will be an array region-name => array(db rows loaded in load_blocks);
  105. * @var array
  106. */
  107. protected $birecordsbyregion = null;
  108. /**
  109. * array region-name => array(block objects); populated as necessary by
  110. * the ensure_instances_exist method.
  111. * @var array
  112. */
  113. protected $blockinstances = array();
  114. /**
  115. * array region-name => array(block_contents objects) what actually needs to
  116. * be displayed in each region.
  117. * @var array
  118. */
  119. protected $visibleblockcontent = array();
  120. /**
  121. * array region-name => array(block_contents objects) extra block-like things
  122. * to be displayed in each region, before the real blocks.
  123. * @var array
  124. */
  125. protected $extracontent = array();
  126. /**
  127. * Used by the block move id, to track whether a block is currently being moved.
  128. *
  129. * When you click on the move icon of a block, first the page needs to reload with
  130. * extra UI for choosing a new position for a particular block. In that situation
  131. * this field holds the id of the block being moved.
  132. *
  133. * @var integer|null
  134. */
  135. protected $movingblock = null;
  136. /**
  137. * Show only fake blocks
  138. */
  139. protected $fakeblocksonly = false;
  140. /// Constructor ================================================================
  141. /**
  142. * Constructor.
  143. * @param object $page the moodle_page object object we are managing the blocks for,
  144. * or a reasonable faxilimily. (See the comment at the top of this class
  145. * and {@link http://en.wikipedia.org/wiki/Duck_typing})
  146. */
  147. public function __construct($page) {
  148. $this->page = $page;
  149. }
  150. /// Getter methods =============================================================
  151. /**
  152. * Get an array of all region names on this page where a block may appear
  153. *
  154. * @return array the internal names of the regions on this page where block may appear.
  155. */
  156. public function get_regions() {
  157. if (is_null($this->defaultregion)) {
  158. $this->page->initialise_theme_and_output();
  159. }
  160. return array_keys($this->regions);
  161. }
  162. /**
  163. * Get the region name of the region blocks are added to by default
  164. *
  165. * @return string the internal names of the region where new blocks are added
  166. * by default, and where any blocks from an unrecognised region are shown.
  167. * (Imagine that blocks were added with one theme selected, then you switched
  168. * to a theme with different block positions.)
  169. */
  170. public function get_default_region() {
  171. $this->page->initialise_theme_and_output();
  172. return $this->defaultregion;
  173. }
  174. /**
  175. * The list of block types that may be added to this page.
  176. *
  177. * @return array block name => record from block table.
  178. */
  179. public function get_addable_blocks() {
  180. $this->check_is_loaded();
  181. if (!is_null($this->addableblocks)) {
  182. return $this->addableblocks;
  183. }
  184. // Lazy load.
  185. $this->addableblocks = array();
  186. $allblocks = blocks_get_record();
  187. if (empty($allblocks)) {
  188. return $this->addableblocks;
  189. }
  190. $pageformat = $this->page->pagetype;
  191. foreach($allblocks as $block) {
  192. if ($block->visible &&
  193. (block_method_result($block->name, 'instance_allow_multiple') || !$this->is_block_present($block->name)) &&
  194. blocks_name_allowed_in_format($block->name, $pageformat) &&
  195. block_method_result($block->name, 'user_can_addto', $this->page)) {
  196. $this->addableblocks[$block->name] = $block;
  197. }
  198. }
  199. return $this->addableblocks;
  200. }
  201. /**
  202. * Given a block name, find out of any of them are currently present in the page
  203. * @param string $blockname - the basic name of a block (eg "navigation")
  204. * @return boolean - is there one of these blocks in the current page?
  205. */
  206. public function is_block_present($blockname) {
  207. if (empty($this->blockinstances)) {
  208. return false;
  209. }
  210. foreach ($this->blockinstances as $region) {
  211. foreach ($region as $instance) {
  212. if (empty($instance->instance->blockname)) {
  213. continue;
  214. }
  215. if ($instance->instance->blockname == $blockname) {
  216. return true;
  217. }
  218. }
  219. }
  220. return false;
  221. }
  222. /**
  223. * Find out if a block type is known by the system
  224. *
  225. * @param string $blockname the name of the type of block.
  226. * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
  227. * @return boolean true if this block in installed.
  228. */
  229. public function is_known_block_type($blockname, $includeinvisible = false) {
  230. $blocks = $this->get_installed_blocks();
  231. foreach ($blocks as $block) {
  232. if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
  233. return true;
  234. }
  235. }
  236. return false;
  237. }
  238. /**
  239. * Find out if a region exists on a page
  240. *
  241. * @param string $region a region name
  242. * @return boolean true if this region exists on this page.
  243. */
  244. public function is_known_region($region) {
  245. return array_key_exists($region, $this->regions);
  246. }
  247. /**
  248. * Get an array of all blocks within a given region
  249. *
  250. * @param string $region a block region that exists on this page.
  251. * @return array of block instances.
  252. */
  253. public function get_blocks_for_region($region) {
  254. $this->check_is_loaded();
  255. $this->ensure_instances_exist($region);
  256. return $this->blockinstances[$region];
  257. }
  258. /**
  259. * Returns an array of block content objects that exist in a region
  260. *
  261. * @param string $region a block region that exists on this page.
  262. * @return array of block block_contents objects for all the blocks in a region.
  263. */
  264. public function get_content_for_region($region, $output) {
  265. $this->check_is_loaded();
  266. $this->ensure_content_created($region, $output);
  267. return $this->visibleblockcontent[$region];
  268. }
  269. /**
  270. * Helper method used by get_content_for_region.
  271. * @param string $region region name
  272. * @param float $weight weight. May be fractional, since you may want to move a block
  273. * between ones with weight 2 and 3, say ($weight would be 2.5).
  274. * @return string URL for moving block $this->movingblock to this position.
  275. */
  276. protected function get_move_target_url($region, $weight) {
  277. return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
  278. 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
  279. }
  280. /**
  281. * Determine whether a region contains anything. (Either any real blocks, or
  282. * the add new block UI.)
  283. *
  284. * (You may wonder why the $output parameter is required. Unfortunately,
  285. * because of the way that blocks work, the only reliable way to find out
  286. * if a block will be visible is to get the content for output, and to
  287. * get the content, you need a renderer. Fortunately, this is not a
  288. * performance problem, because we cache the output that is generated, and
  289. * in almost every case where we call region_has_content, we are about to
  290. * output the blocks anyway, so we are not doing wasted effort.)
  291. *
  292. * @param string $region a block region that exists on this page.
  293. * @param object $output a core_renderer. normally the global $OUTPUT.
  294. * @return boolean Whether there is anything in this region.
  295. */
  296. public function region_has_content($region, $output) {
  297. if (!$this->is_known_region($region)) {
  298. return false;
  299. }
  300. $this->check_is_loaded();
  301. $this->ensure_content_created($region, $output);
  302. if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
  303. // If editing is on, we need all the block regions visible, for the
  304. // move blocks UI.
  305. return true;
  306. }
  307. return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
  308. }
  309. /**
  310. * Get an array of all of the installed blocks.
  311. *
  312. * @return array contents of the block table.
  313. */
  314. public function get_installed_blocks() {
  315. global $DB;
  316. if (is_null($this->allblocks)) {
  317. $this->allblocks = $DB->get_records('block');
  318. }
  319. return $this->allblocks;
  320. }
  321. /// Setter methods =============================================================
  322. /**
  323. * Add a region to a page
  324. *
  325. * @param string $region add a named region where blocks may appear on the
  326. * current page. This is an internal name, like 'side-pre', not a string to
  327. * display in the UI.
  328. */
  329. public function add_region($region) {
  330. $this->check_not_yet_loaded();
  331. $this->regions[$region] = 1;
  332. }
  333. /**
  334. * Add an array of regions
  335. * @see add_region()
  336. *
  337. * @param array $regions this utility method calls add_region for each array element.
  338. */
  339. public function add_regions($regions) {
  340. foreach ($regions as $region) {
  341. $this->add_region($region);
  342. }
  343. }
  344. /**
  345. * Set the default region for new blocks on the page
  346. *
  347. * @param string $defaultregion the internal names of the region where new
  348. * blocks should be added by default, and where any blocks from an
  349. * unrecognised region are shown.
  350. */
  351. public function set_default_region($defaultregion) {
  352. $this->check_not_yet_loaded();
  353. if ($defaultregion) {
  354. $this->check_region_is_known($defaultregion);
  355. }
  356. $this->defaultregion = $defaultregion;
  357. }
  358. /**
  359. * Add something that looks like a block, but which isn't an actual block_instance,
  360. * to this page.
  361. *
  362. * @param block_contents $bc the content of the block-like thing.
  363. * @param string $region a block region that exists on this page.
  364. */
  365. public function add_fake_block($bc, $region) {
  366. $this->page->initialise_theme_and_output();
  367. if (!$this->is_known_region($region)) {
  368. $region = $this->get_default_region();
  369. }
  370. if (array_key_exists($region, $this->visibleblockcontent)) {
  371. throw new coding_exception('block_manager has already prepared the blocks in region ' .
  372. $region . 'for output. It is too late to add a fake block.');
  373. }
  374. $this->extracontent[$region][] = $bc;
  375. }
  376. /**
  377. * When the block_manager class was created, the {@link add_fake_block()}
  378. * was called add_pretend_block, which is inconsisted with
  379. * {@link show_only_fake_blocks()}. To fix this inconsistency, this method
  380. * was renamed to add_fake_block. Please update your code.
  381. * @param block_contents $bc the content of the block-like thing.
  382. * @param string $region a block region that exists on this page.
  383. */
  384. public function add_pretend_block($bc, $region) {
  385. debugging(DEBUG_DEVELOPER, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
  386. $this->add_fake_block($bc, $region);
  387. }
  388. /**
  389. * Checks to see whether all of the blocks within the given region are docked
  390. *
  391. * @see region_uses_dock
  392. * @param string $region
  393. * @return bool True if all of the blocks within that region are docked
  394. */
  395. public function region_completely_docked($region, $output) {
  396. if (!$this->page->theme->enable_dock) {
  397. return false;
  398. }
  399. $this->check_is_loaded();
  400. $this->ensure_content_created($region, $output);
  401. foreach($this->visibleblockcontent[$region] as $instance) {
  402. if (!empty($instance->content) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
  403. return false;
  404. }
  405. }
  406. return true;
  407. }
  408. /**
  409. * Checks to see whether any of the blocks within the given regions are docked
  410. *
  411. * @see region_completely_docked
  412. * @param array|string $regions array of regions (or single region)
  413. * @return bool True if any of the blocks within that region are docked
  414. */
  415. public function region_uses_dock($regions, $output) {
  416. if (!$this->page->theme->enable_dock) {
  417. return false;
  418. }
  419. $this->check_is_loaded();
  420. foreach((array)$regions as $region) {
  421. $this->ensure_content_created($region, $output);
  422. foreach($this->visibleblockcontent[$region] as $instance) {
  423. if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
  424. return true;
  425. }
  426. }
  427. }
  428. return false;
  429. }
  430. /// Actions ====================================================================
  431. /**
  432. * This method actually loads the blocks for our page from the database.
  433. *
  434. * @param boolean|null $includeinvisible
  435. * null (default) - load hidden blocks if $this->page->user_is_editing();
  436. * true - load hidden blocks.
  437. * false - don't load hidden blocks.
  438. */
  439. public function load_blocks($includeinvisible = null) {
  440. global $DB, $CFG;
  441. if (!is_null($this->birecordsbyregion)) {
  442. // Already done.
  443. return;
  444. }
  445. if ($CFG->version < 2009050619) {
  446. // Upgrade/install not complete. Don't try too show any blocks.
  447. $this->birecordsbyregion = array();
  448. return;
  449. }
  450. // Ensure we have been initialised.
  451. if (is_null($this->defaultregion)) {
  452. $this->page->initialise_theme_and_output();
  453. // If there are still no block regions, then there are no blocks on this page.
  454. if (empty($this->regions)) {
  455. $this->birecordsbyregion = array();
  456. return;
  457. }
  458. }
  459. // Check if we need to load normal blocks
  460. if ($this->fakeblocksonly) {
  461. $this->birecordsbyregion = $this->prepare_per_region_arrays();
  462. return;
  463. }
  464. if (is_null($includeinvisible)) {
  465. $includeinvisible = $this->page->user_is_editing();
  466. }
  467. if ($includeinvisible) {
  468. $visiblecheck = '';
  469. } else {
  470. $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
  471. }
  472. $context = $this->page->context;
  473. $contexttest = 'bi.parentcontextid = :contextid2';
  474. $parentcontextparams = array();
  475. $parentcontextids = get_parent_contexts($context);
  476. if ($parentcontextids) {
  477. list($parentcontexttest, $parentcontextparams) =
  478. $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext0000');
  479. $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
  480. }
  481. $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
  482. list($pagetypepatterntest, $pagetypepatternparams) =
  483. $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest0000');
  484. list($ccselect, $ccjoin) = context_instance_preload_sql('b.id', CONTEXT_BLOCK, 'ctx');
  485. $params = array(
  486. 'subpage1' => $this->page->subpage,
  487. 'subpage2' => $this->page->subpage,
  488. 'contextid1' => $context->id,
  489. 'contextid2' => $context->id,
  490. 'pagetype' => $this->page->pagetype,
  491. );
  492. $sql = "SELECT
  493. bi.id,
  494. bp.id AS blockpositionid,
  495. bi.blockname,
  496. bi.parentcontextid,
  497. bi.showinsubcontexts,
  498. bi.pagetypepattern,
  499. bi.subpagepattern,
  500. bi.defaultregion,
  501. bi.defaultweight,
  502. COALESCE(bp.visible, 1) AS visible,
  503. COALESCE(bp.region, bi.defaultregion) AS region,
  504. COALESCE(bp.weight, bi.defaultweight) AS weight,
  505. bi.configdata
  506. $ccselect
  507. FROM {block_instances} bi
  508. JOIN {block} b ON bi.blockname = b.name
  509. LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
  510. AND bp.contextid = :contextid1
  511. AND bp.pagetype = :pagetype
  512. AND bp.subpage = :subpage1
  513. $ccjoin
  514. WHERE
  515. $contexttest
  516. AND bi.pagetypepattern $pagetypepatterntest
  517. AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
  518. $visiblecheck
  519. AND b.visible = 1
  520. ORDER BY
  521. COALESCE(bp.region, bi.defaultregion),
  522. COALESCE(bp.weight, bi.defaultweight),
  523. bi.id";
  524. $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
  525. $this->birecordsbyregion = $this->prepare_per_region_arrays();
  526. $unknown = array();
  527. foreach ($blockinstances as $bi) {
  528. context_instance_preload($bi);
  529. if ($this->is_known_region($bi->region)) {
  530. $this->birecordsbyregion[$bi->region][] = $bi;
  531. } else {
  532. $unknown[] = $bi;
  533. }
  534. }
  535. // Pages don't necessarily have a defaultregion. The one time this can
  536. // happen is when there are no theme block regions, but the script itself
  537. // has a block region in the main content area.
  538. if (!empty($this->defaultregion)) {
  539. $this->birecordsbyregion[$this->defaultregion] =
  540. array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
  541. }
  542. }
  543. /**
  544. * Add a block to the current page, or related pages. The block is added to
  545. * context $this->page->contextid. If $pagetypepattern $subpagepattern
  546. *
  547. * @param string $blockname The type of block to add.
  548. * @param string $region the block region on this page to add the block to.
  549. * @param integer $weight determines the order where this block appears in the region.
  550. * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
  551. * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
  552. * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
  553. */
  554. public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
  555. global $DB;
  556. // Allow invisible blocks because this is used when adding default page blocks, which
  557. // might include invisible ones if the user makes some default blocks invisible
  558. $this->check_known_block_type($blockname, true);
  559. $this->check_region_is_known($region);
  560. if (empty($pagetypepattern)) {
  561. $pagetypepattern = $this->page->pagetype;
  562. }
  563. $blockinstance = new stdClass;
  564. $blockinstance->blockname = $blockname;
  565. $blockinstance->parentcontextid = $this->page->context->id;
  566. $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
  567. $blockinstance->pagetypepattern = $pagetypepattern;
  568. $blockinstance->subpagepattern = $subpagepattern;
  569. $blockinstance->defaultregion = $region;
  570. $blockinstance->defaultweight = $weight;
  571. $blockinstance->configdata = '';
  572. $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
  573. // Ensure the block context is created.
  574. get_context_instance(CONTEXT_BLOCK, $blockinstance->id);
  575. // If the new instance was created, allow it to do additional setup
  576. if ($block = block_instance($blockname, $blockinstance)) {
  577. $block->instance_create();
  578. }
  579. }
  580. public function add_block_at_end_of_default_region($blockname) {
  581. $defaulregion = $this->get_default_region();
  582. $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
  583. if ($lastcurrentblock) {
  584. $weight = $lastcurrentblock->weight + 1;
  585. } else {
  586. $weight = 0;
  587. }
  588. if ($this->page->subpage) {
  589. $subpage = $this->page->subpage;
  590. } else {
  591. $subpage = null;
  592. }
  593. // Special case. Course view page type include the course format, but we
  594. // want to add the block non-format-specifically.
  595. $pagetypepattern = $this->page->pagetype;
  596. if (strpos($pagetypepattern, 'course-view') === 0) {
  597. $pagetypepattern = 'course-view-*';
  598. }
  599. $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
  600. }
  601. /**
  602. * Convenience method, calls add_block repeatedly for all the blocks in $blocks.
  603. *
  604. * @param array $blocks array with array keys the region names, and values an array of block names.
  605. * @param string $pagetypepattern optional. Passed to @see add_block()
  606. * @param string $subpagepattern optional. Passed to @see add_block()
  607. */
  608. public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
  609. $this->add_regions(array_keys($blocks));
  610. foreach ($blocks as $region => $regionblocks) {
  611. $weight = 0;
  612. foreach ($regionblocks as $blockname) {
  613. $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
  614. $weight += 1;
  615. }
  616. }
  617. }
  618. /**
  619. * Move a block to a new position on this page.
  620. *
  621. * If this block cannot appear on any other pages, then we change defaultposition/weight
  622. * in the block_instances table. Otherwise we just set the position on this page.
  623. *
  624. * @param $blockinstanceid the block instance id.
  625. * @param $newregion the new region name.
  626. * @param $newweight the new weight.
  627. */
  628. public function reposition_block($blockinstanceid, $newregion, $newweight) {
  629. global $DB;
  630. $this->check_region_is_known($newregion);
  631. $inst = $this->find_instance($blockinstanceid);
  632. $bi = $inst->instance;
  633. if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
  634. !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
  635. (!$this->page->subpage || $bi->subpagepattern)) {
  636. // Set default position
  637. $newbi = new stdClass;
  638. $newbi->id = $bi->id;
  639. $newbi->defaultregion = $newregion;
  640. $newbi->defaultweight = $newweight;
  641. $DB->update_record('block_instances', $newbi);
  642. if ($bi->blockpositionid) {
  643. $bp = new stdClass;
  644. $bp->id = $bi->blockpositionid;
  645. $bp->region = $newregion;
  646. $bp->weight = $newweight;
  647. $DB->update_record('block_positions', $bp);
  648. }
  649. } else {
  650. // Just set position on this page.
  651. $bp = new stdClass;
  652. $bp->region = $newregion;
  653. $bp->weight = $newweight;
  654. if ($bi->blockpositionid) {
  655. $bp->id = $bi->blockpositionid;
  656. $DB->update_record('block_positions', $bp);
  657. } else {
  658. $bp->blockinstanceid = $bi->id;
  659. $bp->contextid = $this->page->context->id;
  660. $bp->pagetype = $this->page->pagetype;
  661. if ($this->page->subpage) {
  662. $bp->subpage = $this->page->subpage;
  663. } else {
  664. $bp->subpage = '';
  665. }
  666. $bp->visible = $bi->visible;
  667. $DB->insert_record('block_positions', $bp);
  668. }
  669. }
  670. }
  671. /**
  672. * Find a given block by its instance id
  673. *
  674. * @param integer $instanceid
  675. * @return object
  676. */
  677. public function find_instance($instanceid) {
  678. foreach ($this->regions as $region => $notused) {
  679. $this->ensure_instances_exist($region);
  680. foreach($this->blockinstances[$region] as $instance) {
  681. if ($instance->instance->id == $instanceid) {
  682. return $instance;
  683. }
  684. }
  685. }
  686. throw new block_not_on_page_exception($instanceid, $this->page);
  687. }
  688. /// Inner workings =============================================================
  689. /**
  690. * Check whether the page blocks have been loaded yet
  691. *
  692. * @return void Throws coding exception if already loaded
  693. */
  694. protected function check_not_yet_loaded() {
  695. if (!is_null($this->birecordsbyregion)) {
  696. 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.');
  697. }
  698. }
  699. /**
  700. * Check whether the page blocks have been loaded yet
  701. *
  702. * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
  703. *
  704. * @return void Throws coding exception if already loaded
  705. */
  706. protected function check_is_loaded() {
  707. if (is_null($this->birecordsbyregion)) {
  708. throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
  709. }
  710. }
  711. /**
  712. * Check if a block type is known and usable
  713. *
  714. * @param string $blockname The block type name to search for
  715. * @param bool $includeinvisible Include disabled block types in the initial pass
  716. * @return void Coding Exception thrown if unknown or not enabled
  717. */
  718. protected function check_known_block_type($blockname, $includeinvisible = false) {
  719. if (!$this->is_known_block_type($blockname, $includeinvisible)) {
  720. if ($this->is_known_block_type($blockname, true)) {
  721. throw new coding_exception('Unknown block type ' . $blockname);
  722. } else {
  723. throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
  724. }
  725. }
  726. }
  727. /**
  728. * Check if a region is known by its name
  729. *
  730. * @param string $region
  731. * @return void Coding Exception thrown if the region is not known
  732. */
  733. protected function check_region_is_known($region) {
  734. if (!$this->is_known_region($region)) {
  735. throw new coding_exception('Trying to reference an unknown block region ' . $region);
  736. }
  737. }
  738. /**
  739. * Returns an array of region names as keys and nested arrays for values
  740. *
  741. * @return array an array where the array keys are the region names, and the array
  742. * values are empty arrays.
  743. */
  744. protected function prepare_per_region_arrays() {
  745. $result = array();
  746. foreach ($this->regions as $region => $notused) {
  747. $result[$region] = array();
  748. }
  749. return $result;
  750. }
  751. /**
  752. * Create a set of new block instance from a record array
  753. *
  754. * @param array $birecords An array of block instance records
  755. * @return array An array of instantiated block_instance objects
  756. */
  757. protected function create_block_instances($birecords) {
  758. $results = array();
  759. foreach ($birecords as $record) {
  760. if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
  761. $results[] = $blockobject;
  762. }
  763. }
  764. return $results;
  765. }
  766. /**
  767. * Create all the block instances for all the blocks that were loaded by
  768. * load_blocks. This is used, for example, to ensure that all blocks get a
  769. * chance to initialise themselves via the {@link block_base::specialize()}
  770. * method, before any output is done.
  771. */
  772. public function create_all_block_instances() {
  773. foreach ($this->get_regions() as $region) {
  774. $this->ensure_instances_exist($region);
  775. }
  776. }
  777. /**
  778. * Return an array of content objects from a set of block instances
  779. *
  780. * @param array $instances An array of block instances
  781. * @param renderer_base The renderer to use.
  782. * @param string $region the region name.
  783. * @return array An array of block_content (and possibly block_move_target) objects.
  784. */
  785. protected function create_block_contents($instances, $output, $region) {
  786. $results = array();
  787. $lastweight = 0;
  788. $lastblock = 0;
  789. if ($this->movingblock) {
  790. $first = reset($instances);
  791. if ($first) {
  792. $lastweight = $first->instance->weight - 2;
  793. }
  794. $strmoveblockhere = get_string('moveblockhere', 'block');
  795. }
  796. foreach ($instances as $instance) {
  797. $content = $instance->get_content_for_output($output);
  798. if (empty($content)) {
  799. continue;
  800. }
  801. if ($this->movingblock && $lastweight != $instance->instance->weight &&
  802. $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
  803. $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
  804. }
  805. if ($content->blockinstanceid == $this->movingblock) {
  806. $content->add_class('beingmoved');
  807. $content->annotation .= get_string('movingthisblockcancel', 'block',
  808. html_writer::link($this->page->url, get_string('cancel')));
  809. }
  810. $results[] = $content;
  811. $lastweight = $instance->instance->weight;
  812. $lastblock = $instance->instance->id;
  813. }
  814. if ($this->movingblock && $lastblock != $this->movingblock) {
  815. $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1));
  816. }
  817. return $results;
  818. }
  819. /**
  820. * Ensure block instances exist for a given region
  821. *
  822. * @param string $region Check for bi's with the instance with this name
  823. */
  824. protected function ensure_instances_exist($region) {
  825. $this->check_region_is_known($region);
  826. if (!array_key_exists($region, $this->blockinstances)) {
  827. $this->blockinstances[$region] =
  828. $this->create_block_instances($this->birecordsbyregion[$region]);
  829. }
  830. }
  831. /**
  832. * Ensure that there is some content within the given region
  833. *
  834. * @param string $region The name of the region to check
  835. */
  836. protected function ensure_content_created($region, $output) {
  837. $this->ensure_instances_exist($region);
  838. if (!array_key_exists($region, $this->visibleblockcontent)) {
  839. $contents = array();
  840. if (array_key_exists($region, $this->extracontent)) {
  841. $contents = $this->extracontent[$region];
  842. }
  843. $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
  844. if ($region == $this->defaultregion) {
  845. $addblockui = block_add_block_ui($this->page, $output);
  846. if ($addblockui) {
  847. $contents[] = $addblockui;
  848. }
  849. }
  850. $this->visibleblockcontent[$region] = $contents;
  851. }
  852. }
  853. /// Process actions from the URL ===============================================
  854. /**
  855. * Get the appropriate list of editing icons for a block. This is used
  856. * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
  857. *
  858. * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
  859. * @return an array in the format for {@link block_contents::$controls}
  860. */
  861. public function edit_controls($block) {
  862. global $CFG;
  863. if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
  864. $CFG->undeletableblocktypes = array('navigation','settings');
  865. } else if (is_string($CFG->undeletableblocktypes)) {
  866. $CFG->undeletableblocktypes = explode(',', $CFG->undeletableblocktypes);
  867. }
  868. $controls = array();
  869. $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));
  870. // Assign roles icon.
  871. if (has_capability('moodle/role:assign', $block->context)) {
  872. //TODO: please note it is sloppy to pass urls through page parameters!!
  873. // it is shortened because some web servers (e.g. IIS by default) give
  874. // a 'security' error if you try to pass a full URL as a GET parameter in another URL.
  875. $return = $this->page->url->out(false);
  876. $return = str_replace($CFG->wwwroot . '/', '', $return);
  877. $controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin .
  878. '/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return),
  879. 'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));
  880. }
  881. if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
  882. // Show/hide icon.
  883. if ($block->instance->visible) {
  884. $controls[] = array('url' => $actionurl . '&bui_hideid=' . $block->instance->id,
  885. 'icon' => 't/hide', 'caption' => get_string('hide'));
  886. } else {
  887. $controls[] = array('url' => $actionurl . '&bui_showid=' . $block->instance->id,
  888. 'icon' => 't/show', 'caption' => get_string('show'));
  889. }
  890. }
  891. if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
  892. // Edit config icon - always show - needed for positioning UI.
  893. $controls[] = array('url' => $actionurl . '&bui_editid=' . $block->instance->id,
  894. 'icon' => 't/edit', 'caption' => get_string('configuration'));
  895. }
  896. if ($this->page->user_can_edit_blocks() && $block->user_can_edit() && $block->user_can_addto($this->page)) {
  897. if (!in_array($block->instance->blockname, $CFG->undeletableblocktypes)) {
  898. // Delete icon.
  899. $controls[] = array('url' => $actionurl . '&bui_deleteid=' . $block->instance->id,
  900. 'icon' => 't/delete', 'caption' => get_string('delete'));
  901. }
  902. }
  903. if ($this->page->user_can_edit_blocks()) {
  904. // Move icon.
  905. $controls[] = array('url' => $actionurl . '&bui_moveid=' . $block->instance->id,
  906. 'icon' => 't/move', 'caption' => get_string('move'));
  907. }
  908. return $controls;
  909. }
  910. /**
  911. * Process any block actions that were specified in the URL.
  912. *
  913. * This can only be done given a valid $page object.
  914. *
  915. * @param moodle_page $page the page to add blocks to.
  916. * @return boolean true if anything was done. False if not.
  917. */
  918. public function process_url_actions() {
  919. if (!$this->page->user_is_editing()) {
  920. return false;
  921. }
  922. return $this->process_url_add() || $this->process_url_delete() ||
  923. $this->process_url_show_hide() || $this->process_url_edit() ||
  924. $this->process_url_move();
  925. }
  926. /**
  927. * Handle adding a block.
  928. * @return boolean true if anything was done. False if not.
  929. */
  930. public function process_url_add() {
  931. $blocktype = optional_param('bui_addblock', null, PARAM_SAFEDIR);
  932. if (!$blocktype) {
  933. return false;
  934. }
  935. require_sesskey();
  936. if (!$this->page->user_can_edit_blocks()) {
  937. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
  938. }
  939. if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
  940. throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
  941. }
  942. $this->add_block_at_end_of_default_region($blocktype);
  943. // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
  944. $this->page->ensure_param_not_in_url('bui_addblock');
  945. return true;
  946. }
  947. /**
  948. * Handle deleting a block.
  949. * @return boolean true if anything was done. False if not.
  950. */
  951. public function process_url_delete() {
  952. $blockid = optional_param('bui_deleteid', null, PARAM_INTEGER);
  953. if (!$blockid) {
  954. return false;
  955. }
  956. require_sesskey();
  957. $block = $this->page->blocks->find_instance($blockid);
  958. if (!$block->user_can_edit() || !$this->page->user_can_edit_blocks() || !$block->user_can_addto($this->page)) {
  959. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
  960. }
  961. blocks_delete_instance($block->instance);
  962. // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
  963. $this->page->ensure_param_not_in_url('bui_deleteid');
  964. return true;
  965. }
  966. /**
  967. * Handle showing or hiding a block.
  968. * @return boolean true if anything was done. False if not.
  969. */
  970. public function process_url_show_hide() {
  971. if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER)) {
  972. $newvisibility = 0;
  973. } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER)) {
  974. $newvisibility = 1;
  975. } else {
  976. return false;
  977. }
  978. require_sesskey();
  979. $block = $this->page->blocks->find_instance($blockid);
  980. if (!$this->page->user_can_edit_blocks()) {
  981. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
  982. } else if (!$block->instance_can_be_hidden()) {
  983. return false;
  984. }
  985. blocks_set_visibility($block->instance, $this->page, $newvisibility);
  986. // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
  987. $this->page->ensure_param_not_in_url('bui_hideid');
  988. $this->page->ensure_param_not_in_url('bui_showid');
  989. return true;
  990. }
  991. /**
  992. * Handle showing/processing the submission from the block editing form.
  993. * @return boolean true if the form was submitted and the new config saved. Does not
  994. * return if the editing form was displayed. False otherwise.
  995. */
  996. public function process_url_edit() {
  997. global $CFG, $DB, $PAGE;
  998. $blockid = optional_param('bui_editid', null, PARAM_INTEGER);
  999. if (!$blockid) {
  1000. return false;
  1001. }
  1002. require_sesskey();
  1003. require_once($CFG->dirroot . '/blocks/edit_form.php');
  1004. $block = $this->find_instance($blockid);
  1005. if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
  1006. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
  1007. }
  1008. $editpage = new moodle_page();
  1009. $editpage->set_pagelayout('admin');
  1010. $editpage->set_course($this->page->course);
  1011. $editpage->set_context($block->context);
  1012. if ($this->page->cm) {
  1013. $editpage->set_cm($this->page->cm);
  1014. }
  1015. $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
  1016. $editurlparams = $this->page->url->params();
  1017. $editurlparams['bui_editid'] = $blockid;
  1018. $editpage->set_url($editurlbase, $editurlparams);
  1019. $editpage->set_block_actions_done();
  1020. // At this point we are either going to redirect, or display the form, so
  1021. // overwrite global $PAGE ready for this. (Formslib refers to it.)
  1022. $PAGE = $editpage;
  1023. $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
  1024. if (is_readable($formfile)) {
  1025. require_once($formfile);
  1026. $classname = 'block_' . $block->name() . '_edit_form';
  1027. if (!class_exists($classname)) {
  1028. $classname = 'block_edit_form';
  1029. }
  1030. } else {
  1031. $classname = 'block_edit_form';
  1032. }
  1033. $mform = new $classname($editpage->url, $block, $this->page);
  1034. $mform->set_data($block->instance);
  1035. if ($mform->is_cancelled()) {
  1036. redirect($this->page->url);
  1037. } else if ($data = $mform->get_data()) {
  1038. $bi = new stdClass;
  1039. $bi->id = $block->instance->id;
  1040. $bi->pagetypepattern = $data->bui_pagetypepattern;
  1041. if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
  1042. $bi->subpagepattern = null;
  1043. } else {
  1044. $bi->subpagepattern = $data->bui_subpagepattern;
  1045. }
  1046. $parentcontext = get_context_instance_by_id($data->bui_parentcontextid);
  1047. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  1048. // Updating stickiness and contexts. See MDL-21375 for details.
  1049. if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
  1050. // Explicitly set the context
  1051. $bi->parentcontextid = $parentcontext->id;
  1052. // If the context type is > 0 then we'll explicitly set the block as sticky, otherwise not
  1053. $bi->showinsubcontexts = (int)(!empty($data->bui_contexts));
  1054. // If the block wants to be system-wide, then explicitly set that
  1055. if ($data->bui_contexts == 2) { // Only possible on a frontpage or system page
  1056. $bi->parentcontextid = $systemcontext->id;
  1057. } else { // The block doesn't want to be system-wide, so let's ensure that
  1058. if ($parentcontext->id == $systemcontext->id) { // We need to move it to the front page
  1059. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  1060. $bi->parentcontextid = $frontpagecontext->id;
  1061. $bi->pagetypepattern = '*'; // Just in case
  1062. }
  1063. }
  1064. }
  1065. $bi->defaultregion = $data->bui_defaultregion;
  1066. $bi->defaultweight = $data->bui_defaultweight;
  1067. $DB->update_record('block_instances', $bi);
  1068. if (!empty($block->config)) {
  1069. $config = clone($block->config);
  1070. } else {
  1071. $config = new stdClass;
  1072. }
  1073. foreach ($data as $configfield => $value) {
  1074. if (strpos($configfield, 'config_') !== 0) {
  1075. continue;
  1076. }
  1077. $field = substr($configfield, 7);
  1078. $config->$field = $value;
  1079. }
  1080. $block->instance_config_save($config);
  1081. $bp = new stdClass;
  1082. $bp->visible = $data->bui_visible;
  1083. $bp->region = $data->bui_region;
  1084. $bp->weight = $data->bui_weight;
  1085. $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
  1086. $data->bui_weight != $data->bui_defaultweight;
  1087. if ($block->instance->blockpositionid && !$needbprecord) {
  1088. $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
  1089. } else if ($block->instance->blockpositionid && $needbprecord) {
  1090. $bp->id = $block->instance->blockpositionid;
  1091. $DB->update_record('block_positions', $bp);
  1092. } else if ($needbprecord) {
  1093. $bp->blockinstanceid = $block->instance->id;
  1094. $bp->contextid = $this->page->context->id;
  1095. $bp->pagetype = $this->page->pagetype;
  1096. if ($this->page->subpage) {
  1097. $bp->subpage = $this->page->subpage;
  1098. } else {
  1099. $bp->subpage = '';
  1100. }
  1101. $DB->insert_record('block_positions', $bp);
  1102. }
  1103. redirect($this->page->url);
  1104. } else {
  1105. $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
  1106. $editpage->set_title($strheading);
  1107. $editpage->set_heading($strheading);
  1108. $editpage->navbar->add($strheading);
  1109. $output = $editpage->get_renderer('core');
  1110. echo $output->header();
  1111. echo $output->heading($strheading, 2);
  1112. $mform->display();
  1113. echo $output->footer();
  1114. exit;
  1115. }
  1116. }
  1117. /**
  1118. * Handle showing/processing the submission from the block editing form.
  1119. * @return boolean true if the form was submitted and the new config saved. Does not
  1120. * return if the editing form was displayed. False otherwise.
  1121. */
  1122. public function process_url_move() {
  1123. global $CFG, $DB, $PAGE;
  1124. $blockid = optional_param('bui_moveid', null, PARAM_INTEGER);
  1125. if (!$blockid) {
  1126. return false;
  1127. }
  1128. require_sesskey();
  1129. $block = $this->find_instance($blockid);
  1130. if (!$this->page->user_can_edit_blocks()) {
  1131. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
  1132. }
  1133. $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
  1134. $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
  1135. if (!$newregion || is_null($newweight)) {
  1136. // Don't have a valid target position yet, must be just starting the move.
  1137. $this->movingblock = $blockid;
  1138. $this->page->ensure_param_not_in_url('bui_moveid');
  1139. return false;
  1140. }
  1141. if (!$this->is_known_region($newregion)) {
  1142. throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
  1143. }
  1144. // Move this block. This may involve moving other nearby blocks.
  1145. $blocks = $this->birecordsbyregion[$newregion];
  1146. $maxweight = self::MAX_WEIGHT;
  1147. $minweight = -self::MAX_WEIGHT;
  1148. // Initialise the used weights and spareweights array with the default values
  1149. $spareweights = array();
  1150. $usedweights = array();
  1151. for ($i = $minweight; $i <= $maxweight; $i++) {
  1152. $spareweights[$i] = $i;
  1153. $usedweights[$i] = array();
  1154. }
  1155. // Check each block and sort out where we have used weights
  1156. foreach ($blocks as $bi) {
  1157. if ($bi->weight > $maxweight) {
  1158. // If this statement is true then the blocks weight is more than the
  1159. // current maximum. To ensure that we can get the best block position
  1160. // we will initialise elements within the usedweights and spareweights
  1161. // arrays between the blocks weight (which will then be the new max) and
  1162. // the current max
  1163. $parseweight = $bi->weight;
  1164. while (!array_key_exists($parseweight, $usedweights)) {
  1165. $usedweights[$parseweight] = array();
  1166. $spareweights[$parseweight] = $parseweight;
  1167. $parseweight--;
  1168. }
  1169. $maxweight = $bi->weight;
  1170. } else if ($bi->weight < $minweight) {
  1171. // As above except this time the blocks weight is LESS than the
  1172. // the current minimum, so we will initialise the array from the
  1173. // blocks weight (new minimum) to the current minimum
  1174. $parseweight = $bi->weight;
  1175. while (!array_key_exists($parseweight, $usedweights)) {
  1176. $usedweights[$parseweight] = array();
  1177. $spareweights[$parseweight] = $parseweight;
  1178. $parseweight++;
  1179. }
  1180. $minweight = $bi->weight;
  1181. }
  1182. if ($bi->id != $block->instance->id) {
  1183. unset($spareweights[$bi->weight]);
  1184. $usedweights[$bi->weight][] = $bi->id;
  1185. }
  1186. }
  1187. // First we find the nearest gap in the list of weights.
  1188. $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
  1189. $bestgap = null;
  1190. foreach ($spareweights as $spareweight) {
  1191. if (abs($newweight - $spareweight) < $bestdistance) {
  1192. $bestdistance = abs($newweight - $spareweight);
  1193. $bestgap = $spareweight;
  1194. }
  1195. }
  1196. // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
  1197. if (is_null($bestgap)) {
  1198. $bestgap = self::MAX_WEIGHT + 1;
  1199. while (!empty($usedweights[$bestgap])) {
  1200. $bestgap++;
  1201. }
  1202. }
  1203. // Now we know the gap we are aiming for, so move all the blocks along.
  1204. if ($bestgap < $newweight) {
  1205. $newweight = floor($newweight);
  1206. for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
  1207. foreach ($usedweights[$weight] as $biid) {
  1208. $this->reposition_block($biid, $newregion, $weight - 1);
  1209. }
  1210. }
  1211. $this->reposition_block($block->instance->id, $newregion, $newweight);
  1212. } else {
  1213. $newweight = ceil($newweight);
  1214. for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
  1215. foreach ($usedweights[$weight] as $biid) {
  1216. $this->reposition_block($biid, $newregion, $weight + 1);
  1217. }
  1218. }
  1219. $this->reposition_block($block->instance->id, $newregion, $newweight);
  1220. }
  1221. $this->page->ensure_param_not_in_url('bui_moveid');
  1222. $this->page->ensure_param_not_in_url('bui_newregion');
  1223. $this->page->ensure_param_not_in_url('bui_newweight');
  1224. return true;
  1225. }
  1226. /**
  1227. * Turns the display of normal blocks either on or off.
  1228. *
  1229. * @param bool $setting
  1230. */
  1231. public function show_only_fake_blocks($setting = true) {
  1232. $this->fakeblocksonly = $setting;
  1233. }
  1234. }
  1235. /// Helper functions for working with block classes ============================
  1236. /**
  1237. * Call a class method (one that does not require a block instance) on a block class.
  1238. *
  1239. * @param string $blockname the name of the block.
  1240. * @param string $method the method name.
  1241. * @param array $param parameters to pass to the method.
  1242. * @return mixed whatever the method returns.
  1243. */
  1244. function block_method_result($blockname, $method, $param = NULL) {
  1245. if(!block_load_class($blockname)) {
  1246. return NULL;
  1247. }
  1248. return call_user_func(array('block_'.$blockname, $method), $param);
  1249. }
  1250. /**
  1251. * Creates a new instance of the specified block class.
  1252. *
  1253. * @param string $blockname the name of the block.
  1254. * @param $instance block_instances DB table row (optional).
  1255. * @param moodle_page $page the page this block is appearing on.
  1256. * @return block_base the requested block instance.
  1257. */
  1258. function block_instance($blockname, $instance = NULL, $page = NULL) {
  1259. if(!block_load_class($blockname)) {
  1260. return false;
  1261. }
  1262. $classname = 'block_'.$blockname;
  1263. $retval = new $classname;
  1264. if($instance !== NULL) {
  1265. if (is_null($page)) {
  1266. global $PAGE;
  1267. $page = $PAGE;
  1268. }
  1269. $retval->_load_instance($instance, $page);
  1270. }
  1271. return $retval;
  1272. }
  1273. /**
  1274. * Load the block class for a particular type of block.
  1275. *
  1276. * @param string $blockname the name of the block.
  1277. * @return boolean success or failure.
  1278. */
  1279. function block_load_class($blockname) {
  1280. global $CFG;
  1281. if(empty($blockname)) {
  1282. return false;
  1283. }
  1284. $classname = 'block_'.$blockname;
  1285. if(class_exists($classname)) {
  1286. return true;
  1287. }
  1288. $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
  1289. if (file_exists($blockpath)) {
  1290. require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
  1291. include_once($blockpath);
  1292. }else{
  1293. //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
  1294. return false;
  1295. }
  1296. return class_exists($classname);
  1297. }
  1298. /**
  1299. * Given a specific page type, return all the page type patterns that might
  1300. * match it.
  1301. *
  1302. * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
  1303. * @return array an array of all the page type patterns that might match this page type.
  1304. */
  1305. function matching_page_type_patterns($pagetype) {
  1306. $patterns = array($pagetype);
  1307. $bits = explode('-', $pagetype);
  1308. if (count($bits) == 3 && $bits[0] == 'mod') {
  1309. if ($bits[2] == 'view') {
  1310. $patterns[] = 'mod-*-view';
  1311. } else if ($bits[2] == 'index') {
  1312. $patterns[] = 'mod-*-index';
  1313. }
  1314. }
  1315. while (count($bits) > 0) {
  1316. $patterns[] = implode('-', $bits) . '-*';
  1317. array_pop($bits);
  1318. }
  1319. $patterns[] = '*';
  1320. return $patterns;
  1321. }
  1322. /// Functions update the blocks if required by the request parameters ==========
  1323. /**
  1324. * Return a {@link block_contents} representing the add a new block UI, if
  1325. * this user is allowed to see it.
  1326. *
  1327. * @return block_contents an appropriate block_contents, or null if the user
  1328. * cannot add any blocks here.
  1329. */
  1330. function block_add_block_ui($page, $output) {
  1331. global $CFG, $OUTPUT;
  1332. if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
  1333. return null;
  1334. }
  1335. $bc = new block_contents();
  1336. $bc->title = get_string('addblock');
  1337. $bc->add_class('block_adminblock');
  1338. $missingblocks = $page->blocks->get_addable_blocks();
  1339. if (empty($missingblocks)) {
  1340. $bc->content = get_string('noblockstoaddhere');
  1341. return $bc;
  1342. }
  1343. $menu = array();
  1344. foreach ($missingblocks as $block) {
  1345. $blockobject = block_instance($block->name);
  1346. if ($blockobject !== false && $blockobject->user_can_addto($page)) {
  1347. $menu[$block->name] = $blockobject->get_title();
  1348. }
  1349. }
  1350. textlib_get_instance()->asort($menu);
  1351. $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
  1352. $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
  1353. $bc->content = $OUTPUT->render($select);
  1354. return $bc;
  1355. }
  1356. // Functions that have been deprecated by block_manager =======================
  1357. /**
  1358. * @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
  1359. *
  1360. * This function returns an array with the IDs of any blocks that you can add to your page.
  1361. * Parameters are passed by reference for speed; they are not modified at all.
  1362. *
  1363. * @param $page the page object.
  1364. * @param $blockmanager Not used.
  1365. * @return array of block type ids.
  1366. */
  1367. function blocks_get_missing(&$page, &$blockmanager) {
  1368. debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER);
  1369. $blocks = $page->blocks->get_addable_blocks();
  1370. $ids = array();
  1371. foreach ($blocks as $block) {
  1372. $ids[] = $block->id;
  1373. }
  1374. return $ids;
  1375. }
  1376. /**
  1377. * Actually delete from the database any blocks that are currently on this page,
  1378. * but which should not be there according to blocks_name_allowed_in_format.
  1379. *
  1380. * @todo Write/Fix this function. Currently returns immediately
  1381. * @param $course
  1382. */
  1383. function blocks_remove_inappropriate($course) {
  1384. // TODO
  1385. return;
  1386. /*
  1387. $blockmanager = blocks_get_by_page($page);
  1388. if (empty($blockmanager)) {
  1389. return;
  1390. }
  1391. if (($pageformat = $page->pagetype) == NULL) {
  1392. return;
  1393. }
  1394. foreach($blockmanager as $region) {
  1395. foreach($region as $instance) {
  1396. $block = blocks_get_record($instance->blockid);
  1397. if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
  1398. blocks_delete_instance($instance->instance);
  1399. }
  1400. }
  1401. }*/
  1402. }
  1403. /**
  1404. * Check that a given name is in a permittable format
  1405. *
  1406. * @param string $name
  1407. * @param string $pageformat
  1408. * @return bool
  1409. */
  1410. function blocks_name_allowed_in_format($name, $pageformat) {
  1411. $accept = NULL;
  1412. $maxdepth = -1;
  1413. $formats = block_method_result($name, 'applicable_formats');
  1414. if (!$formats) {
  1415. $formats = array();
  1416. }
  1417. foreach ($formats as $format => $allowed) {
  1418. $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
  1419. $depth = substr_count($format, '-');
  1420. if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
  1421. $maxdepth = $depth;
  1422. $accept = $allowed;
  1423. }
  1424. }
  1425. if ($accept === NULL) {
  1426. $accept = !empty($formats['all']);
  1427. }
  1428. return $accept;
  1429. }
  1430. /**
  1431. * Delete a block, and associated data.
  1432. *
  1433. * @param object $instance a row from the block_instances table
  1434. * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
  1435. * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
  1436. */
  1437. function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
  1438. global $DB;
  1439. if ($block = block_instance($instance->blockname, $instance)) {
  1440. $block->instance_delete();
  1441. }
  1442. delete_context(CONTEXT_BLOCK, $instance->id);
  1443. if (!$skipblockstables) {
  1444. $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
  1445. $DB->delete_records('block_instances', array('id' => $instance->id));
  1446. $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
  1447. }
  1448. }
  1449. /**
  1450. * Delete all the blocks that belong to a particular context.
  1451. *
  1452. * @param int $contextid the context id.
  1453. */
  1454. function blocks_delete_all_for_context($contextid) {
  1455. global $DB;
  1456. $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
  1457. foreach ($instances as $instance) {
  1458. blocks_delete_instance($instance, true);
  1459. }
  1460. $instances->close();
  1461. $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
  1462. $DB->delete_records('block_positions', array('contextid' => $contextid));
  1463. }
  1464. /**
  1465. * Set a block to be visible or hidden on a particular page.
  1466. *
  1467. * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
  1468. * block_positions table as return by block_manager.
  1469. * @param moodle_page $page the back to set the visibility with respect to.
  1470. * @param integer $newvisibility 1 for visible, 0 for hidden.
  1471. */
  1472. function blocks_set_visibility($instance, $page, $newvisibility) {
  1473. global $DB;
  1474. if (!empty($instance->blockpositionid)) {
  1475. // Already have local information on this page.
  1476. $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
  1477. return;
  1478. }
  1479. // Create a new block_positions record.
  1480. $bp = new stdClass;
  1481. $bp->blockinstanceid = $instance->id;
  1482. $bp->contextid = $page->context->id;
  1483. $bp->pagetype = $page->pagetype;
  1484. if ($page->subpage) {
  1485. $bp->subpage = $page->subpage;
  1486. }
  1487. $bp->visible = $newvisibility;
  1488. $bp->region = $instance->defaultregion;
  1489. $bp->weight = $instance->defaultweight;
  1490. $DB->insert_record('block_positions', $bp);
  1491. }
  1492. /**
  1493. * @deprecated since 2.0
  1494. * Delete all the blocks from a particular page.
  1495. *
  1496. * @param string $pagetype the page type.
  1497. * @param integer $pageid the page id.
  1498. * @return bool success or failure.
  1499. */
  1500. function blocks_delete_all_on_page($pagetype, $pageid) {
  1501. global $DB;
  1502. debugging('Call to deprecated function blocks_delete_all_on_page. ' .
  1503. 'This function cannot work any more. Doing nothing. ' .
  1504. 'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER);
  1505. return false;
  1506. }
  1507. /**
  1508. * Dispite what this function is called, it seems to be mostly used to populate
  1509. * the default blocks when a new course (or whatever) is created.
  1510. *
  1511. * @deprecated since 2.0
  1512. *
  1513. * @param object $page the page to add default blocks to.
  1514. * @return boolean success or failure.
  1515. */
  1516. function blocks_repopulate_page($page) {
  1517. global $CFG;
  1518. debugging('Call to deprecated function blocks_repopulate_page. ' .
  1519. 'Use a more specific method like blocks_add_default_course_blocks, ' .
  1520. 'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER);
  1521. /// If the site override has been defined, it is the only valid one.
  1522. if (!empty($CFG->defaultblocks_override)) {
  1523. $blocknames = $CFG->defaultblocks_override;
  1524. } else {
  1525. $blocknames = $page->blocks_get_default();
  1526. }
  1527. $blocks = blocks_parse_default_blocks_list($blocknames);
  1528. $page->blocks->add_blocks($blocks);
  1529. return true;
  1530. }
  1531. /**
  1532. * Get the block record for a particular blockid - that is, a particular type os block.
  1533. *
  1534. * @param $int blockid block type id. If null, an array of all block types is returned.
  1535. * @param bool $notusedanymore No longer used.
  1536. * @return array|object row from block table, or all rows.
  1537. */
  1538. function blocks_get_record($blockid = NULL, $notusedanymore = false) {
  1539. global $PAGE;
  1540. $blocks = $PAGE->blocks->get_installed_blocks();
  1541. if ($blockid === NULL) {
  1542. return $blocks;
  1543. } else if (isset($blocks[$blockid])) {
  1544. return $blocks[$blockid];
  1545. } else {
  1546. return false;
  1547. }
  1548. }
  1549. /**
  1550. * Find a given block by its blockid within a provide array
  1551. *
  1552. * @param int $blockid
  1553. * @param array $blocksarray
  1554. * @return bool|object Instance if found else false
  1555. */
  1556. function blocks_find_block($blockid, $blocksarray) {
  1557. if (empty($blocksarray)) {
  1558. return false;
  1559. }
  1560. foreach($blocksarray as $blockgroup) {
  1561. if (empty($blockgroup)) {
  1562. continue;
  1563. }
  1564. foreach($blockgroup as $instance) {
  1565. if($instance->blockid == $blockid) {
  1566. return $instance;
  1567. }
  1568. }
  1569. }
  1570. return false;
  1571. }
  1572. // Functions for programatically adding default blocks to pages ================
  1573. /**
  1574. * Parse a list of default blocks. See config-dist for a description of the format.
  1575. *
  1576. * @param string $blocksstr
  1577. * @return array
  1578. */
  1579. function blocks_parse_default_blocks_list($blocksstr) {
  1580. $blocks = array();
  1581. $bits = explode(':', $blocksstr);
  1582. if (!empty($bits)) {
  1583. $leftbits = trim(array_shift($bits));
  1584. if ($leftbits != '') {
  1585. $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
  1586. }
  1587. }
  1588. if (!empty($bits)) {
  1589. $rightbits =trim(array_shift($bits));
  1590. if ($rightbits != '') {
  1591. $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
  1592. }
  1593. }
  1594. return $blocks;
  1595. }
  1596. /**
  1597. * @return array the blocks that should be added to the site course by default.
  1598. */
  1599. function blocks_get_default_site_course_blocks() {
  1600. global $CFG;
  1601. if (!empty($CFG->defaultblocks_site)) {
  1602. return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
  1603. } else {
  1604. return array(
  1605. BLOCK_POS_LEFT => array('site_main_menu'),
  1606. BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
  1607. );
  1608. }
  1609. }
  1610. /**
  1611. * Add the default blocks to a course.
  1612. *
  1613. * @param object $course a course object.
  1614. */
  1615. function blocks_add_default_course_blocks($course) {
  1616. global $CFG;
  1617. if (!empty($CFG->defaultblocks_override)) {
  1618. $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
  1619. } else if ($course->id == SITEID) {
  1620. $blocknames = blocks_get_default_site_course_blocks();
  1621. } else {
  1622. $defaultblocks = 'defaultblocks_' . $course->format;
  1623. if (!empty($CFG->$defaultblocks)) {
  1624. $blocknames = blocks_parse_default_blocks_list($CFG->$defaultblocks);
  1625. } else {
  1626. $formatconfig = $CFG->dirroot.'/course/format/'.$course->format.'/config.php';
  1627. $format = array(); // initialize array in external file
  1628. if (is_readable($formatconfig)) {
  1629. include($formatconfig);
  1630. }
  1631. if (!empty($format['defaultblocks'])) {
  1632. $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']);
  1633. } else if (!empty($CFG->defaultblocks)){
  1634. $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks);
  1635. } else {
  1636. $blocknames = array(
  1637. BLOCK_POS_LEFT => array(),
  1638. BLOCK_POS_RIGHT => array('search_forums', 'news_items', 'calendar_upcoming', 'recent_activity')
  1639. );
  1640. }
  1641. }
  1642. }
  1643. if ($course->id == SITEID) {
  1644. $pagetypepattern = 'site-index';
  1645. } else {
  1646. $pagetypepattern = 'course-view-*';
  1647. }
  1648. $page = new moodle_page();
  1649. $page->set_course($course);
  1650. $page->blocks->add_blocks($blocknames, $pagetypepattern);
  1651. }
  1652. /**
  1653. * Add the default system-context blocks. E.g. the admin tree.
  1654. */
  1655. function blocks_add_default_system_blocks() {
  1656. global $DB;
  1657. $page = new moodle_page();
  1658. $page->set_context(get_context_instance(CONTEXT_SYSTEM));
  1659. $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
  1660. $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
  1661. if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
  1662. $subpagepattern = $defaultmypage->id;
  1663. } else {
  1664. $subpagepattern = null;
  1665. }
  1666. $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);
  1667. }