PageRenderTime 67ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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. r

Large files files are truncated, but you can click here to view the full file