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

/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
  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 = $this->page->url->out(false, array('sesskey'=> sesskey()));
  1137. $blocktitle = $block->title;
  1138. if (empty($blocktitle)) {
  1139. $blocktitle = $block->arialabel;
  1140. }
  1141. if ($this->page->user_can_edit_blocks()) {
  1142. // Move icon.
  1143. $str = new lang_string('moveblock', 'block', $blocktitle);
  1144. $controls[] = new action_menu_link_primary(
  1145. new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)),
  1146. new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1147. $str,
  1148. array('class' => 'editing_move')
  1149. );
  1150. }
  1151. if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
  1152. // Edit config icon - always show - needed for positioning UI.
  1153. $str = new lang_string('configureblock', 'block', $blocktitle);
  1154. $editactionurl = new moodle_url($actionurl, ['bui_editid' => $block->instance->id]);
  1155. $editactionurl->remove_params(['sesskey']);
  1156. // Handle editing block on admin index page, prevent the page redirecting before block action can begin.
  1157. if ($editactionurl->compare(new moodle_url('/admin/index.php'), URL_MATCH_BASE)) {
  1158. $editactionurl->param('cache', 1);
  1159. }
  1160. $controls[] = new action_menu_link_secondary(
  1161. $editactionurl,
  1162. new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1163. $str,
  1164. array('class' => 'editing_edit')
  1165. );
  1166. }
  1167. if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
  1168. // Show/hide icon.
  1169. if ($block->instance->visible) {
  1170. $str = new lang_string('hideblock', 'block', $blocktitle);
  1171. $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id));
  1172. $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
  1173. $attributes = array('class' => 'editing_hide');
  1174. } else {
  1175. $str = new lang_string('showblock', 'block', $blocktitle);
  1176. $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id));
  1177. $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => ''));
  1178. $attributes = array('class' => 'editing_show');
  1179. }
  1180. $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes);
  1181. }
  1182. // Assign roles.
  1183. if (get_assignable_roles($block->context, ROLENAME_SHORT)) {
  1184. $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id,
  1185. 'returnurl' => $this->page->url->out_as_local_url()));
  1186. $str = new lang_string('assignrolesinblock', 'block', $blocktitle);
  1187. $controls[] = new action_menu_link_secondary(
  1188. $rolesurl,
  1189. new pix_icon('i/assignroles', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1190. $str, array('class' => 'editing_assignroles')
  1191. );
  1192. }
  1193. // Permissions.
  1194. if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) {
  1195. $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id,
  1196. 'returnurl' => $this->page->url->out_as_local_url()));
  1197. $str = get_string('permissions', 'role');
  1198. $controls[] = new action_menu_link_secondary(
  1199. $rolesurl,
  1200. new pix_icon('i/permissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1201. $str, array('class' => 'editing_permissions')
  1202. );
  1203. }
  1204. // Change permissions.
  1205. if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) {
  1206. $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id,
  1207. 'returnurl' => $this->page->url->out_as_local_url()));
  1208. $str = get_string('checkpermissions', 'role');
  1209. $controls[] = new action_menu_link_secondary(
  1210. $rolesurl,
  1211. new pix_icon('i/checkpermissions', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1212. $str, array('class' => 'editing_checkroles')
  1213. );
  1214. }
  1215. if ($this->user_can_delete_block($block)) {
  1216. // Delete icon.
  1217. $str = new lang_string('deleteblock', 'block', $blocktitle);
  1218. $deleteactionurl = new moodle_url($actionurl, ['bui_deleteid' => $block->instance->id]);
  1219. $deleteactionurl->remove_params(['sesskey']);
  1220. // Handle deleting block on admin index page, prevent the page redirecting before block action can begin.
  1221. if ($deleteactionurl->compare(new moodle_url('/admin/index.php'), URL_MATCH_BASE)) {
  1222. $deleteactionurl->param('cache', 1);
  1223. }
  1224. $deleteconfirmationurl = new moodle_url($actionurl, [
  1225. 'bui_deleteid' => $block->instance->id,
  1226. 'bui_confirm' => 1,
  1227. 'sesskey' => sesskey(),
  1228. ]);
  1229. $blocktitle = $block->get_title();
  1230. $controls[] = new action_menu_link_secondary(
  1231. $deleteactionurl,
  1232. new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1233. $str,
  1234. [
  1235. 'class' => 'editing_delete',
  1236. 'data-confirmation' => 'modal',
  1237. 'data-confirmation-title-str' => json_encode(['deletecheck_modal', 'block']),
  1238. 'data-confirmation-question-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),
  1239. 'data-confirmation-yes-button-str' => json_encode(['delete', 'core']),
  1240. 'data-confirmation-toast' => 'true',
  1241. 'data-confirmation-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),
  1242. 'data-confirmation-destination' => $deleteconfirmationurl->out(false),
  1243. ]
  1244. );
  1245. }
  1246. if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $block->context)) {
  1247. $parentcontext = $block->context->get_parent_context();
  1248. if (empty($parentcontext) || empty($parentcontext->locked)) {
  1249. if ($block->context->locked) {
  1250. $lockicon = 'i/unlock';
  1251. $lockstring = get_string('managecontextunlock', 'admin');
  1252. } else {
  1253. $lockicon = 'i/lock';
  1254. $lockstring = get_string('managecontextlock', 'admin');
  1255. }
  1256. $controls[] = new action_menu_link_secondary(
  1257. new moodle_url(
  1258. '/admin/lock.php',
  1259. [
  1260. 'id' => $block->context->id,
  1261. ]
  1262. ),
  1263. new pix_icon($lockicon, $lockstring, 'moodle', array('class' => 'iconsmall', 'title' => '')),
  1264. $lockstring,
  1265. ['class' => 'editing_lock']
  1266. );
  1267. }
  1268. }
  1269. return $controls;
  1270. }
  1271. /**
  1272. * @param block_base $block a block that appears on this page.
  1273. * @return boolean boolean whether the currently logged in user is allowed to delete this block.
  1274. */
  1275. protected function user_can_delete_block($block) {
  1276. return $this->page->user_can_edit_blocks() && $block->user_can_edit() &&
  1277. $block->user_can_addto($this->page) &&
  1278. !in_array($block->instance->blockname, self::get_undeletable_block_types()) &&
  1279. !in_array($block->instance->blockname, $this->get_required_by_theme_block_types());
  1280. }
  1281. /**
  1282. * Process any block actions that were specified in the URL.
  1283. *
  1284. * @return boolean true if anything was done. False if not.
  1285. */
  1286. public function process_url_actions() {
  1287. if (!$this->page->user_is_editing()) {
  1288. return false;
  1289. }
  1290. return $this->process_url_add() || $this->process_url_delete() ||
  1291. $this->process_url_show_hide() || $this->process_url_edit() ||
  1292. $this->process_url_move();
  1293. }
  1294. /**
  1295. * Handle adding a block.
  1296. * @return boolean true if anything was done. False if not.
  1297. */
  1298. public function process_url_add() {
  1299. global $CFG, $PAGE, $OUTPUT;
  1300. $blocktype = optional_param('bui_addblock', null, PARAM_PLUGIN);
  1301. if ($blocktype === null) {
  1302. return false;
  1303. }
  1304. require_sesskey();
  1305. if (!$this->page->user_can_edit_blocks()) {
  1306. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
  1307. }
  1308. $addableblocks = $this->get_addable_blocks();
  1309. if ($blocktype === '') {
  1310. // Display add block selection.
  1311. $addpage = new moodle_page();
  1312. $addpage->set_pagelayout('admin');
  1313. $addpage->blocks->show_only_fake_blocks(true);
  1314. $addpage->set_course($this->page->course);
  1315. $addpage->set_context($this->page->context);
  1316. if ($this->page->cm) {
  1317. $addpage->set_cm($this->page->cm);
  1318. }
  1319. $addpagebase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
  1320. $addpageparams = $this->page->url->params();
  1321. $addpage->set_url($addpagebase, $addpageparams);
  1322. $addpage->set_block_actions_done();
  1323. // At this point we are going to display the block selector, overwrite global $PAGE ready for this.
  1324. $PAGE = $addpage;
  1325. // Some functions use $OUTPUT so we need to replace that too.
  1326. $OUTPUT = $addpage->get_renderer('core');
  1327. $site = get_site();
  1328. $straddblock = get_string('addblock');
  1329. $PAGE->navbar->add($straddblock);
  1330. $PAGE->set_title($straddblock);
  1331. $PAGE->set_heading($site->fullname);
  1332. echo $OUTPUT->header();
  1333. echo $OUTPUT->heading($straddblock);
  1334. if (!$addableblocks) {
  1335. echo $OUTPUT->box(get_string('noblockstoaddhere'));
  1336. echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('back')), 'mx-3 mb-1');
  1337. } else {
  1338. $url = new moodle_url($addpage->url, array('sesskey' => sesskey()));
  1339. echo $OUTPUT->render_from_template('core/add_block_body',
  1340. ['blocks' => array_values($addableblocks),
  1341. 'url' => '?' . $url->get_query_string(false)]);
  1342. echo $OUTPUT->container($OUTPUT->action_link($addpage->url, get_string('cancel')), 'mx-3 mb-1');
  1343. }
  1344. echo $OUTPUT->footer();
  1345. // Make sure that nothing else happens after we have displayed this form.
  1346. exit;
  1347. }
  1348. if (!array_key_exists($blocktype, $addableblocks)) {
  1349. throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
  1350. }
  1351. $this->add_block_at_end_of_default_region($blocktype);
  1352. // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
  1353. $this->page->ensure_param_not_in_url('bui_addblock');
  1354. return true;
  1355. }
  1356. /**
  1357. * Handle deleting a block.
  1358. * @return boolean true if anything was done. False if not.
  1359. */
  1360. public function process_url_delete() {
  1361. global $CFG, $PAGE, $OUTPUT;
  1362. $blockid = optional_param('bui_deleteid', null, PARAM_INT);
  1363. $confirmdelete = optional_param('bui_confirm', null, PARAM_INT);
  1364. if (!$blockid) {
  1365. return false;
  1366. }
  1367. $block = $this->page->blocks->find_instance($blockid);
  1368. if (!$this->user_can_delete_block($block)) {
  1369. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
  1370. }
  1371. if (!$confirmdelete) {
  1372. $deletepage = new moodle_page();
  1373. $deletepage->set_pagelayout('admin');
  1374. $deletepage->blocks->show_only_fake_blocks(true);
  1375. $deletepage->set_course($this->page->course);
  1376. $deletepage->set_context($this->page->context);
  1377. if ($this->page->cm) {
  1378. $deletepage->set_cm($this->page->cm);
  1379. }
  1380. $deleteurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
  1381. $deleteurlparams = $this->page->url->params();
  1382. $deletepage->set_url($deleteurlbase, $deleteurlparams);
  1383. $deletepage->set_block_actions_done();
  1384. $deletepage->set_secondarynav($this->get_secondarynav($block));
  1385. // At this point we are either going to redirect, or display the form, so
  1386. // overwrite global $PAGE ready for this. (Formslib refers to it.)
  1387. $PAGE = $deletepage;
  1388. //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that too
  1389. $output = $deletepage->get_renderer('core');
  1390. $OUTPUT = $output;
  1391. $site = get_site();
  1392. $blocktitle = $block->get_title();
  1393. $strdeletecheck = get_string('deletecheck', 'block', $blocktitle);
  1394. $message = get_string('deleteblockcheck', 'block', $blocktitle);
  1395. // If the block is being shown in sub contexts display a warning.
  1396. if ($block->instance->showinsubcontexts == 1) {
  1397. $parentcontext = context::instance_by_id($block->instance->parentcontextid);
  1398. $systemcontext = context_system::instance();
  1399. $messagestring = new stdClass();
  1400. $messagestring->location = $parentcontext->get_context_name();
  1401. // Checking for blocks that may have visibility on the front page and pages added on that.
  1402. if ($parentcontext->id != $systemcontext->id && is_inside_frontpage($parentcontext)) {
  1403. $messagestring->pagetype = get_string('showonfrontpageandsubs', 'block');
  1404. } else {
  1405. $pagetypes = generate_page_type_patterns($this->page->pagetype, $parentcontext);
  1406. $messagestring->pagetype = $block->instance->pagetypepattern;
  1407. if (isset($pagetypes[$block->instance->pagetypepattern])) {
  1408. $messagestring->pagetype = $pagetypes[$block->instance->pagetypepattern];
  1409. }
  1410. }
  1411. $message = get_string('deleteblockwarning', 'block', $messagestring);
  1412. }
  1413. $PAGE->navbar->add($strdeletecheck);
  1414. $PAGE->set_title($blocktitle . ': ' . $strdeletecheck);
  1415. $PAGE->set_heading($site->fullname);
  1416. echo $OUTPUT->header();
  1417. $confirmurl = new moodle_url($deletepage->url, array('sesskey' => sesskey(), 'bui_deleteid' => $block->instance->id, 'bui_confirm' => 1));
  1418. $cancelurl = new moodle_url($deletepage->url);
  1419. $yesbutton = new single_button($confirmurl, get_string('yes'));
  1420. $nobutton = new single_button($cancelurl, get_string('no'));
  1421. echo $OUTPUT->confirm($message, $yesbutton, $nobutton);
  1422. echo $OUTPUT->footer();
  1423. // Make sure that nothing else happens after we have displayed this form.
  1424. exit;
  1425. } else {
  1426. require_sesskey();
  1427. blocks_delete_instance($block->instance);
  1428. // bui_deleteid and bui_confirm should not be in the PAGE url.
  1429. $this->page->ensure_param_not_in_url('bui_deleteid');
  1430. $this->page->ensure_param_not_in_url('bui_confirm');
  1431. return true;
  1432. }
  1433. }
  1434. /**
  1435. * Handle showing or hiding a block.
  1436. * @return boolean true if anything was done. False if not.
  1437. */
  1438. public function process_url_show_hide() {
  1439. if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) {
  1440. $newvisibility = 0;
  1441. } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) {
  1442. $newvisibility = 1;
  1443. } else {
  1444. return false;
  1445. }
  1446. require_sesskey();
  1447. $block = $this->page->blocks->find_instance($blockid);
  1448. if (!$this->page->user_can_edit_blocks()) {
  1449. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
  1450. } else if (!$block->instance_can_be_hidden()) {
  1451. return false;
  1452. }
  1453. blocks_set_visibility($block->instance, $this->page, $newvisibility);
  1454. // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
  1455. $this->page->ensure_param_not_in_url('bui_hideid');
  1456. $this->page->ensure_param_not_in_url('bui_showid');
  1457. return true;
  1458. }
  1459. /**
  1460. * Convenience function to check whether a block is implementing a secondary nav class and return it
  1461. * initialised to the calling function
  1462. *
  1463. * @param block_base $block
  1464. * @return \core\navigation\views\secondary
  1465. */
  1466. protected function get_secondarynav(block_base $block): \core\navigation\views\secondary {
  1467. $class = "core_block\\local\\views\\secondary";
  1468. if (class_exists("block_{$block->name()}\\local\\views\\secondary")) {
  1469. $class = "block_{$block->name()}\\local\\views\\secondary";
  1470. }
  1471. $secondarynav = new $class($this->page);
  1472. $secondarynav->initialise();
  1473. return $secondarynav;
  1474. }
  1475. /**
  1476. * Handle showing/processing the submission from the block editing form.
  1477. * @return boolean true if the form was submitted and the new config saved. Does not
  1478. * return if the editing form was displayed. False otherwise.
  1479. */
  1480. public function process_url_edit() {
  1481. global $CFG, $DB, $PAGE, $OUTPUT;
  1482. $blockid = optional_param('bui_editid', null, PARAM_INT);
  1483. if (!$blockid) {
  1484. return false;
  1485. }
  1486. require_once($CFG->dirroot . '/blocks/edit_form.php');
  1487. $block = $this->find_instance($blockid);
  1488. if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
  1489. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
  1490. }
  1491. $editpage = new moodle_page();
  1492. $editpage->set_pagelayout('admin');
  1493. $editpage->blocks->show_only_fake_blocks(true);
  1494. $editpage->set_course($this->page->course);
  1495. //$editpage->set_context($block->context);
  1496. $editpage->set_context($this->page->context);
  1497. $editpage->set_secondarynav($this->get_secondarynav($block));
  1498. if ($this->page->cm) {
  1499. $editpage->set_cm($this->page->cm);
  1500. }
  1501. $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
  1502. $editurlparams = $this->page->url->params();
  1503. $editurlparams['bui_editid'] = $blockid;
  1504. $editpage->set_url($editurlbase, $editurlparams);
  1505. $editpage->set_block_actions_done();
  1506. // At this point we are either going to redirect, or display the form, so
  1507. // overwrite global $PAGE ready for this. (Formslib refers to it.)
  1508. $PAGE = $editpage;
  1509. //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
  1510. $output = $editpage->get_renderer('core');
  1511. $OUTPUT = $output;
  1512. $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
  1513. if (is_readable($formfile)) {
  1514. require_once($formfile);
  1515. $classname = 'block_' . $block->name() . '_edit_form';
  1516. if (!class_exists($classname)) {
  1517. $classname = 'block_edit_form';
  1518. }
  1519. } else {
  1520. $classname = 'block_edit_form';
  1521. }
  1522. $mform = new $classname($editpage->url, $block, $this->page);
  1523. $mform->set_data($block->instance);
  1524. if ($mform->is_cancelled()) {
  1525. redirect($this->page->url);
  1526. } else if ($data = $mform->get_data()) {
  1527. $bi = new stdClass;
  1528. $bi->id = $block->instance->id;
  1529. // This may get overwritten by the special case handling below.
  1530. $bi->pagetypepattern = $data->bui_pagetypepattern;
  1531. $bi->showinsubcontexts = (bool) $data->bui_contexts;
  1532. if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
  1533. $bi->subpagepattern = null;
  1534. } else {
  1535. $bi->subpagepattern = $data->bui_subpagepattern;
  1536. }
  1537. $systemcontext = context_system::instance();
  1538. $frontpagecontext = context_course::instance(SITEID);
  1539. $parentcontext = context::instance_by_id($data->bui_parentcontextid);
  1540. // Updating stickiness and contexts. See MDL-21375 for details.
  1541. if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
  1542. // Explicitly set the default context
  1543. $bi->parentcontextid = $parentcontext->id;
  1544. if ($data->bui_editingatfrontpage) { // The block is being edited on the front page
  1545. // The interface here is a special case because the pagetype pattern is
  1546. // totally derived from the context menu. Here are the excpetions. MDL-30340
  1547. switch ($data->bui_contexts) {
  1548. case BUI_CONTEXTS_ENTIRE_SITE:
  1549. // The user wants to show the block across the entire site
  1550. $bi->parentcontextid = $systemcontext->id;
  1551. $bi->showinsubcontexts = true;
  1552. $bi->pagetypepattern = '*';
  1553. break;
  1554. case BUI_CONTEXTS_FRONTPAGE_SUBS:
  1555. // The user wants the block shown on the front page and all subcontexts
  1556. $bi->parentcontextid = $frontpagecontext->id;
  1557. $bi->showinsubcontexts = true;
  1558. $bi->pagetypepattern = '*';
  1559. break;
  1560. case BUI_CONTEXTS_FRONTPAGE_ONLY:
  1561. // The user want to show the front page on the frontpage only
  1562. $bi->parentcontextid = $frontpagecontext->id;
  1563. $bi->showinsubcontexts = false;
  1564. $bi->pagetypepattern = 'site-index';
  1565. // This is the only relevant page type anyway but we'll set it explicitly just
  1566. // in case the front page grows site-index-* subpages of its own later
  1567. break;
  1568. }
  1569. }
  1570. }
  1571. $bits = explode('-', $bi->pagetypepattern);
  1572. // hacks for some contexts
  1573. if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
  1574. // For course context
  1575. // is page type pattern is mod-*, change showinsubcontext to 1
  1576. if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
  1577. $bi->showinsubcontexts = 1;
  1578. } else {
  1579. $bi->showinsubcontexts = 0;
  1580. }
  1581. } else if ($parentcontext->contextlevel == CONTEXT_USER) {
  1582. // for user context
  1583. // subpagepattern should be null
  1584. if ($bits[0] == 'user' or $bits[0] == 'my') {
  1585. // we don't need subpagepattern in usercontext
  1586. $bi->subpagepattern = null;
  1587. }
  1588. }
  1589. $bi->defaultregion = $data->bui_defaultregion;
  1590. $bi->defaultweight = $data->bui_defaultweight;
  1591. $bi->timemodified = time();
  1592. $DB->update_record('block_instances', $bi);
  1593. if (!empty($block->config)) {
  1594. $config = clone($block->config);
  1595. } else {
  1596. $config = new stdClass;
  1597. }
  1598. foreach ($data as $configfield => $value) {
  1599. if (strpos($configfield, 'config_') !== 0) {
  1600. continue;
  1601. }
  1602. $field = substr($configfield, 7);
  1603. $config->$field = $value;
  1604. }
  1605. $block->instance_config_save($config);
  1606. $bp = new stdClass;
  1607. $bp->visible = $data->bui_visible;
  1608. $bp->region = $data->bui_region;
  1609. $bp->weight = $data->bui_weight;
  1610. $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
  1611. $data->bui_weight != $data->bui_defaultweight;
  1612. if ($block->instance->blockpositionid && !$needbprecord) {
  1613. $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));
  1614. } else if ($block->instance->blockpositionid && $needbprecord) {
  1615. $bp->id = $block->instance->blockpositionid;
  1616. $DB->update_record('block_positions', $bp);
  1617. } else if ($needbprecord) {
  1618. $bp->blockinstanceid = $block->instance->id;
  1619. $bp->contextid = $this->page->context->id;
  1620. $bp->pagetype = $this->page->pagetype;
  1621. if ($this->page->subpage) {
  1622. $bp->subpage = $this->page->subpage;
  1623. } else {
  1624. $bp->subpage = '';
  1625. }
  1626. $DB->insert_record('block_positions', $bp);
  1627. }
  1628. redirect($this->page->url);
  1629. } else {
  1630. $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
  1631. $editpage->set_title($strheading);
  1632. $editpage->set_heading($strheading);
  1633. $bits = explode('-', $this->page->pagetype);
  1634. if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
  1635. // better navbar for tag pages
  1636. $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
  1637. $tag = core_tag_tag::get($this->page->subpage);
  1638. // tag search page doesn't have subpageid
  1639. if ($tag) {
  1640. $editpage->navbar->add($tag->get_display_name(), $tag->get_view_url());
  1641. }
  1642. }
  1643. $editpage->navbar->add($block->get_title());
  1644. $editpage->navbar->add(get_string('configuration'));
  1645. echo $output->header();
  1646. echo $output->heading($strheading, 2);
  1647. $mform->display();
  1648. echo $output->footer();
  1649. exit;
  1650. }
  1651. }
  1652. /**
  1653. * Handle showing/processing the submission from the block editing form.
  1654. * @return boolean true if the form was submitted and the new config saved. Does not
  1655. * return if the editing form was displayed. False otherwise.
  1656. */
  1657. public function process_url_move() {
  1658. global $CFG, $DB, $PAGE;
  1659. $blockid = optional_param('bui_moveid', null, PARAM_INT);
  1660. if (!$blockid) {
  1661. return false;
  1662. }
  1663. require_sesskey();
  1664. $block = $this->find_instance($blockid);
  1665. if (!$this->page->user_can_edit_blocks()) {
  1666. throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
  1667. }
  1668. $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
  1669. $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
  1670. if (!$newregion || is_null($newweight)) {
  1671. // Don't have a valid target position yet, must be just starting the move.
  1672. $this->movingblock = $blockid;
  1673. $this->page->ensure_param_not_in_url('bui_moveid');
  1674. return false;
  1675. }
  1676. if (!$this->is_known_region($newregion)) {
  1677. throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
  1678. }
  1679. // Move this block. This may involve moving other nearby blocks.
  1680. $blocks = $this->birecordsbyregion[$newregion];
  1681. $maxweight = self::MAX_WEIGHT;
  1682. $minweight = -self::MAX_WEIGHT;
  1683. // Initialise the used weights and spareweights array with the default values
  1684. $spareweights = array();
  1685. $usedweights = array();
  1686. for ($i = $minweight; $i <= $maxweight; $i++) {
  1687. $spareweights[$i] = $i;
  1688. $usedweights[$i] = array();
  1689. }
  1690. // Check each block and sort out where we have used weights
  1691. foreach ($blocks as $bi) {
  1692. if ($bi->weight > $maxweight) {
  1693. // If this statement is true then the blocks weight is more than the
  1694. // current maximum. To ensure that we can get the best block position
  1695. // we will initialise elements within the usedweights and spareweights
  1696. // arrays between the blocks weight (which will then be the new max) and
  1697. // the current max
  1698. $parseweight = $bi->weight;
  1699. while (!array_key_exists($parseweight, $usedweights)) {
  1700. $usedweights[$parseweight] = array();
  1701. $spareweights[$parseweight] = $parseweight;
  1702. $parseweight--;
  1703. }
  1704. $maxweight = $bi->weight;
  1705. } else if ($bi->weight < $minweight) {
  1706. // As above except this time the blocks weight is LESS than the
  1707. // the current minimum, so we will initialise the array from the
  1708. // blocks weight (new minimum) to the current minimum
  1709. $parseweight = $bi->weight;
  1710. while (!array_key_exists($parseweight, $usedweights)) {
  1711. $usedweights[$parseweight] = array();
  1712. $spareweights[$parseweight] = $parseweight;
  1713. $parseweight++;
  1714. }
  1715. $minweight = $bi->weight;
  1716. }
  1717. if ($bi->id != $block->instance->id) {
  1718. unset($spareweights[$bi->weight]);
  1719. $usedweights[$bi->weight][] = $bi->id;
  1720. }
  1721. }
  1722. // First we find the nearest gap in the list of weights.
  1723. $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
  1724. $bestgap = null;
  1725. foreach ($spareweights as $spareweight) {
  1726. if (abs($newweight - $spareweight) < $bestdistance) {
  1727. $bestdistance = abs($newweight - $spareweight);
  1728. $bestgap = $spareweight;
  1729. }
  1730. }
  1731. // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
  1732. if (is_null($bestgap)) {
  1733. $bestgap = self::MAX_WEIGHT + 1;
  1734. while (!empty($usedweights[$bestgap])) {
  1735. $bestgap++;
  1736. }
  1737. }
  1738. // Now we know the gap we are aiming for, so move all the blocks along.
  1739. if ($bestgap < $newweight) {
  1740. $newweight = floor($newweight);
  1741. for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
  1742. if (array_key_exists($weight, $usedweights)) {
  1743. foreach ($usedweights[$weight] as $biid) {
  1744. $this->reposition_block($biid, $newregion, $weight - 1);
  1745. }
  1746. }
  1747. }
  1748. $this->reposition_block($block->instance->id, $newregion, $newweight);
  1749. } else {
  1750. $newweight = ceil($newweight);
  1751. for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
  1752. if (array_key_exists($weight, $usedweights)) {
  1753. foreach ($usedweights[$weight] as $biid) {
  1754. $this->reposition_block($biid, $newregion, $weight + 1);
  1755. }
  1756. }
  1757. }
  1758. $this->reposition_block($block->instance->id, $newregion, $newweight);
  1759. }
  1760. $this->page->ensure_param_not_in_url('bui_moveid');
  1761. $this->page->ensure_param_not_in_url('bui_newregion');
  1762. $this->page->ensure_param_not_in_url('bui_newweight');
  1763. return true;
  1764. }
  1765. /**
  1766. * Turns the display of normal blocks either on or off.
  1767. *
  1768. * @param bool $setting
  1769. */
  1770. public function show_only_fake_blocks($setting = true) {
  1771. $this->fakeblocksonly = $setting;
  1772. }
  1773. }
  1774. /// Helper functions for working with block classes ============================
  1775. /**
  1776. * Call a class method (one that does not require a block instance) on a block class.
  1777. *
  1778. * @param string $blockname the name of the block.
  1779. * @param string $method the method name.
  1780. * @param array $param parameters to pass to the method.
  1781. * @return mixed whatever the method returns.
  1782. */
  1783. function block_method_result($blockname, $method, $param = NULL) {
  1784. if(!block_load_class($blockname)) {
  1785. return NULL;
  1786. }
  1787. return call_user_func(array('block_'.$blockname, $method), $param);
  1788. }
  1789. /**
  1790. * Returns a new instance of the specified block instance id.
  1791. *
  1792. * @param int $blockinstanceid
  1793. * @return block_base the requested block instance.
  1794. */
  1795. function block_instance_by_id($blockinstanceid) {
  1796. global $DB;
  1797. $blockinstance = $DB->get_record('block_instances', ['id' => $blockinstanceid]);
  1798. $instance = block_instance($blockinstance->blockname, $blockinstance);
  1799. return $instance;
  1800. }
  1801. /**
  1802. * Creates a new instance of the specified block class.
  1803. *
  1804. * @param string $blockname the name of the block.
  1805. * @param $instance block_instances DB table row (optional).
  1806. * @param moodle_page $page the page this block is appearing on.
  1807. * @return block_base the requested block instance.
  1808. */
  1809. function block_instance($blockname, $instance = NULL, $page = NULL) {
  1810. if(!block_load_class($blockname)) {
  1811. return false;
  1812. }
  1813. $classname = 'block_'.$blockname;
  1814. $retval = new $classname;
  1815. if($instance !== NULL) {
  1816. if (is_null($page)) {
  1817. global $PAGE;
  1818. $page = $PAGE;
  1819. }
  1820. $retval->_load_instance($instance, $page);
  1821. }
  1822. return $retval;
  1823. }
  1824. /**
  1825. * Load the block class for a particular type of block.
  1826. *
  1827. * @param string $blockname the name of the block.
  1828. * @return boolean success or failure.
  1829. */
  1830. function block_load_class($blockname) {
  1831. global $CFG;
  1832. if(empty($blockname)) {
  1833. return false;
  1834. }
  1835. $classname = 'block_'.$blockname;
  1836. if(class_exists($classname)) {
  1837. return true;
  1838. }
  1839. $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';
  1840. if (file_exists($blockpath)) {
  1841. require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
  1842. include_once($blockpath);
  1843. }else{
  1844. //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
  1845. return false;
  1846. }
  1847. return class_exists($classname);
  1848. }
  1849. /**
  1850. * Given a specific page type, return all the page type patterns that might
  1851. * match it.
  1852. *
  1853. * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
  1854. * @return array an array of all the page type patterns that might match this page type.
  1855. */
  1856. function matching_page_type_patterns($pagetype) {
  1857. $patterns = array($pagetype);
  1858. $bits = explode('-', $pagetype);
  1859. if (count($bits) == 3 && $bits[0] == 'mod') {
  1860. if ($bits[2] == 'view') {
  1861. $patterns[] = 'mod-*-view';
  1862. } else if ($bits[2] == 'index') {
  1863. $patterns[] = 'mod-*-index';
  1864. }
  1865. }
  1866. while (count($bits) > 0) {
  1867. $patterns[] = implode('-', $bits) . '-*';
  1868. array_pop($bits);
  1869. }
  1870. $patterns[] = '*';
  1871. return $patterns;
  1872. }
  1873. /**
  1874. * Give an specific pattern, return all the page type patterns that would also match it.
  1875. *
  1876. * @param string $pattern the pattern, e.g. 'mod-forum-*' or 'mod-quiz-view'.
  1877. * @return array of all the page type patterns matching.
  1878. */
  1879. function matching_page_type_patterns_from_pattern($pattern) {
  1880. $patterns = array($pattern);
  1881. if ($pattern === '*') {
  1882. return $patterns;
  1883. }
  1884. // Only keep the part before the star because we will append -* to all the bits.
  1885. $star = strpos($pattern, '-*');
  1886. if ($star !== false) {
  1887. $pattern = substr($pattern, 0, $star);
  1888. }
  1889. $patterns = array_merge($patterns, matching_page_type_patterns($pattern));
  1890. $patterns = array_unique($patterns);
  1891. return $patterns;
  1892. }
  1893. /**
  1894. * Given a specific page type, parent context and currect context, return all the page type patterns
  1895. * that might be used by this block.
  1896. *
  1897. * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
  1898. * @param stdClass $parentcontext Block's parent context
  1899. * @param stdClass $currentcontext Current context of block
  1900. * @return array an array of all the page type patterns that might match this page type.
  1901. */
  1902. function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
  1903. global $CFG; // Required for includes bellow.
  1904. $bits = explode('-', $pagetype);
  1905. $core = core_component::get_core_subsystems();
  1906. $plugins = core_component::get_plugin_types();
  1907. //progressively strip pieces off the page type looking for a match
  1908. $componentarray = null;
  1909. for ($i = count($bits); $i > 0; $i--) {
  1910. $possiblecomponentarray = array_slice($bits, 0, $i);
  1911. $possiblecomponent = implode('', $possiblecomponentarray);
  1912. // Check to see if the component is a core component
  1913. if (array_key_exists($possiblecomponent, $core) && !empty($core[$possiblecomponent])) {
  1914. $libfile = $core[$possiblecomponent].'/lib.php';
  1915. if (file_exists($libfile)) {
  1916. require_once($libfile);
  1917. $function = $possiblecomponent.'_page_type_list';
  1918. if (function_exists($function)) {
  1919. if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
  1920. break;
  1921. }
  1922. }
  1923. }
  1924. }
  1925. //check the plugin directory and look for a callback
  1926. if (array_key_exists($possiblecomponent, $plugins) && !empty($plugins[$possiblecomponent])) {
  1927. //We've found a plugin type. Look for a plugin name by getting the next section of page type
  1928. if (count($bits) > $i) {
  1929. $pluginname = $bits[$i];
  1930. $directory = core_component::get_plugin_directory($possiblecomponent, $pluginname);
  1931. if (!empty($directory)){
  1932. $libfile = $directory.'/lib.php';
  1933. if (file_exists($libfile)) {
  1934. require_once($libfile);
  1935. $function = $possiblecomponent.'_'.$pluginname.'_page_type_list';
  1936. if (!function_exists($function)) {
  1937. $function = $pluginname.'_page_type_list';
  1938. }
  1939. if (function_exists($function)) {
  1940. if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
  1941. break;
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. //we'll only get to here if we still don't have any patterns
  1948. //the plugin type may have a callback
  1949. $directory = $plugins[$possiblecomponent];
  1950. $libfile = $directory.'/lib.php';
  1951. if (file_exists($libfile)) {
  1952. require_once($libfile);
  1953. $function = $possiblecomponent.'_page_type_list';
  1954. if (function_exists($function)) {
  1955. if ($patterns = $function($pagetype, $parentcontext, $currentcontext)) {
  1956. break;
  1957. }
  1958. }
  1959. }
  1960. }
  1961. }
  1962. if (empty($patterns)) {
  1963. $patterns = default_page_type_list($pagetype, $parentcontext, $currentcontext);
  1964. }
  1965. // Ensure that the * pattern is always available if editing block 'at distance', so
  1966. // we always can 'bring back' it to the original context. MDL-30340
  1967. if ((!isset($currentcontext) or !isset($parentcontext) or $currentcontext->id != $parentcontext->id) && !isset($patterns['*'])) {
  1968. // TODO: We could change the string here, showing its 'bring back' meaning
  1969. $patterns['*'] = get_string('page-x', 'pagetype');
  1970. }
  1971. return $patterns;
  1972. }
  1973. /**
  1974. * Generates a default page type list when a more appropriate callback cannot be decided upon.
  1975. *
  1976. * @param string $pagetype
  1977. * @param stdClass $parentcontext
  1978. * @param stdClass $currentcontext
  1979. * @return array
  1980. */
  1981. function default_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
  1982. // Generate page type patterns based on current page type if
  1983. // callbacks haven't been defined
  1984. $patterns = array($pagetype => $pagetype);
  1985. $bits = explode('-', $pagetype);
  1986. while (count($bits) > 0) {
  1987. $pattern = implode('-', $bits) . '-*';
  1988. $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
  1989. // guessing page type description
  1990. if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
  1991. $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
  1992. } else {
  1993. $patterns[$pattern] = $pattern;
  1994. }
  1995. array_pop($bits);
  1996. }
  1997. $patterns['*'] = get_string('page-x', 'pagetype');
  1998. return $patterns;
  1999. }
  2000. /**
  2001. * Generates the page type list for the my moodle page
  2002. *
  2003. * @param string $pagetype
  2004. * @param stdClass $parentcontext
  2005. * @param stdClass $currentcontext
  2006. * @return array
  2007. */
  2008. function my_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
  2009. return array('my-index' => get_string('page-my-index', 'pagetype'));
  2010. }
  2011. /**
  2012. * Generates the page type list for a module by either locating and using the modules callback
  2013. * or by generating a default list.
  2014. *
  2015. * @param string $pagetype
  2016. * @param stdClass $parentcontext
  2017. * @param stdClass $currentcontext
  2018. * @return array
  2019. */
  2020. function mod_page_type_list($pagetype, $parentcontext = null, $currentcontext = null) {
  2021. $patterns = plugin_page_type_list($pagetype, $parentcontext, $currentcontext);
  2022. if (empty($patterns)) {
  2023. // if modules don't have callbacks
  2024. // generate two default page type patterns for modules only
  2025. $bits = explode('-', $pagetype);
  2026. $patterns = array($pagetype => $pagetype);
  2027. if ($bits[2] == 'view') {
  2028. $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
  2029. } else if ($bits[2] == 'index') {
  2030. $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
  2031. }
  2032. }
  2033. return $patterns;
  2034. }
  2035. /// Functions update the blocks if required by the request parameters ==========
  2036. /**
  2037. * Return a {@link block_contents} representing the add a new block UI, if
  2038. * this user is allowed to see it.
  2039. *
  2040. * @return block_contents an appropriate block_contents, or null if the user
  2041. * cannot add any blocks here.
  2042. */
  2043. function block_add_block_ui($page, $output) {
  2044. global $CFG, $OUTPUT;
  2045. if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
  2046. return null;
  2047. }
  2048. $bc = new block_contents();
  2049. $bc->title = get_string('addblock');
  2050. $bc->add_class('block_adminblock');
  2051. $bc->attributes['data-block'] = 'adminblock';
  2052. $missingblocks = $page->blocks->get_addable_blocks();
  2053. if (empty($missingblocks)) {
  2054. $bc->content = get_string('noblockstoaddhere');
  2055. return $bc;
  2056. }
  2057. $menu = array();
  2058. foreach ($missingblocks as $block) {
  2059. $menu[$block->name] = $block->title;
  2060. }
  2061. $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
  2062. $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
  2063. $select->set_label(get_string('addblock'), array('class'=>'accesshide'));
  2064. $bc->content = $OUTPUT->render($select);
  2065. return $bc;
  2066. }
  2067. /**
  2068. * Actually delete from the database any blocks that are currently on this page,
  2069. * but which should not be there according to blocks_name_allowed_in_format.
  2070. *
  2071. * @todo Write/Fix this function. Currently returns immediately
  2072. * @param $course
  2073. */
  2074. function blocks_remove_inappropriate($course) {
  2075. // TODO
  2076. return;
  2077. /*
  2078. $blockmanager = blocks_get_by_page($page);
  2079. if (empty($blockmanager)) {
  2080. return;
  2081. }
  2082. if (($pageformat = $page->pagetype) == NULL) {
  2083. return;
  2084. }
  2085. foreach($blockmanager as $region) {
  2086. foreach($region as $instance) {
  2087. $block = blocks_get_record($instance->blockid);
  2088. if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
  2089. blocks_delete_instance($instance->instance);
  2090. }
  2091. }
  2092. }*/
  2093. }
  2094. /**
  2095. * Check that a given name is in a permittable format
  2096. *
  2097. * @param string $name
  2098. * @param string $pageformat
  2099. * @return bool
  2100. */
  2101. function blocks_name_allowed_in_format($name, $pageformat) {
  2102. $accept = NULL;
  2103. $maxdepth = -1;
  2104. if (!$bi = block_instance($name)) {
  2105. return false;
  2106. }
  2107. $formats = $bi->applicable_formats();
  2108. if (!$formats) {
  2109. $formats = array();
  2110. }
  2111. foreach ($formats as $format => $allowed) {
  2112. $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
  2113. $depth = substr_count($format, '-');
  2114. if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
  2115. $maxdepth = $depth;
  2116. $accept = $allowed;
  2117. }
  2118. }
  2119. if ($accept === NULL) {
  2120. $accept = !empty($formats['all']);
  2121. }
  2122. return $accept;
  2123. }
  2124. /**
  2125. * Delete a block, and associated data.
  2126. *
  2127. * @param object $instance a row from the block_instances table
  2128. * @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
  2129. * @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
  2130. */
  2131. function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
  2132. global $DB;
  2133. // Allow plugins to use this block before we completely delete it.
  2134. if ($pluginsfunction = get_plugins_with_function('pre_block_delete')) {
  2135. foreach ($pluginsfunction as $plugintype => $plugins) {
  2136. foreach ($plugins as $pluginfunction) {
  2137. $pluginfunction($instance);
  2138. }
  2139. }
  2140. }
  2141. if ($block = block_instance($instance->blockname, $instance)) {
  2142. $block->instance_delete();
  2143. }
  2144. context_helper::delete_instance(CONTEXT_BLOCK, $instance->id);
  2145. if (!$skipblockstables) {
  2146. $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
  2147. $DB->delete_records('block_instances', array('id' => $instance->id));
  2148. $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
  2149. }
  2150. }
  2151. /**
  2152. * Delete multiple blocks at once.
  2153. *
  2154. * @param array $instanceids A list of block instance ID.
  2155. */
  2156. function blocks_delete_instances($instanceids) {
  2157. global $DB;
  2158. $limit = 1000;
  2159. $count = count($instanceids);
  2160. $chunks = [$instanceids];
  2161. if ($count > $limit) {
  2162. $chunks = array_chunk($instanceids, $limit);
  2163. }
  2164. // Perform deletion for each chunk.
  2165. foreach ($chunks as $chunk) {
  2166. $instances = $DB->get_recordset_list('block_instances', 'id', $chunk);
  2167. foreach ($instances as $instance) {
  2168. blocks_delete_instance($instance, false, true);
  2169. }
  2170. $instances->close();
  2171. $DB->delete_records_list('block_positions', 'blockinstanceid', $chunk);
  2172. $DB->delete_records_list('block_instances', 'id', $chunk);
  2173. $preferences = array();
  2174. foreach ($chunk as $instanceid) {
  2175. $preferences[] = 'block' . $instanceid . 'hidden';
  2176. $preferences[] = 'docked_block_instance_' . $instanceid;
  2177. }
  2178. $DB->delete_records_list('user_preferences', 'name', $preferences);
  2179. }
  2180. }
  2181. /**
  2182. * Delete all the blocks that belong to a particular context.
  2183. *
  2184. * @param int $contextid the context id.
  2185. */
  2186. function blocks_delete_all_for_context($contextid) {
  2187. global $DB;
  2188. $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
  2189. foreach ($instances as $instance) {
  2190. blocks_delete_instance($instance, true);
  2191. }
  2192. $instances->close();
  2193. $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
  2194. $DB->delete_records('block_positions', array('contextid' => $contextid));
  2195. }
  2196. /**
  2197. * Set a block to be visible or hidden on a particular page.
  2198. *
  2199. * @param object $instance a row from the block_instances, preferably LEFT JOINed with the
  2200. * block_positions table as return by block_manager.
  2201. * @param moodle_page $page the back to set the visibility with respect to.
  2202. * @param integer $newvisibility 1 for visible, 0 for hidden.
  2203. */
  2204. function blocks_set_visibility($instance, $page, $newvisibility) {
  2205. global $DB;
  2206. if (!empty($instance->blockpositionid)) {
  2207. // Already have local information on this page.
  2208. $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
  2209. return;
  2210. }
  2211. // Create a new block_positions record.
  2212. $bp = new stdClass;
  2213. $bp->blockinstanceid = $instance->id;
  2214. $bp->contextid = $page->context->id;
  2215. $bp->pagetype = $page->pagetype;
  2216. if ($page->subpage) {
  2217. $bp->subpage = $page->subpage;
  2218. }
  2219. $bp->visible = $newvisibility;
  2220. $bp->region = $instance->defaultregion;
  2221. $bp->weight = $instance->defaultweight;
  2222. $DB->insert_record('block_positions', $bp);
  2223. }
  2224. /**
  2225. * Get the block record for a particular blockid - that is, a particular type os block.
  2226. *
  2227. * @param $int blockid block type id. If null, an array of all block types is returned.
  2228. * @param bool $notusedanymore No longer used.
  2229. * @return array|object row from block table, or all rows.
  2230. */
  2231. function blocks_get_record($blockid = NULL, $notusedanymore = false) {
  2232. global $PAGE;
  2233. $blocks = $PAGE->blocks->get_installed_blocks();
  2234. if ($blockid === NULL) {
  2235. return $blocks;
  2236. } else if (isset($blocks[$blockid])) {
  2237. return $blocks[$blockid];
  2238. } else {
  2239. return false;
  2240. }
  2241. }
  2242. /**
  2243. * Find a given block by its blockid within a provide array
  2244. *
  2245. * @param int $blockid
  2246. * @param array $blocksarray
  2247. * @return bool|object Instance if found else false
  2248. */
  2249. function blocks_find_block($blockid, $blocksarray) {
  2250. if (empty($blocksarray)) {
  2251. return false;
  2252. }
  2253. foreach($blocksarray as $blockgroup) {
  2254. if (empty($blockgroup)) {
  2255. continue;
  2256. }
  2257. foreach($blockgroup as $instance) {
  2258. if($instance->blockid == $blockid) {
  2259. return $instance;
  2260. }
  2261. }
  2262. }
  2263. return false;
  2264. }
  2265. // Functions for programatically adding default blocks to pages ================
  2266. /**
  2267. * Parse a list of default blocks. See config-dist for a description of the format.
  2268. *
  2269. * @param string $blocksstr Determines the starting point that the blocks are added in the region.
  2270. * @return array the parsed list of default blocks
  2271. */
  2272. function blocks_parse_default_blocks_list($blocksstr) {
  2273. $blocks = array();
  2274. $bits = explode(':', $blocksstr);
  2275. if (!empty($bits)) {
  2276. $leftbits = trim(array_shift($bits));
  2277. if ($leftbits != '') {
  2278. $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
  2279. }
  2280. }
  2281. if (!empty($bits)) {
  2282. $rightbits = trim(array_shift($bits));
  2283. if ($rightbits != '') {
  2284. $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
  2285. }
  2286. }
  2287. return $blocks;
  2288. }
  2289. /**
  2290. * @return array the blocks that should be added to the site course by default.
  2291. */
  2292. function blocks_get_default_site_course_blocks() {
  2293. global $CFG;
  2294. if (isset($CFG->defaultblocks_site)) {
  2295. return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
  2296. } else {
  2297. return array(
  2298. BLOCK_POS_LEFT => array(),
  2299. BLOCK_POS_RIGHT => array()
  2300. );
  2301. }
  2302. }
  2303. /**
  2304. * Add the default blocks to a course.
  2305. *
  2306. * @param object $course a course object.
  2307. */
  2308. function blocks_add_default_course_blocks($course) {
  2309. global $CFG;
  2310. if (isset($CFG->defaultblocks_override)) {
  2311. $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);
  2312. } else if ($course->id == SITEID) {
  2313. $blocknames = blocks_get_default_site_course_blocks();
  2314. } else if (isset($CFG->{'defaultblocks_' . $course->format})) {
  2315. $blocknames = blocks_parse_default_blocks_list($CFG->{'defaultblocks_' . $course->format});
  2316. } else {
  2317. require_once($CFG->dirroot. '/course/lib.php');
  2318. $blocknames = course_get_format($course)->get_default_blocks();
  2319. }
  2320. if ($course->id == SITEID) {
  2321. $pagetypepattern = 'site-index';
  2322. } else {
  2323. $pagetypepattern = 'course-view-*';
  2324. }
  2325. $page = new moodle_page();
  2326. $page->set_course($course);
  2327. $page->blocks->add_blocks($blocknames, $pagetypepattern);
  2328. }
  2329. /**
  2330. * Add the default system-context blocks. E.g. the admin tree.
  2331. */
  2332. function blocks_add_default_system_blocks() {
  2333. global $DB;
  2334. $page = new moodle_page();
  2335. $page->set_context(context_system::instance());
  2336. // We don't add blocks required by the theme, they will be auto-created.
  2337. $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);
  2338. if ($defaultmypage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__default', 'private' => 1))) {
  2339. $subpagepattern = $defaultmypage->id;
  2340. } else {
  2341. $subpagepattern = null;
  2342. }
  2343. if ($defaultmycoursespage = $DB->get_record('my_pages', array('userid' => null, 'name' => '__courses', 'private' => 0))) {
  2344. $mycoursesubpagepattern = $defaultmycoursespage->id;
  2345. } else {
  2346. $mycoursesubpagepattern = null;
  2347. }
  2348. $page->blocks->add_blocks([
  2349. BLOCK_POS_RIGHT => [
  2350. 'private_files',
  2351. 'badges',
  2352. ],
  2353. 'content' => [
  2354. 'timeline',
  2355. 'calendar_month',
  2356. ]],
  2357. 'my-index',
  2358. $subpagepattern
  2359. );
  2360. $page->blocks->add_blocks([
  2361. 'content' => [
  2362. 'myoverview'
  2363. ]],
  2364. 'my-index',
  2365. $mycoursesubpagepattern
  2366. );
  2367. }