PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/blocklib.php

https://github.com/dongsheng/moodle
PHP | 2676 lines | 1628 code | 305 blank | 743 comment | 354 complexity | 6170233955961f45057d5c68f76efa8b MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1

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. * Default names for the block regions in the standard theme.
  29. */
  30. define('BLOCK_POS_LEFT', 'side-pre');
  31. define('BLOCK_POS_RIGHT', 'side-post');
  32. /**#@-*/
  33. define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
  34. define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
  35. define('BUI_CONTEXTS_ENTIRE_SITE', 2);
  36. define('BUI_CONTEXTS_CURRENT', 0);
  37. define('BUI_CONTEXTS_CURRENT_SUBS', 1);
  38. // Position of "Add block" control, to be used in theme config as a value for $THEME->addblockposition:
  39. // - default: as a fake block that is displayed in editing mode
  40. // - flatnav: "Add block" item in the flat navigation drawer in editing mode
  41. // - custom: none of the above, theme will take care of displaying the control.
  42. define('BLOCK_ADDBLOCK_POSITION_DEFAULT', 0);
  43. define('BLOCK_ADDBLOCK_POSITION_FLATNAV', 1);
  44. define('BLOCK_ADDBLOCK_POSITION_CUSTOM', -1);
  45. /**
  46. * Exception thrown when someone tried to do something with a block that does
  47. * not exist on a page.
  48. *
  49. * @copyright 2009 Tim Hunt
  50. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  51. * @since Moodle 2.0
  52. */
  53. class block_not_on_page_exception extends moodle_exception {
  54. /**
  55. * Constructor
  56. * @param int $instanceid the block instance id of the block that was looked for.
  57. * @param object $page the current page.
  58. */
  59. public function __construct($instanceid, $page) {
  60. $a = new stdClass;
  61. $a->instanceid = $instanceid;
  62. $a->url = $page->url->out();
  63. parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
  64. }
  65. }
  66. /**
  67. * This class keeps track of the block that should appear on a moodle_page.
  68. *
  69. * The page to work with as passed to the constructor.
  70. *
  71. * @copyright 2009 Tim Hunt
  72. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  73. * @since Moodle 2.0
  74. */
  75. class block_manager {
  76. /**
  77. * The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
  78. * although other weights are valid.
  79. */
  80. const MAX_WEIGHT = 10;
  81. /// Field declarations =========================================================
  82. /**
  83. * the moodle_page we are managing blocks for.
  84. * @var moodle_page
  85. */
  86. protected $page;
  87. /** @var array region name => 1.*/
  88. protected $regions = array();
  89. /** @var string the region where new blocks are added.*/
  90. protected $defaultregion = null;
  91. /** @var array will be $DB->get_records('blocks') */
  92. protected $allblocks = null;
  93. /**
  94. * @var array blocks that this user can add to this page. Will be a subset
  95. * of $allblocks, but with array keys block->name. Access this via the
  96. * {@link get_addable_blocks()} method to ensure it is lazy-loaded.
  97. */
  98. protected $addableblocks = null;
  99. /**
  100. * Will be an array region-name => array(db rows loaded in load_blocks);
  101. * @var array
  102. */
  103. protected $birecordsbyregion = null;
  104. /**
  105. * array region-name => array(block objects); populated as necessary by
  106. * the ensure_instances_exist method.
  107. * @var array
  108. */
  109. protected $blockinstances = array();
  110. /**
  111. * array region-name => array(block_contents objects) what actually needs to
  112. * be displayed in each region.
  113. * @var array
  114. */
  115. protected $visibleblockcontent = array();
  116. /**
  117. * array region-name => array(block_contents objects) extra block-like things
  118. * to be displayed in each region, before the real blocks.
  119. * @var array
  120. */
  121. protected $extracontent = array();
  122. /**
  123. * Used by the block move id, to track whether a block is currently being moved.
  124. *
  125. * When you click on the move icon of a block, first the page needs to reload with
  126. * extra UI for choosing a new position for a particular block. In that situation
  127. * this field holds the id of the block being moved.
  128. *
  129. * @var integer|null
  130. */
  131. protected $movingblock = null;
  132. /**
  133. * Show only fake blocks
  134. */
  135. protected $fakeblocksonly = false;
  136. /// Constructor ================================================================
  137. /**
  138. * Constructor.
  139. * @param object $page the moodle_page object object we are managing the blocks for,
  140. * or a reasonable faxilimily. (See the comment at the top of this class
  141. * and {@link http://en.wikipedia.org/wiki/Duck_typing})
  142. */
  143. public function __construct($page) {
  144. $this->page = $page;
  145. }
  146. /// Getter methods =============================================================
  147. /**
  148. * Get an array of all region names on this page where a block may appear
  149. *
  150. * @return array the internal names of the regions on this page where block may appear.
  151. */
  152. public function get_regions() {
  153. if (is_null($this->defaultregion)) {
  154. $this->page->initialise_theme_and_output();
  155. }
  156. return array_keys($this->regions);
  157. }
  158. /**
  159. * Get the region name of the region blocks are added to by default
  160. *
  161. * @return string the internal names of the region where new blocks are added
  162. * by default, and where any blocks from an unrecognised region are shown.
  163. * (Imagine that blocks were added with one theme selected, then you switched
  164. * to a theme with different block positions.)
  165. */
  166. public function get_default_region() {
  167. $this->page->initialise_theme_and_output();
  168. return $this->defaultregion;
  169. }
  170. /**
  171. * The list of block types that may be added to this page.
  172. *
  173. * @return array block name => record from block table.
  174. */
  175. public function get_addable_blocks() {
  176. $this->check_is_loaded();
  177. if (!is_null($this->addableblocks)) {
  178. return $this->addableblocks;
  179. }
  180. // Lazy load.
  181. $this->addableblocks = array();
  182. $allblocks = blocks_get_record();
  183. if (empty($allblocks)) {
  184. return $this->addableblocks;
  185. }
  186. $unaddableblocks = self::get_undeletable_block_types();
  187. $requiredbythemeblocks = $this->get_required_by_theme_block_types();
  188. $pageformat = $this->page->pagetype;
  189. foreach($allblocks as $block) {
  190. if (!$bi = block_instance($block->name)) {
  191. continue;
  192. }
  193. if ($block->visible && !in_array($block->name, $unaddableblocks) &&
  194. !in_array($block->name, $requiredbythemeblocks) &&
  195. ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
  196. blocks_name_allowed_in_format($block->name, $pageformat) &&
  197. $bi->user_can_addto($this->page)) {
  198. $block->title = $bi->get_title();
  199. $this->addableblocks[$block->name] = $block;
  200. }
  201. }
  202. core_collator::asort_objects_by_property($this->addableblocks, 'title');
  203. return $this->addableblocks;
  204. }
  205. /**
  206. * Given a block name, find out of any of them are currently present in the page
  207. * @param string $blockname - the basic name of a block (eg "navigation")
  208. * @return boolean - is there one of these blocks in the current page?
  209. */
  210. public function is_block_present($blockname) {
  211. if (empty($this->blockinstances)) {
  212. return false;
  213. }
  214. $requiredbythemeblocks = $this->get_required_by_theme_block_types();
  215. foreach ($this->blockinstances as $region) {
  216. foreach ($region as $instance) {
  217. if (empty($instance->instance->blockname)) {
  218. continue;
  219. }
  220. if ($instance->instance->blockname == $blockname) {
  221. if ($instance->instance->requiredbytheme) {
  222. if (!in_array($blockname, $requiredbythemeblocks)) {
  223. continue;
  224. }
  225. }
  226. return true;
  227. }
  228. }
  229. }
  230. return false;
  231. }
  232. /**
  233. * Find out if a block type is known by the system
  234. *
  235. * @param string $blockname the name of the type of block.
  236. * @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
  237. * @return boolean true if this block in installed.
  238. */
  239. public function is_known_block_type($blockname, $includeinvisible = false) {
  240. $blocks = $this->get_installed_blocks();
  241. foreach ($blocks as $block) {
  242. if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
  243. return true;
  244. }
  245. }
  246. return false;
  247. }
  248. /**
  249. * Find out if a region exists on a page
  250. *
  251. * @param string $region a region name
  252. * @return boolean true if this region exists on this page.
  253. */
  254. public function is_known_region($region) {
  255. if (empty($region)) {
  256. return false;
  257. }
  258. return array_key_exists($region, $this->regions);
  259. }
  260. /**
  261. * Get an array of all blocks within a given region
  262. *
  263. * @param string $region a block region that exists on this page.
  264. * @return array of block instances.
  265. */
  266. public function get_blocks_for_region($region) {
  267. $this->check_is_loaded();
  268. $this->ensure_instances_exist($region);
  269. return $this->blockinstances[$region];
  270. }
  271. /**
  272. * Returns an array of block content objects that exist in a region
  273. *
  274. * @param string $region a block region that exists on this page.
  275. * @return array of block block_contents objects for all the blocks in a region.
  276. */
  277. public function get_content_for_region($region, $output) {
  278. $this->check_is_loaded();
  279. $this->ensure_content_created($region, $output);
  280. return $this->visibleblockcontent[$region];
  281. }
  282. /**
  283. * Returns an array of block content objects for all the existings regions
  284. *
  285. * @param renderer_base $output the rendered to use
  286. * @return array of block block_contents objects for all the blocks in all regions.
  287. * @since Moodle 3.3
  288. */
  289. public function get_content_for_all_regions($output) {
  290. $contents = array();
  291. $this->check_is_loaded();
  292. foreach ($this->regions as $region => $val) {
  293. $this->ensure_content_created($region, $output);
  294. $contents[$region] = $this->visibleblockcontent[$region];
  295. }
  296. return $contents;
  297. }
  298. /**
  299. * Helper method used by get_content_for_region.
  300. * @param string $region region name
  301. * @param float $weight weight. May be fractional, since you may want to move a block
  302. * between ones with weight 2 and 3, say ($weight would be 2.5).
  303. * @return string URL for moving block $this->movingblock to this position.
  304. */
  305. protected function get_move_target_url($region, $weight) {
  306. return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
  307. 'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
  308. }
  309. /**
  310. * Determine whether a region contains anything. (Either any real blocks, or
  311. * the add new block UI.)
  312. *
  313. * (You may wonder why the $output parameter is required. Unfortunately,
  314. * because of the way that blocks work, the only reliable way to find out
  315. * if a block will be visible is to get the content for output, and to
  316. * get the content, you need a renderer. Fortunately, this is not a
  317. * performance problem, because we cache the output that is generated, and
  318. * in almost every case where we call region_has_content, we are about to
  319. * output the blocks anyway, so we are not doing wasted effort.)
  320. *
  321. * @param string $region a block region that exists on this page.
  322. * @param core_renderer $output a core_renderer. normally the global $OUTPUT.
  323. * @return boolean Whether there is anything in this region.
  324. */
  325. public function region_has_content($region, $output) {
  326. if (!$this->is_known_region($region)) {
  327. return false;
  328. }
  329. $this->check_is_loaded();
  330. $this->ensure_content_created($region, $output);
  331. // if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
  332. // Mark Nielsen's patch - part 1
  333. if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
  334. // If editing is on, we need all the block regions visible, for the
  335. // move blocks UI.
  336. return true;
  337. }
  338. return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
  339. }
  340. /**
  341. * Determine whether a region contains any fake blocks.
  342. *
  343. * (Fake blocks are typically added to the extracontent array per region)
  344. *
  345. * @param string $region a block region that exists on this page.
  346. * @return boolean Whether there are fake blocks in this region.
  347. */
  348. public function region_has_fakeblocks($region): bool {
  349. return !empty($this->extracontent[$region]);
  350. }
  351. /**
  352. * Get an array of all of the installed blocks.
  353. *
  354. * @return array contents of the block table.
  355. */
  356. public function get_installed_blocks() {
  357. global $DB;
  358. if (is_null($this->allblocks)) {
  359. $this->allblocks = $DB->get_records('block');
  360. }
  361. return $this->allblocks;
  362. }
  363. /**
  364. * @return array names of block types that must exist on every page with this theme.
  365. */
  366. public function get_required_by_theme_block_types() {
  367. $requiredbythemeblocks = false;
  368. if (isset($this->page->theme->requiredblocks)) {
  369. $requiredbythemeblocks = $this->page->theme->requiredblocks;
  370. }
  371. if ($requiredbythemeblocks === false) {
  372. return array('navigation', 'settings');
  373. } else if ($requiredbythemeblocks === '') {
  374. return array();
  375. } else if (is_string($requiredbythemeblocks)) {
  376. return explode(',', $requiredbythemeblocks);
  377. } else {
  378. return $requiredbythemeblocks;
  379. }
  380. }
  381. /**
  382. * Make this block type undeletable and unaddable.
  383. *
  384. * @param mixed $blockidorname string or int
  385. */
  386. public static function protect_block($blockidorname) {
  387. global $DB;
  388. $syscontext = context_system::instance();
  389. require_capability('moodle/site:config', $syscontext);
  390. $block = false;
  391. if (is_int($blockidorname)) {
  392. $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
  393. } else {
  394. $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
  395. }
  396. $undeletableblocktypes = self::get_undeletable_block_types();
  397. if (!in_array($block->name, $undeletableblocktypes)) {
  398. $undeletableblocktypes[] = $block->name;
  399. set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
  400. add_to_config_log('block_protect', "0", "1", $block->name);
  401. }
  402. }
  403. /**
  404. * Make this block type deletable and addable.
  405. *
  406. * @param mixed $blockidorname string or int
  407. */
  408. public static function unprotect_block($blockidorname) {
  409. global $DB;
  410. $syscontext = context_system::instance();
  411. require_capability('moodle/site:config', $syscontext);
  412. $block = false;
  413. if (is_int($blockidorname)) {
  414. $block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
  415. } else {
  416. $block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
  417. }
  418. $undeletableblocktypes = self::get_undeletable_block_types();
  419. if (in_array($block->name, $undeletableblocktypes)) {
  420. $undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name));
  421. set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
  422. add_to_config_log('block_protect', "1", "0", $block->name);
  423. }
  424. }
  425. /**
  426. * Get the list of "protected" blocks via admin block manager ui.
  427. *
  428. * @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
  429. */
  430. public static function get_undeletable_block_types() {
  431. global $CFG;
  432. $undeletableblocks = false;
  433. if (isset($CFG->undeletableblocktypes)) {
  434. $undeletableblocks = $CFG->undeletableblocktypes;
  435. }
  436. if (empty($undeletableblocks)) {
  437. return array();
  438. } else if (is_string($undeletableblocks)) {
  439. return explode(',', $undeletableblocks);
  440. } else {
  441. return $undeletableblocks;
  442. }
  443. }
  444. /// Setter methods =============================================================
  445. /**
  446. * Add a region to a page
  447. *
  448. * @param string $region add a named region where blocks may appear on the current page.
  449. * This is an internal name, like 'side-pre', not a string to display in the UI.
  450. * @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
  451. */
  452. public function add_region($region, $custom = true) {
  453. global $SESSION;
  454. $this->check_not_yet_loaded();
  455. if ($custom) {
  456. if (array_key_exists($region, $this->regions)) {
  457. // This here is EXACTLY why we should not be adding block regions into a page. It should
  458. // ALWAYS be done in a theme layout.
  459. debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
  460. }
  461. // We need to register this custom region against the page type being used.
  462. // This allows us to check, when performing block actions, that unrecognised regions can be worked with.
  463. $type = $this->page->pagetype;
  464. if (!isset($SESSION->custom_block_regions)) {
  465. $SESSION->custom_block_regions = array($type => array($region));
  466. } else if (!isset($SESSION->custom_block_regions[$type])) {
  467. $SESSION->custom_block_regions[$type] = array($region);
  468. } else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
  469. $SESSION->custom_block_regions[$type][] = $region;
  470. }
  471. }
  472. $this->regions[$region] = 1;
  473. // Checking the actual property instead of calling get_default_region as it ends up in a recursive call.
  474. if (empty($this->defaultregion)) {
  475. $this->set_default_region($region);
  476. }
  477. }
  478. /**
  479. * Add an array of regions
  480. * @see add_region()
  481. *
  482. * @param array $regions this utility method calls add_region for each array element.
  483. */
  484. public function add_regions($regions, $custom = true) {
  485. foreach ($regions as $region) {
  486. $this->add_region($region, $custom);
  487. }
  488. }
  489. /**
  490. * Finds custom block regions associated with a page type and registers them with this block manager.
  491. *
  492. * @param string $pagetype
  493. */
  494. public function add_custom_regions_for_pagetype($pagetype) {
  495. global $SESSION;
  496. if (isset($SESSION->custom_block_regions[$pagetype])) {
  497. foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
  498. $this->add_region($customregion, false);
  499. }
  500. }
  501. }
  502. /**
  503. * Set the default region for new blocks on the page
  504. *
  505. * @param string $defaultregion the internal names of the region where new
  506. * blocks should be added by default, and where any blocks from an
  507. * unrecognised region are shown.
  508. */
  509. public function set_default_region($defaultregion) {
  510. $this->check_not_yet_loaded();
  511. if ($defaultregion) {
  512. $this->check_region_is_known($defaultregion);
  513. }
  514. $this->defaultregion = $defaultregion;
  515. }
  516. /**
  517. * Add something that looks like a block, but which isn't an actual block_instance,
  518. * to this page.
  519. *
  520. * @param block_contents $bc the content of the block-like thing.
  521. * @param string $region a block region that exists on this page.
  522. */
  523. public function add_fake_block($bc, $region) {
  524. $this->page->initialise_theme_and_output();
  525. if (!$this->is_known_region($region)) {
  526. $region = $this->get_default_region();
  527. }
  528. if (array_key_exists($region, $this->visibleblockcontent)) {
  529. throw new coding_exception('block_manager has already prepared the blocks in region ' .
  530. $region . 'for output. It is too late to add a fake block.');
  531. }
  532. if (!isset($bc->attributes['data-block'])) {
  533. $bc->attributes['data-block'] = '_fake';
  534. }
  535. $bc->attributes['class'] .= ' block_fake';
  536. $this->extracontent[$region][] = $bc;
  537. }
  538. /**
  539. * Checks to see whether all of the blocks within the given region are docked
  540. *
  541. * @see region_uses_dock
  542. * @param string $region
  543. * @return bool True if all of the blocks within that region are docked
  544. *
  545. * Return false as from MDL-64506
  546. */
  547. public function region_completely_docked($region, $output) {
  548. return false;
  549. }
  550. /**
  551. * Checks to see whether any of the blocks within the given regions are docked
  552. *
  553. * @see region_completely_docked
  554. * @param array|string $regions array of regions (or single region)
  555. * @return bool True if any of the blocks within that region are docked
  556. *
  557. * Return false as from MDL-64506
  558. */
  559. public function region_uses_dock($regions, $output) {
  560. return false;
  561. }
  562. /// Actions ====================================================================
  563. /**
  564. * This method actually loads the blocks for our page from the database.
  565. *
  566. * @param boolean|null $includeinvisible
  567. * null (default) - load hidden blocks if $this->page->user_is_editing();
  568. * true - load hidden blocks.
  569. * false - don't load hidden blocks.
  570. */
  571. public function load_blocks($includeinvisible = null) {
  572. global $DB, $CFG;
  573. if (!is_null($this->birecordsbyregion)) {
  574. // Already done.
  575. return;
  576. }
  577. if ($CFG->version < 2009050619) {
  578. // Upgrade/install not complete. Don't try too show any blocks.
  579. $this->birecordsbyregion = array();
  580. return;
  581. }
  582. // Ensure we have been initialised.
  583. if (is_null($this->defaultregion)) {
  584. $this->page->initialise_theme_and_output();
  585. // If there are still no block regions, then there are no blocks on this page.
  586. if (empty($this->regions)) {
  587. $this->birecordsbyregion = array();
  588. return;
  589. }
  590. }
  591. // Check if we need to load normal blocks
  592. if ($this->fakeblocksonly) {
  593. $this->birecordsbyregion = $this->prepare_per_region_arrays();
  594. return;
  595. }
  596. // Exclude auto created blocks if they are not undeletable in this theme.
  597. $requiredbytheme = $this->get_required_by_theme_block_types();
  598. $requiredbythemecheck = '';
  599. $requiredbythemeparams = array();
  600. $requiredbythemenotparams = array();
  601. if (!empty($requiredbytheme)) {
  602. list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED, 'requiredbytheme');
  603. list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED,
  604. 'notrequiredbytheme', false);
  605. $requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
  606. ' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
  607. } else {
  608. $requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
  609. }
  610. if (is_null($includeinvisible)) {
  611. $includeinvisible = $this->page->user_is_editing();
  612. }
  613. if ($includeinvisible) {
  614. $visiblecheck = '';
  615. } else {
  616. $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL) AND (bs.visible = 1 OR bs.visible IS NULL)';
  617. }
  618. $context = $this->page->context;
  619. $contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
  620. $parentcontextparams = array();
  621. $parentcontextids = $context->get_parent_context_ids();
  622. if ($parentcontextids) {
  623. list($parentcontexttest, $parentcontextparams) =
  624. $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
  625. $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
  626. }
  627. $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
  628. list($pagetypepatterntest, $pagetypepatternparams) =
  629. $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
  630. $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  631. $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
  632. $systemcontext = context_system::instance();
  633. $params = array(
  634. 'contextlevel' => CONTEXT_BLOCK,
  635. 'subpage1' => $this->page->subpage,
  636. 'subpage2' => $this->page->subpage,
  637. 'subpage3' => $this->page->subpage,
  638. 'contextid1' => $context->id,
  639. 'contextid2' => $context->id,
  640. 'contextid3' => $systemcontext->id,
  641. 'contextid4' => $systemcontext->id,
  642. 'pagetype' => $this->page->pagetype,
  643. 'pagetype2' => $this->page->pagetype,
  644. );
  645. if ($this->page->subpage === '') {
  646. $params['subpage1'] = '';
  647. $params['subpage2'] = '';
  648. $params['subpage3'] = '';
  649. }
  650. $sql = "SELECT
  651. bi.id,
  652. COALESCE(bp.id, bs.id) AS blockpositionid,
  653. bi.blockname,
  654. bi.parentcontextid,
  655. bi.showinsubcontexts,
  656. bi.pagetypepattern,
  657. bi.requiredbytheme,
  658. bi.subpagepattern,
  659. bi.defaultregion,
  660. bi.defaultweight,
  661. COALESCE(bp.visible, bs.visible, 1) AS visible,
  662. COALESCE(bp.region, bs.region, bi.defaultregion) AS region,
  663. COALESCE(bp.weight, bs.weight, bi.defaultweight) AS weight,
  664. bi.configdata
  665. $ccselect
  666. FROM {block_instances} bi
  667. JOIN {block} b ON bi.blockname = b.name
  668. LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
  669. AND bp.contextid = :contextid1
  670. AND bp.pagetype = :pagetype
  671. AND bp.subpage = :subpage1
  672. LEFT JOIN {block_positions} bs ON bs.blockinstanceid = bi.id
  673. AND bs.contextid = :contextid4
  674. AND bs.pagetype = :pagetype2
  675. AND bs.subpage = :subpage3
  676. $ccjoin
  677. WHERE
  678. $contexttest
  679. AND bi.pagetypepattern $pagetypepatterntest
  680. AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
  681. $visiblecheck
  682. AND b.visible = 1
  683. $requiredbythemecheck
  684. ORDER BY
  685. COALESCE(bp.region, bs.region, bi.defaultregion),
  686. COALESCE(bp.weight, bs.weight, bi.defaultweight),
  687. bi.id";
  688. $allparams = $params + $parentcontextparams + $pagetypepatternparams + $requiredbythemeparams + $requiredbythemenotparams;
  689. $blockinstances = $DB->get_recordset_sql($sql, $allparams);
  690. $this->birecordsbyregion = $this->prepare_per_region_arrays();
  691. $unknown = array();
  692. foreach ($blockinstances as $bi) {
  693. context_helper::preload_from_record($bi);
  694. if ($this->is_known_region($bi->region)) {
  695. $this->birecordsbyregion[$bi->region][] = $bi;
  696. } else {
  697. $unknown[] = $bi;
  698. }
  699. }
  700. $blockinstances->close();
  701. // Pages don't necessarily have a defaultregion. The one time this can
  702. // happen is when there are no theme block regions, but the script itself
  703. // has a block region in the main content area.
  704. if (!empty($this->defaultregion)) {
  705. $this->birecordsbyregion[$this->defaultregion] =
  706. array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
  707. }
  708. }
  709. /**
  710. * Add a block to the current page, or related pages. The block is added to
  711. * context $this->page->contextid. If $pagetypepattern $subpagepattern
  712. *
  713. * @param string $blockname The type of block to add.
  714. * @param string $region the block region on this page to add the block to.
  715. * @param integer $weight determines the order where this block appears in the region.
  716. * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
  717. * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
  718. * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
  719. */
  720. public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
  721. global $DB;
  722. // Allow invisible blocks because this is used when adding default page blocks, which
  723. // might include invisible ones if the user makes some default blocks invisible
  724. $this->check_known_block_type($blockname, true);
  725. $this->check_region_is_known($region);
  726. if (empty($pagetypepattern)) {
  727. $pagetypepattern = $this->page->pagetype;
  728. }
  729. $blockinstance = new stdClass;
  730. $blockinstance->blockname = $blockname;
  731. $blockinstance->parentcontextid = $this->page->context->id;
  732. $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
  733. $blockinstance->pagetypepattern = $pagetypepattern;
  734. $blockinstance->subpagepattern = $subpagepattern;
  735. $blockinstance->defaultregion = $region;
  736. $blockinstance->defaultweight = $weight;
  737. $blockinstance->configdata = '';
  738. $blockinstance->timecreated = time();
  739. $blockinstance->timemodified = $blockinstance->timecreated;
  740. $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
  741. // Ensure the block context is created.
  742. context_block::instance($blockinstance->id);
  743. // If the new instance was created, allow it to do additional setup
  744. if ($block = block_instance($blockname, $blockinstance)) {
  745. $block->instance_create();
  746. }
  747. }
  748. public function add_block_at_end_of_default_region($blockname) {
  749. if (empty($this->birecordsbyregion)) {
  750. // No blocks or block regions exist yet.
  751. return;
  752. }
  753. $defaulregion = $this->get_default_region();
  754. $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
  755. if ($lastcurrentblock) {
  756. $weight = $lastcurrentblock->weight + 1;
  757. } else {
  758. $weight = 0;
  759. }
  760. if ($this->page->subpage) {
  761. $subpage = $this->page->subpage;
  762. } else {
  763. $subpage = null;
  764. }
  765. // Special case. Course view page type include the course format, but we
  766. // want to add the block non-format-specifically.
  767. $pagetypepattern = $this->page->pagetype;
  768. if (strpos($pagetypepattern, 'course-view') === 0) {
  769. $pagetypepattern = 'course-view-*';
  770. }
  771. // We should end using this for ALL the blocks, making always the 1st option
  772. // the default one to be used. Until then, this is one hack to avoid the
  773. // 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
  774. // non-existing $pagetypepattern set. This way at least we guarantee one "valid"
  775. // (the FIRST $pagetypepattern will be set)
  776. // We are applying it to all blocks created in mod pages for now and only if the
  777. // default pagetype is not one of the available options
  778. if (preg_match('/^mod-.*-/', $pagetypepattern)) {
  779. $pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
  780. // Only go for the first if the pagetype is not a valid option
  781. if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
  782. $pagetypepattern = key($pagetypelist);
  783. }
  784. }
  785. // Surely other pages like course-report will need this too, they just are not important
  786. // enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
  787. $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
  788. }
  789. /**
  790. * Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
  791. * can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
  792. * and incremented by the position of the block in the $blocks array
  793. *
  794. * @param array $blocks array with array keys the region names, and values an array of block names.
  795. * @param string $pagetypepattern optional. Passed to {@link add_block()}
  796. * @param string $subpagepattern optional. Passed to {@link add_block()}
  797. * @param boolean $showinsubcontexts optional. Passed to {@link add_block()}
  798. * @param integer $weight optional. Determines the starting point that the blocks are added in the region.
  799. */
  800. public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
  801. $initialweight = $weight;
  802. $this->add_regions(array_keys($blocks), false);
  803. foreach ($blocks as $region => $regionblocks) {
  804. foreach ($regionblocks as $offset => $blockname) {
  805. $weight = $initialweight + $offset;
  806. $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
  807. }
  808. }
  809. }
  810. /**
  811. * Move a block to a new position on this page.
  812. *
  813. * If this block cannot appear on any other pages, then we change defaultposition/weight
  814. * in the block_instances table. Otherwise we just set the position on this page.
  815. *
  816. * @param $blockinstanceid the block instance id.
  817. * @param $newregion the new region name.
  818. * @param $newweight the new weight.
  819. */
  820. public function reposition_block($blockinstanceid, $newregion, $newweight) {
  821. global $DB;
  822. $this->check_region_is_known($newregion);
  823. $inst = $this->find_instance($blockinstanceid);
  824. $bi = $inst->instance;
  825. if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
  826. !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
  827. (!$this->page->subpage || $bi->subpagepattern)) {
  828. // Set default position
  829. $newbi = new stdClass;
  830. $newbi->id = $bi->id;
  831. $newbi->defaultregion = $newregion;
  832. $newbi->defaultweight = $newweight;
  833. $newbi->timemodified = time();
  834. $DB->update_record('block_instances', $newbi);
  835. if ($bi->blockpositionid) {
  836. $bp = new stdClass;
  837. $bp->id = $bi->blockpositionid;
  838. $bp->region = $newregion;
  839. $bp->weight = $newweight;
  840. $DB->update_record('block_positions', $bp);
  841. }
  842. } else {
  843. // Just set position on this page.
  844. $bp = new stdClass;
  845. $bp->region = $newregion;
  846. $bp->weight = $newweight;
  847. if ($bi->blockpositionid) {
  848. $bp->id = $bi->blockpositionid;
  849. $DB->update_record('block_positions', $bp);
  850. } else {
  851. $bp->blockinstanceid = $bi->id;
  852. $bp->contextid = $this->page->context->id;
  853. $bp->pagetype = $this->page->pagetype;
  854. if ($this->page->subpage) {
  855. $bp->subpage = $this->page->subpage;
  856. } else {
  857. $bp->subpage = '';
  858. }
  859. $bp->visible = $bi->visible;
  860. $DB->insert_record('block_positions', $bp);
  861. }
  862. }
  863. }
  864. /**
  865. * Find a given block by its instance id
  866. *
  867. * @param integer $instanceid
  868. * @return block_base
  869. */
  870. public function find_instance($instanceid) {
  871. foreach ($this->regions as $region => $notused) {
  872. $this->ensure_instances_exist($region);
  873. foreach($this->blockinstances[$region] as $instance) {
  874. if ($instance->instance->id == $instanceid) {
  875. return $instance;
  876. }
  877. }
  878. }
  879. throw new block_not_on_page_exception($instanceid, $this->page);
  880. }
  881. /// Inner workings =============================================================
  882. /**
  883. * Check whether the page blocks have been loaded yet
  884. *
  885. * @return void Throws coding exception if already loaded
  886. */
  887. protected function check_not_yet_loaded() {
  888. if (!is_null($this->birecordsbyregion)) {
  889. 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.');
  890. }
  891. }
  892. /**
  893. * Check whether the page blocks have been loaded yet
  894. *
  895. * Nearly identical to the above function {@link check_not_yet_loaded()} except different message
  896. *
  897. * @return void Throws coding exception if already loaded
  898. */
  899. protected function check_is_loaded() {
  900. if (is_null($this->birecordsbyregion)) {
  901. throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
  902. }
  903. }
  904. /**
  905. * Check if a block type is known and usable
  906. *
  907. * @param string $blockname The block type name to search for
  908. * @param bool $includeinvisible Include disabled block types in the initial pass
  909. * @return void Coding Exception thrown if unknown or not enabled
  910. */
  911. protected function check_known_block_type($blockname, $includeinvisible = false) {
  912. if (!$this->is_known_block_type($blockname, $includeinvisible)) {
  913. if ($this->is_known_block_type($blockname, true)) {
  914. throw new coding_exception('Unknown block type ' . $blockname);
  915. } else {
  916. throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
  917. }
  918. }
  919. }
  920. /**
  921. * Check if a region is known by its name
  922. *
  923. * @param string $region
  924. * @return void Coding Exception thrown if the region is not known
  925. */
  926. protected function check_region_is_known($region) {
  927. if (!$this->is_known_region($region)) {
  928. throw new coding_exception('Trying to reference an unknown block region ' . $region);
  929. }
  930. }
  931. /**
  932. * Returns an array of region names as keys and nested arrays for values
  933. *
  934. * @return array an array where the array keys are the region names, and the array
  935. * values are empty arrays.
  936. */
  937. protected function prepare_per_region_arrays() {
  938. $result = array();
  939. foreach ($this->regions as $region => $notused) {
  940. $result[$region] = array();
  941. }
  942. return $result;
  943. }
  944. /**
  945. * Create a set of new block instance from a record array
  946. *
  947. * @param array $birecords An array of block instance records
  948. * @return array An array of instantiated block_instance objects
  949. */
  950. protected function create_block_instances($birecords) {
  951. $results = array();
  952. foreach ($birecords as $record) {
  953. if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
  954. $results[] = $blockobject;
  955. }
  956. }
  957. return $results;
  958. }
  959. /**
  960. * Create all the block instances for all the blocks that were loaded by
  961. * load_blocks. This is used, for example, to ensure that all blocks get a
  962. * chance to initialise themselves via the {@link block_base::specialize()}
  963. * method, before any output is done.
  964. *
  965. * It is also used to create any blocks that are "requiredbytheme" by the current theme.
  966. * These blocks that are auto-created have requiredbytheme set on the block instance
  967. * so they are only visible on themes that require them.
  968. */
  969. public function create_all_block_instances() {
  970. $missing = false;
  971. // If there are any un-removable blocks that were not created - force them.
  972. $requiredbytheme = $this->get_required_by_theme_block_types();
  973. if (!$this->fakeblocksonly) {
  974. foreach ($requiredbytheme as $forced) {
  975. if (empty($forced)) {
  976. continue;
  977. }
  978. $found = false;
  979. foreach ($this->get_regions() as $region) {
  980. foreach($this->birecordsbyregion[$region] as $instance) {
  981. if ($instance->blockname == $forced) {
  982. $found = true;
  983. }
  984. }
  985. }
  986. if (!$found) {
  987. $this->add_block_required_by_theme($forced);
  988. $missing = true;
  989. }
  990. }
  991. }
  992. if ($missing) {
  993. // Some blocks were missing. Lets do it again.
  994. $this->birecordsbyregion = null;
  995. $this->load_blocks();
  996. }
  997. foreach ($this->get_regions() as $region) {
  998. $this->ensure_instances_exist($region);
  999. }
  1000. }
  1001. /**
  1002. * Add a block that is required by the current theme but has not been
  1003. * created yet. This is a special type of block that only shows in themes that
  1004. * require it (by listing it in undeletable_block_types).
  1005. *
  1006. * @param string $blockname the name of the block type.
  1007. */
  1008. protected function add_block_required_by_theme($blockname) {
  1009. global $DB;
  1010. if (empty($this->birecordsbyregion)) {
  1011. // No blocks or block regions exist yet.
  1012. return;
  1013. }
  1014. // Never auto create blocks when we are showing fake blocks only.
  1015. if ($this->fakeblocksonly) {
  1016. return;
  1017. }
  1018. // Never add a duplicate block required by theme.
  1019. if ($DB->record_exists('block_instances', array('blockname' => $blockname, 'requiredbytheme' => 1))) {
  1020. return;
  1021. }
  1022. $systemcontext = context_system::instance();
  1023. $defaultregion = $this->get_default_region();
  1024. // Add a special system wide block instance only for themes that require it.
  1025. $blockinstance = new stdClass;
  1026. $blockinstance->blockname = $blockname;
  1027. $blockinstance->parentcontextid = $systemcontext->id;
  1028. $blockinstance->showinsubcontexts = true;
  1029. $blockinstance->requiredbytheme = true;
  1030. $blockinstance->pagetypepattern = '*';
  1031. $blockinstance->subpagepattern = null;
  1032. $blockinstance->defaultregion = $defaultregion;
  1033. $blockinstance->defaultweight = 0;
  1034. $blockinstance->configdata = '';
  1035. $blockinstance->timecreated = time();
  1036. $blockinstance->timemodified = $blockinstance->timecreated;
  1037. $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
  1038. // Ensure the block context is created.
  1039. context_block::instance($blockinstance->id);
  1040. // If the new instance was created, allow it to do additional setup.
  1041. if ($block = block_instance($blockname, $blockinstance)) {
  1042. $block->instance_create();
  1043. }
  1044. }
  1045. /**
  1046. * Return an array of content objects from a set of block instances
  1047. *
  1048. * @param array $instances An array of block instances
  1049. * @param renderer_base The renderer to use.
  1050. * @param string $region the region name.
  1051. * @return array An array of block_content (and possibly block_move_target) objects.
  1052. */
  1053. protected function create_block_contents($instances, $output, $region) {
  1054. $results = array();
  1055. $lastweight = 0;
  1056. $lastblock = 0;
  1057. if ($this->movingblock) {
  1058. $first = reset($instances);
  1059. if ($first) {
  1060. $lastweight = $first->instance->weight - 2;
  1061. }
  1062. }
  1063. foreach ($instances as $instance) {
  1064. $content = $instance->get_content_for_output($output);
  1065. if (empty($content)) {
  1066. continue;
  1067. }
  1068. if ($this->movingblock && $lastweight != $instance->instance->weight &&
  1069. $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
  1070. $results[] = new block_move_target($this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
  1071. }
  1072. if ($content->blockinstanceid == $this->movingblock) {
  1073. $content->add_class('beingmoved');
  1074. $content->annotation .= get_string('movingthisblockcancel', 'block',
  1075. html_writer::link($this->page->url, get_string('cancel')));
  1076. }
  1077. $results[] = $content;
  1078. $lastweight = $instance->instance->weight;
  1079. $lastblock = $instance->instance->id;
  1080. }
  1081. if ($this->movingblock && $lastblock != $this->movingblock) {
  1082. $results[] = new block_move_target($this->get_move_target_url($region, $lastweight + 1));
  1083. }
  1084. return $results;
  1085. }
  1086. /**
  1087. * Ensure block instances exist for a given region
  1088. *
  1089. * @param string $region Check for bi's with the instance with this name
  1090. */
  1091. protected function ensure_instances_exist($region) {
  1092. $this->check_region_is_known($region);
  1093. if (!array_key_exists($region, $this->blockinstances)) {
  1094. $this->blockinstances[$region] =
  1095. $this->create_block_instances($this->birecordsbyregion[$region]);
  1096. }
  1097. }
  1098. /**
  1099. * Ensure that there is some content within the given region
  1100. *
  1101. * @param string $region The name of the region to check
  1102. */
  1103. public function ensure_content_created($region, $output) {
  1104. $this->ensure_instances_exist($region);
  1105. if (!has_capability('moodle/block:view', $this->page->context) ) {
  1106. $this->visibleblockcontent[$region] = [];
  1107. return;
  1108. }
  1109. if (!array_key_exists($region, $this->visibleblockcontent)) {
  1110. $contents = array();
  1111. if (array_key_exists($region, $this->extracontent)) {
  1112. $contents = $this->extracontent[$region];
  1113. }
  1114. $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
  1115. if (($region == $this->defaultregion) && (!isset($this->page->theme->addblockposition) ||
  1116. $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_DEFAULT)) {
  1117. $addblockui = block_add_block_ui($this->page, $output);
  1118. if ($addblockui) {
  1119. $contents[] = $addblockui;
  1120. }
  1121. }
  1122. $this->visibleblockcontent[$region] = $contents;
  1123. }
  1124. }
  1125. /// Process actions from the URL ===============================================
  1126. /**
  1127. * Get the appropriate list of editing icons for a block. This is used
  1128. * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
  1129. *
  1130. * @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
  1131. * @return an array in the format for {@link block_contents::$controls}
  1132. */
  1133. public function edit_controls($block) {
  1134. global $CFG;
  1135. $controls = array();
  1136. $actionurl

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