Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 0f63f2714f
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 2084 lines (1839 sloc) 77.073 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Block Class and Functions
*
* This file defines the {@link block_manager} class,
*
* @package core
* @subpackage block
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

defined('MOODLE_INTERNAL') || die();

/**#@+
* @deprecated since Moodle 2.0. No longer used.
*/
define('BLOCK_MOVE_LEFT', 0x01);
define('BLOCK_MOVE_RIGHT', 0x02);
define('BLOCK_MOVE_UP', 0x04);
define('BLOCK_MOVE_DOWN', 0x08);
define('BLOCK_CONFIGURE', 0x10);
/**#@-*/

/**#@+
* Default names for the block regions in the standard theme.
*/
define('BLOCK_POS_LEFT', 'side-pre');
define('BLOCK_POS_RIGHT', 'side-post');
/**#@-*/

/**#@+
* @deprecated since Moodle 2.0. No longer used.
*/
define('BLOCKS_PINNED_TRUE',0);
define('BLOCKS_PINNED_FALSE',1);
define('BLOCKS_PINNED_BOTH',2);
/**#@-*/

define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
define('BUI_CONTEXTS_ENTIRE_SITE', 2);

define('BUI_CONTEXTS_CURRENT', 0);
define('BUI_CONTEXTS_CURRENT_SUBS', 1);

/**
* Exception thrown when someone tried to do something with a block that does
* not exist on a page.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class block_not_on_page_exception extends moodle_exception {
    /**
* Constructor
* @param int $instanceid the block instance id of the block that was looked for.
* @param object $page the current page.
*/
    public function __construct($instanceid, $page) {
        $a = new stdClass;
        $a->instanceid = $instanceid;
        $a->url = $page->url->out();
        parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
    }
}

/**
* This class keeps track of the block that should appear on a moodle_page.
*
* The page to work with as passed to the constructor.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class block_manager {
    /**
* The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
* although other weights are valid.
*/
    const MAX_WEIGHT = 10;

/// Field declarations =========================================================

    /**
* the moodle_page we are managing blocks for.
* @var moodle_page
*/
    protected $page;

    /** @var array region name => 1.*/
    protected $regions = array();

    /** @var string the region where new blocks are added.*/
    protected $defaultregion = null;

    /** @var array will be $DB->get_records('blocks') */
    protected $allblocks = null;

    /**
* @var array blocks that this user can add to this page. Will be a subset
* of $allblocks, but with array keys block->name. Access this via the
* {@link get_addable_blocks()} method to ensure it is lazy-loaded.
*/
    protected $addableblocks = null;

    /**
* Will be an array region-name => array(db rows loaded in load_blocks);
* @var array
*/
    protected $birecordsbyregion = null;

    /**
* array region-name => array(block objects); populated as necessary by
* the ensure_instances_exist method.
* @var array
*/
    protected $blockinstances = array();

    /**
* array region-name => array(block_contents objects) what actually needs to
* be displayed in each region.
* @var array
*/
    protected $visibleblockcontent = array();

    /**
* array region-name => array(block_contents objects) extra block-like things
* to be displayed in each region, before the real blocks.
* @var array
*/
    protected $extracontent = array();

    /**
* Used by the block move id, to track whether a block is currently being moved.
*
* When you click on the move icon of a block, first the page needs to reload with
* extra UI for choosing a new position for a particular block. In that situation
* this field holds the id of the block being moved.
*
* @var integer|null
*/
    protected $movingblock = null;

    /**
* Show only fake blocks
*/
    protected $fakeblocksonly = false;

/// Constructor ================================================================

    /**
* Constructor.
* @param object $page the moodle_page object object we are managing the blocks for,
* or a reasonable faxilimily. (See the comment at the top of this class
* and {@link http://en.wikipedia.org/wiki/Duck_typing})
*/
    public function __construct($page) {
        $this->page = $page;
    }

/// Getter methods =============================================================

    /**
* Get an array of all region names on this page where a block may appear
*
* @return array the internal names of the regions on this page where block may appear.
*/
    public function get_regions() {
        if (is_null($this->defaultregion)) {
            $this->page->initialise_theme_and_output();
        }
        return array_keys($this->regions);
    }

    /**
* Get the region name of the region blocks are added to by default
*
* @return string the internal names of the region where new blocks are added
* by default, and where any blocks from an unrecognised region are shown.
* (Imagine that blocks were added with one theme selected, then you switched
* to a theme with different block positions.)
*/
    public function get_default_region() {
        $this->page->initialise_theme_and_output();
        return $this->defaultregion;
    }

    /**
* The list of block types that may be added to this page.
*
* @return array block name => record from block table.
*/
    public function get_addable_blocks() {
        $this->check_is_loaded();

        if (!is_null($this->addableblocks)) {
            return $this->addableblocks;
        }

        // Lazy load.
        $this->addableblocks = array();

        $allblocks = blocks_get_record();
        if (empty($allblocks)) {
            return $this->addableblocks;
        }

        $pageformat = $this->page->pagetype;
        foreach($allblocks as $block) {
            if ($block->visible &&
                    (block_method_result($block->name, 'instance_allow_multiple') || !$this->is_block_present($block->name)) &&
                    blocks_name_allowed_in_format($block->name, $pageformat) &&
                    block_method_result($block->name, 'user_can_addto', $this->page)) {
                $this->addableblocks[$block->name] = $block;
            }
        }

        return $this->addableblocks;
    }

    /**
* Given a block name, find out of any of them are currently present in the page

* @param string $blockname - the basic name of a block (eg "navigation")
* @return boolean - is there one of these blocks in the current page?
*/
    public function is_block_present($blockname) {
        if (empty($this->blockinstances)) {
            return false;
        }

        foreach ($this->blockinstances as $region) {
            foreach ($region as $instance) {
                if (empty($instance->instance->blockname)) {
                    continue;
                }
                if ($instance->instance->blockname == $blockname) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
* Find out if a block type is known by the system
*
* @param string $blockname the name of the type of block.
* @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
* @return boolean true if this block in installed.
*/
    public function is_known_block_type($blockname, $includeinvisible = false) {
        $blocks = $this->get_installed_blocks();
        foreach ($blocks as $block) {
            if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
                return true;
            }
        }
        return false;
    }

    /**
* Find out if a region exists on a page
*
* @param string $region a region name
* @return boolean true if this region exists on this page.
*/
    public function is_known_region($region) {
        return array_key_exists($region, $this->regions);
    }

    /**
* Get an array of all blocks within a given region
*
* @param string $region a block region that exists on this page.
* @return array of block instances.
*/
    public function get_blocks_for_region($region) {
        $this->check_is_loaded();
        $this->ensure_instances_exist($region);
        return $this->blockinstances[$region];
    }

    /**
* Returns an array of block content objects that exist in a region
*
* @param string $region a block region that exists on this page.
* @return array of block block_contents objects for all the blocks in a region.
*/
    public function get_content_for_region($region, $output) {
        $this->check_is_loaded();
        $this->ensure_content_created($region, $output);
        return $this->visibleblockcontent[$region];
    }

    /**
* Helper method used by get_content_for_region.
* @param string $region region name
* @param float $weight weight. May be fractional, since you may want to move a block
* between ones with weight 2 and 3, say ($weight would be 2.5).
* @return string URL for moving block $this->movingblock to this position.
*/
    protected function get_move_target_url($region, $weight) {
        return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
                'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
    }

    /**
* Determine whether a region contains anything. (Either any real blocks, or
* the add new block UI.)
*
* (You may wonder why the $output parameter is required. Unfortunately,
* because of the way that blocks work, the only reliable way to find out
* if a block will be visible is to get the content for output, and to
* get the content, you need a renderer. Fortunately, this is not a
* performance problem, because we cache the output that is generated, and
* in almost every case where we call region_has_content, we are about to
* output the blocks anyway, so we are not doing wasted effort.)
*
* @param string $region a block region that exists on this page.
* @param object $output a core_renderer. normally the global $OUTPUT.
* @return boolean Whether there is anything in this region.
*/
    public function region_has_content($region, $output) {

        if (!$this->is_known_region($region)) {
            return false;
        }
        $this->check_is_loaded();
        $this->ensure_content_created($region, $output);
        if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
            // If editing is on, we need all the block regions visible, for the
            // move blocks UI.
            return true;
        }
        return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
    }

    /**
* Get an array of all of the installed blocks.
*
* @return array contents of the block table.
*/
    public function get_installed_blocks() {
        global $DB;
        if (is_null($this->allblocks)) {
            $this->allblocks = $DB->get_records('block');
        }
        return $this->allblocks;
    }

/// Setter methods =============================================================

    /**
* Add a region to a page
*
* @param string $region add a named region where blocks may appear on the
* current page. This is an internal name, like 'side-pre', not a string to
* display in the UI.
*/
    public function add_region($region) {
        $this->check_not_yet_loaded();
        $this->regions[$region] = 1;
    }

    /**
* Add an array of regions
* @see add_region()
*
* @param array $regions this utility method calls add_region for each array element.
*/
    public function add_regions($regions) {
        foreach ($regions as $region) {
            $this->add_region($region);
        }
    }

    /**
* Set the default region for new blocks on the page
*
* @param string $defaultregion the internal names of the region where new
* blocks should be added by default, and where any blocks from an
* unrecognised region are shown.
*/
    public function set_default_region($defaultregion) {
        $this->check_not_yet_loaded();
        if ($defaultregion) {
            $this->check_region_is_known($defaultregion);
        }
        $this->defaultregion = $defaultregion;
    }

    /**
* Add something that looks like a block, but which isn't an actual block_instance,
* to this page.
*
* @param block_contents $bc the content of the block-like thing.
* @param string $region a block region that exists on this page.
*/
    public function add_fake_block($bc, $region) {
        $this->page->initialise_theme_and_output();
        if (!$this->is_known_region($region)) {
            $region = $this->get_default_region();
        }
        if (array_key_exists($region, $this->visibleblockcontent)) {
            throw new coding_exception('block_manager has already prepared the blocks in region ' .
                    $region . 'for output. It is too late to add a fake block.');
        }
        $this->extracontent[$region][] = $bc;
    }

    /**
* When the block_manager class was created, the {@link add_fake_block()}
* was called add_pretend_block, which is inconsisted with
* {@link show_only_fake_blocks()}. To fix this inconsistency, this method
* was renamed to add_fake_block. Please update your code.
* @param block_contents $bc the content of the block-like thing.
* @param string $region a block region that exists on this page.
*/
    public function add_pretend_block($bc, $region) {
        debugging(DEBUG_DEVELOPER, 'add_pretend_block has been renamed to add_fake_block. Please rename the method call in your code.');
        $this->add_fake_block($bc, $region);
    }

    /**
* Checks to see whether all of the blocks within the given region are docked
*
* @see region_uses_dock
* @param string $region
* @return bool True if all of the blocks within that region are docked
*/
    public function region_completely_docked($region, $output) {
        if (!$this->page->theme->enable_dock) {
            return false;
        }
        $this->check_is_loaded();
        $this->ensure_content_created($region, $output);
        foreach($this->visibleblockcontent[$region] as $instance) {
            if (!empty($instance->content) && !get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
                return false;
            }
        }
        return true;
    }

    /**
* Checks to see whether any of the blocks within the given regions are docked
*
* @see region_completely_docked
* @param array|string $regions array of regions (or single region)
* @return bool True if any of the blocks within that region are docked
*/
    public function region_uses_dock($regions, $output) {
        if (!$this->page->theme->enable_dock) {
            return false;
        }
        $this->check_is_loaded();
        foreach((array)$regions as $region) {
            $this->ensure_content_created($region, $output);
            foreach($this->visibleblockcontent[$region] as $instance) {
                if(!empty($instance->content) && get_user_preferences('docked_block_instance_'.$instance->blockinstanceid, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

/// Actions ====================================================================

    /**
* This method actually loads the blocks for our page from the database.
*
* @param boolean|null $includeinvisible
* null (default) - load hidden blocks if $this->page->user_is_editing();
* true - load hidden blocks.
* false - don't load hidden blocks.
*/
    public function load_blocks($includeinvisible = null) {
        global $DB, $CFG;

        if (!is_null($this->birecordsbyregion)) {
            // Already done.
            return;
        }

        if ($CFG->version < 2009050619) {
            // Upgrade/install not complete. Don't try too show any blocks.
            $this->birecordsbyregion = array();
            return;
        }

        // Ensure we have been initialised.
        if (is_null($this->defaultregion)) {
            $this->page->initialise_theme_and_output();
            // If there are still no block regions, then there are no blocks on this page.
            if (empty($this->regions)) {
                $this->birecordsbyregion = array();
                return;
            }
        }

        // Check if we need to load normal blocks
        if ($this->fakeblocksonly) {
            $this->birecordsbyregion = $this->prepare_per_region_arrays();
            return;
        }

        if (is_null($includeinvisible)) {
            $includeinvisible = $this->page->user_is_editing();
        }
        if ($includeinvisible) {
            $visiblecheck = '';
        } else {
            $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
        }

        $context = $this->page->context;
        $contexttest = 'bi.parentcontextid = :contextid2';
        $parentcontextparams = array();
        $parentcontextids = get_parent_contexts($context);
        if ($parentcontextids) {
            list($parentcontexttest, $parentcontextparams) =
                    $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
            $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
        }

        $pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
        list($pagetypepatterntest, $pagetypepatternparams) =
                $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');

        list($ccselect, $ccjoin) = context_instance_preload_sql('bi.id', CONTEXT_BLOCK, 'ctx');

        $params = array(
            'subpage1' => $this->page->subpage,
            'subpage2' => $this->page->subpage,
            'contextid1' => $context->id,
            'contextid2' => $context->id,
            'pagetype' => $this->page->pagetype,
        );
        $sql = "SELECT
bi.id,
bp.id AS blockpositionid,
bi.blockname,
bi.parentcontextid,
bi.showinsubcontexts,
bi.pagetypepattern,
bi.subpagepattern,
bi.defaultregion,
bi.defaultweight,
COALESCE(bp.visible, 1) AS visible,
COALESCE(bp.region, bi.defaultregion) AS region,
COALESCE(bp.weight, bi.defaultweight) AS weight,
bi.configdata
$ccselect

FROM {block_instances} bi
JOIN {block} b ON bi.blockname = b.name
LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
AND bp.contextid = :contextid1
AND bp.pagetype = :pagetype
AND bp.subpage = :subpage1
$ccjoin

WHERE
$contexttest
AND bi.pagetypepattern $pagetypepatterntest
AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
$visiblecheck
AND b.visible = 1

ORDER BY
COALESCE(bp.region, bi.defaultregion),
COALESCE(bp.weight, bi.defaultweight),
bi.id";
        $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);

        $this->birecordsbyregion = $this->prepare_per_region_arrays();
        $unknown = array();
        foreach ($blockinstances as $bi) {
            context_instance_preload($bi);
            if ($this->is_known_region($bi->region)) {
                $this->birecordsbyregion[$bi->region][] = $bi;
            } else {
                $unknown[] = $bi;
            }
        }

        // Pages don't necessarily have a defaultregion. The one time this can
        // happen is when there are no theme block regions, but the script itself
        // has a block region in the main content area.
        if (!empty($this->defaultregion)) {
            $this->birecordsbyregion[$this->defaultregion] =
                    array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
        }
    }

    /**
* Add a block to the current page, or related pages. The block is added to
* context $this->page->contextid. If $pagetypepattern $subpagepattern
*
* @param string $blockname The type of block to add.
* @param string $region the block region on this page to add the block to.
* @param integer $weight determines the order where this block appears in the region.
* @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
* @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
* @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
*/
    public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
        global $DB;
        // Allow invisible blocks because this is used when adding default page blocks, which
        // might include invisible ones if the user makes some default blocks invisible
        $this->check_known_block_type($blockname, true);
        $this->check_region_is_known($region);

        if (empty($pagetypepattern)) {
            $pagetypepattern = $this->page->pagetype;
        }

        $blockinstance = new stdClass;
        $blockinstance->blockname = $blockname;
        $blockinstance->parentcontextid = $this->page->context->id;
        $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
        $blockinstance->pagetypepattern = $pagetypepattern;
        $blockinstance->subpagepattern = $subpagepattern;
        $blockinstance->defaultregion = $region;
        $blockinstance->defaultweight = $weight;
        $blockinstance->configdata = '';
        $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);

        // Ensure the block context is created.
        get_context_instance(CONTEXT_BLOCK, $blockinstance->id);

        // If the new instance was created, allow it to do additional setup
        if ($block = block_instance($blockname, $blockinstance)) {
            $block->instance_create();
        }
    }

    public function add_block_at_end_of_default_region($blockname) {
        $defaulregion = $this->get_default_region();

        $lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
        if ($lastcurrentblock) {
            $weight = $lastcurrentblock->weight + 1;
        } else {
            $weight = 0;
        }

        if ($this->page->subpage) {
            $subpage = $this->page->subpage;
        } else {
            $subpage = null;
        }

        // Special case. Course view page type include the course format, but we
        // want to add the block non-format-specifically.
        $pagetypepattern = $this->page->pagetype;
        if (strpos($pagetypepattern, 'course-view') === 0) {
            $pagetypepattern = 'course-view-*';
        }

        $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
    }

    /**
* Convenience method, calls add_block repeatedly for all the blocks in $blocks.
*
* @param array $blocks array with array keys the region names, and values an array of block names.
* @param string $pagetypepattern optional. Passed to @see add_block()
* @param string $subpagepattern optional. Passed to @see add_block()
*/
    public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
        $this->add_regions(array_keys($blocks));
        foreach ($blocks as $region => $regionblocks) {
            $weight = 0;
            foreach ($regionblocks as $blockname) {
                $this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
                $weight += 1;
            }
        }
    }

    /**
* Move a block to a new position on this page.
*
* If this block cannot appear on any other pages, then we change defaultposition/weight
* in the block_instances table. Otherwise we just set the position on this page.
*
* @param $blockinstanceid the block instance id.
* @param $newregion the new region name.
* @param $newweight the new weight.
*/
    public function reposition_block($blockinstanceid, $newregion, $newweight) {
        global $DB;

        $this->check_region_is_known($newregion);
        $inst = $this->find_instance($blockinstanceid);

        $bi = $inst->instance;
        if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
                !$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
                (!$this->page->subpage || $bi->subpagepattern)) {

            // Set default position
            $newbi = new stdClass;
            $newbi->id = $bi->id;
            $newbi->defaultregion = $newregion;
            $newbi->defaultweight = $newweight;
            $DB->update_record('block_instances', $newbi);

            if ($bi->blockpositionid) {
                $bp = new stdClass;
                $bp->id = $bi->blockpositionid;
                $bp->region = $newregion;
                $bp->weight = $newweight;
                $DB->update_record('block_positions', $bp);
            }

        } else {
            // Just set position on this page.
            $bp = new stdClass;
            $bp->region = $newregion;
            $bp->weight = $newweight;

            if ($bi->blockpositionid) {
                $bp->id = $bi->blockpositionid;
                $DB->update_record('block_positions', $bp);

            } else {
                $bp->blockinstanceid = $bi->id;
                $bp->contextid = $this->page->context->id;
                $bp->pagetype = $this->page->pagetype;
                if ($this->page->subpage) {
                    $bp->subpage = $this->page->subpage;
                } else {
                    $bp->subpage = '';
                }
                $bp->visible = $bi->visible;
                $DB->insert_record('block_positions', $bp);
            }
        }
    }

    /**
* Find a given block by its instance id
*
* @param integer $instanceid
* @return object
*/
    public function find_instance($instanceid) {
        foreach ($this->regions as $region => $notused) {
            $this->ensure_instances_exist($region);
            foreach($this->blockinstances[$region] as $instance) {
                if ($instance->instance->id == $instanceid) {
                    return $instance;
                }
            }
        }
        throw new block_not_on_page_exception($instanceid, $this->page);
    }

/// Inner workings =============================================================

    /**
* Check whether the page blocks have been loaded yet
*
* @return void Throws coding exception if already loaded
*/
    protected function check_not_yet_loaded() {
        if (!is_null($this->birecordsbyregion)) {
            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.');
        }
    }

    /**
* Check whether the page blocks have been loaded yet
*
* Nearly identical to the above function {@link check_not_yet_loaded()} except different message
*
* @return void Throws coding exception if already loaded
*/
    protected function check_is_loaded() {
        if (is_null($this->birecordsbyregion)) {
            throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.');
        }
    }

    /**
* Check if a block type is known and usable
*
* @param string $blockname The block type name to search for
* @param bool $includeinvisible Include disabled block types in the initial pass
* @return void Coding Exception thrown if unknown or not enabled
*/
    protected function check_known_block_type($blockname, $includeinvisible = false) {
        if (!$this->is_known_block_type($blockname, $includeinvisible)) {
            if ($this->is_known_block_type($blockname, true)) {
                throw new coding_exception('Unknown block type ' . $blockname);
            } else {
                throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.');
            }
        }
    }

    /**
* Check if a region is known by its name
*
* @param string $region
* @return void Coding Exception thrown if the region is not known
*/
    protected function check_region_is_known($region) {
        if (!$this->is_known_region($region)) {
            throw new coding_exception('Trying to reference an unknown block region ' . $region);
        }
    }

    /**
* Returns an array of region names as keys and nested arrays for values
*
* @return array an array where the array keys are the region names, and the array
* values are empty arrays.
*/
    protected function prepare_per_region_arrays() {
        $result = array();
        foreach ($this->regions as $region => $notused) {
            $result[$region] = array();
        }
        return $result;
    }

    /**
* Create a set of new block instance from a record array
*
* @param array $birecords An array of block instance records
* @return array An array of instantiated block_instance objects
*/
    protected function create_block_instances($birecords) {
        $results = array();
        foreach ($birecords as $record) {
            if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
                $results[] = $blockobject;
            }
        }
        return $results;
    }

    /**
* Create all the block instances for all the blocks that were loaded by
* load_blocks. This is used, for example, to ensure that all blocks get a
* chance to initialise themselves via the {@link block_base::specialize()}
* method, before any output is done.
*/
    public function create_all_block_instances() {
        foreach ($this->get_regions() as $region) {
            $this->ensure_instances_exist($region);
        }
    }

    /**
* Return an array of content objects from a set of block instances
*
* @param array $instances An array of block instances
* @param renderer_base The renderer to use.
* @param string $region the region name.
* @return array An array of block_content (and possibly block_move_target) objects.
*/
    protected function create_block_contents($instances, $output, $region) {
        $results = array();

        $lastweight = 0;
        $lastblock = 0;
        if ($this->movingblock) {
            $first = reset($instances);
            if ($first) {
                $lastweight = $first->instance->weight - 2;
            }

            $strmoveblockhere = get_string('moveblockhere', 'block');
        }

        foreach ($instances as $instance) {
            $content = $instance->get_content_for_output($output);
            if (empty($content)) {
                continue;
            }

            if ($this->movingblock && $lastweight != $instance->instance->weight &&
                    $content->blockinstanceid != $this->movingblock && $lastblock != $this->movingblock) {
                $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, ($lastweight + $instance->instance->weight)/2));
            }

            if ($content->blockinstanceid == $this->movingblock) {
                $content->add_class('beingmoved');
                $content->annotation .= get_string('movingthisblockcancel', 'block',
                        html_writer::link($this->page->url, get_string('cancel')));
            }

            $results[] = $content;
            $lastweight = $instance->instance->weight;
            $lastblock = $instance->instance->id;
        }

        if ($this->movingblock && $lastblock != $this->movingblock) {
            $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1));
        }
        return $results;
    }

    /**
* Ensure block instances exist for a given region
*
* @param string $region Check for bi's with the instance with this name
*/
    protected function ensure_instances_exist($region) {
        $this->check_region_is_known($region);
        if (!array_key_exists($region, $this->blockinstances)) {
            $this->blockinstances[$region] =
                    $this->create_block_instances($this->birecordsbyregion[$region]);
        }
    }

    /**
* Ensure that there is some content within the given region
*
* @param string $region The name of the region to check
*/
    protected function ensure_content_created($region, $output) {
        $this->ensure_instances_exist($region);
        if (!array_key_exists($region, $this->visibleblockcontent)) {
            $contents = array();
            if (array_key_exists($region, $this->extracontent)) {
                $contents = $this->extracontent[$region];
            }
            $contents = array_merge($contents, $this->create_block_contents($this->blockinstances[$region], $output, $region));
            if ($region == $this->defaultregion) {
                $addblockui = block_add_block_ui($this->page, $output);
                if ($addblockui) {
                    $contents[] = $addblockui;
                }
            }
            $this->visibleblockcontent[$region] = $contents;
        }
    }

/// Process actions from the URL ===============================================

    /**
* Get the appropriate list of editing icons for a block. This is used
* to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}.
*
* @param $output The core_renderer to use when generating the output. (Need to get icon paths.)
* @return an array in the format for {@link block_contents::$controls}
*/
    public function edit_controls($block) {
        global $CFG;

        if (!isset($CFG->undeletableblocktypes) || (!is_array($CFG->undeletableblocktypes) && !is_string($CFG->undeletableblocktypes))) {
            $CFG->undeletableblocktypes = array('navigation','settings');
        } else if (is_string($CFG->undeletableblocktypes)) {
            $CFG->undeletableblocktypes = explode(',', $CFG->undeletableblocktypes);
        }

        $controls = array();
        $actionurl = $this->page->url->out(false, array('sesskey'=> sesskey()));

        // Assign roles icon.
        if (has_capability('moodle/role:assign', $block->context)) {
            //TODO: please note it is sloppy to pass urls through page parameters!!
            // it is shortened because some web servers (e.g. IIS by default) give
            // a 'security' error if you try to pass a full URL as a GET parameter in another URL.

            $return = $this->page->url->out(false);
            $return = str_replace($CFG->wwwroot . '/', '', $return);

            $controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin .
                    '/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return),
                    'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));
        }

        if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) {
            // Show/hide icon.
            if ($block->instance->visible) {
                $controls[] = array('url' => $actionurl . '&bui_hideid=' . $block->instance->id,
                        'icon' => 't/hide', 'caption' => get_string('hide'));
            } else {
                $controls[] = array('url' => $actionurl . '&bui_showid=' . $block->instance->id,
                        'icon' => 't/show', 'caption' => get_string('show'));
            }
        }

        if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) {
            // Edit config icon - always show - needed for positioning UI.
            $controls[] = array('url' => $actionurl . '&bui_editid=' . $block->instance->id,
                    'icon' => 't/edit', 'caption' => get_string('configuration'));
        }

        if ($this->page->user_can_edit_blocks() && $block->user_can_edit() && $block->user_can_addto($this->page)) {
            if (!in_array($block->instance->blockname, $CFG->undeletableblocktypes)) {
                // Delete icon.
                $controls[] = array('url' => $actionurl . '&bui_deleteid=' . $block->instance->id,
                        'icon' => 't/delete', 'caption' => get_string('delete'));
            }
        }

        if ($this->page->user_can_edit_blocks()) {
            // Move icon.
            $controls[] = array('url' => $actionurl . '&bui_moveid=' . $block->instance->id,
                    'icon' => 't/move', 'caption' => get_string('move'));
        }

        return $controls;
    }

    /**
* Process any block actions that were specified in the URL.
*
* This can only be done given a valid $page object.
*
* @param moodle_page $page the page to add blocks to.
* @return boolean true if anything was done. False if not.
*/
    public function process_url_actions() {
        if (!$this->page->user_is_editing()) {
            return false;
        }
        return $this->process_url_add() || $this->process_url_delete() ||
            $this->process_url_show_hide() || $this->process_url_edit() ||
            $this->process_url_move();
    }

    /**
* Handle adding a block.
* @return boolean true if anything was done. False if not.
*/
    public function process_url_add() {
        $blocktype = optional_param('bui_addblock', null, PARAM_SAFEDIR);
        if (!$blocktype) {
            return false;
        }

        require_sesskey();

        if (!$this->page->user_can_edit_blocks()) {
            throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
        }

        if (!array_key_exists($blocktype, $this->get_addable_blocks())) {
            throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
        }

        $this->add_block_at_end_of_default_region($blocktype);

        // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
        $this->page->ensure_param_not_in_url('bui_addblock');

        return true;
    }

    /**
* Handle deleting a block.
* @return boolean true if anything was done. False if not.
*/
    public function process_url_delete() {
        $blockid = optional_param('bui_deleteid', null, PARAM_INTEGER);
        if (!$blockid) {
            return false;
        }

        require_sesskey();

        $block = $this->page->blocks->find_instance($blockid);

        if (!$block->user_can_edit() || !$this->page->user_can_edit_blocks() || !$block->user_can_addto($this->page)) {
            throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('deleteablock'));
        }

        blocks_delete_instance($block->instance);

        // If the page URL was a guess, it will contain the bui_... param, so we must make sure it is not there.
        $this->page->ensure_param_not_in_url('bui_deleteid');

        return true;
    }

    /**
* Handle showing or hiding a block.
* @return boolean true if anything was done. False if not.
*/
    public function process_url_show_hide() {
        if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER)) {
            $newvisibility = 0;
        } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER)) {
            $newvisibility = 1;
        } else {
            return false;
        }

        require_sesskey();

        $block = $this->page->blocks->find_instance($blockid);

        if (!$this->page->user_can_edit_blocks()) {
            throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('hideshowblocks'));
        } else if (!$block->instance_can_be_hidden()) {
            return false;
        }

        blocks_set_visibility($block->instance, $this->page, $newvisibility);

        // If the page URL was a guses, it will contain the bui_... param, so we must make sure it is not there.
        $this->page->ensure_param_not_in_url('bui_hideid');
        $this->page->ensure_param_not_in_url('bui_showid');

        return true;
    }

    /**
* Handle showing/processing the submission from the block editing form.
* @return boolean true if the form was submitted and the new config saved. Does not
* return if the editing form was displayed. False otherwise.
*/
    public function process_url_edit() {
        global $CFG, $DB, $PAGE, $OUTPUT;

        $blockid = optional_param('bui_editid', null, PARAM_INTEGER);
        if (!$blockid) {
            return false;
        }

        require_sesskey();
        require_once($CFG->dirroot . '/blocks/edit_form.php');

        $block = $this->find_instance($blockid);

        if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) {
            throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
        }

        $editpage = new moodle_page();
        $editpage->set_pagelayout('admin');
        $editpage->set_course($this->page->course);
        //$editpage->set_context($block->context);
        $editpage->set_context($this->page->context);
        if ($this->page->cm) {
            $editpage->set_cm($this->page->cm);
        }
        $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring());
        $editurlparams = $this->page->url->params();
        $editurlparams['bui_editid'] = $blockid;
        $editpage->set_url($editurlbase, $editurlparams);
        $editpage->set_block_actions_done();
        // At this point we are either going to redirect, or display the form, so
        // overwrite global $PAGE ready for this. (Formslib refers to it.)
        $PAGE = $editpage;
        //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to
        $output = $editpage->get_renderer('core');
        $OUTPUT = $output;

        $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php';
        if (is_readable($formfile)) {
            require_once($formfile);
            $classname = 'block_' . $block->name() . '_edit_form';
            if (!class_exists($classname)) {
                $classname = 'block_edit_form';
            }
        } else {
            $classname = 'block_edit_form';
        }

        $mform = new $classname($editpage->url, $block, $this->page);
        $mform->set_data($block->instance);

        if ($mform->is_cancelled()) {
            redirect($this->page->url);

        } else if ($data = $mform->get_data()) {
            $bi = new stdClass;
            $bi->id = $block->instance->id;
            $bi->pagetypepattern = $data->bui_pagetypepattern;
            if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') {
                $bi->subpagepattern = null;
            } else {
                $bi->subpagepattern = $data->bui_subpagepattern;
            }

            $parentcontext = get_context_instance_by_id($data->bui_parentcontextid);
            $systemcontext = get_context_instance(CONTEXT_SYSTEM);

            // Updating stickiness and contexts. See MDL-21375 for details.
            if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination
                // Explicitly set the context
                $bi->parentcontextid = $parentcontext->id;

                // If the context type is > 0 then we'll explicitly set the block as sticky, otherwise not
                $bi->showinsubcontexts = (int)(!empty($data->bui_contexts));

                // If the block wants to be system-wide, then explicitly set that
                if ($data->bui_contexts == BUI_CONTEXTS_ENTIRE_SITE) { // Only possible on a frontpage or system page
                    $bi->parentcontextid = $systemcontext->id;
                    $bi->showinsubcontexts = 1;

                } else { // The block doesn't want to be system-wide, so let's ensure that
                    if ($parentcontext->id == $systemcontext->id) { // We need to move it to the front page
                        $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
                        $bi->parentcontextid = $frontpagecontext->id;
                        $bi->pagetypepattern = '*'; // Just in case
                    }
                }
            }

            $bits = explode('-', $bi->pagetypepattern);
            // hacks for some contexts
            if (($parentcontext->contextlevel == CONTEXT_COURSE) && ($parentcontext->instanceid != SITEID)) {
                // For course context
                // is page type pattern is mod-*, change showinsubcontext to 1
                if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') {
                    $bi->showinsubcontexts = 1;
                } else {
                    $bi->showinsubcontexts = 0;
                }
            } else if ($parentcontext->contextlevel == CONTEXT_USER) {
                // for user context
                // subpagepattern should be null
                if ($bits[0] == 'user' or $bits[0] == 'my') {
                    // we don't need subpagepattern in usercontext
                    $bi->subpagepattern = null;
                }
            }

            $bi->defaultregion = $data->bui_defaultregion;
            $bi->defaultweight = $data->bui_defaultweight;
            $DB->update_record('block_instances', $bi);

            if (!empty($block->config)) {
                $config = clone($block->config);
            } else {
                $config = new stdClass;
            }
            foreach ($data as $configfield => $value) {
                if (strpos($configfield, 'config_') !== 0) {
                    continue;
                }
                $field = substr($configfield, 7);
                $config->$field = $value;
            }
            $block->instance_config_save($config);

            $bp = new stdClass;
            $bp->visible = $data->bui_visible;
            $bp->region = $data->bui_region;
            $bp->weight = $data->bui_weight;
            $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion ||
                    $data->bui_weight != $data->bui_defaultweight;

            if ($block->instance->blockpositionid && !$needbprecord) {
                $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid));

            } else if ($block->instance->blockpositionid && $needbprecord) {
                $bp->id = $block->instance->blockpositionid;
                $DB->update_record('block_positions', $bp);

            } else if ($needbprecord) {
                $bp->blockinstanceid = $block->instance->id;
                $bp->contextid = $this->page->context->id;
                $bp->pagetype = $this->page->pagetype;
                if ($this->page->subpage) {
                    $bp->subpage = $this->page->subpage;
                } else {
                    $bp->subpage = '';
                }
                $DB->insert_record('block_positions', $bp);
            }

            redirect($this->page->url);

        } else {
            $strheading = get_string('blockconfiga', 'moodle', $block->get_title());
            $editpage->set_title($strheading);
            $editpage->set_heading($strheading);
            $bits = explode('-', $this->page->pagetype);
            if ($bits[0] == 'tag' && !empty($this->page->subpage)) {
                // better navbar for tag pages
                $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/'));
                $tag = tag_get('id', $this->page->subpage, '*');
                // tag search page doesn't have subpageid
                if ($tag) {
                    $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id'=>$tag->id)));
                }
            }
            $editpage->navbar->add($block->get_title());
            $editpage->navbar->add(get_string('configuration'));
            echo $output->header();
            echo $output->heading($strheading, 2);
            $mform->display();
            echo $output->footer();
            exit;
        }
    }

    /**
* Handle showing/processing the submission from the block editing form.
* @return boolean true if the form was submitted and the new config saved. Does not
* return if the editing form was displayed. False otherwise.
*/
    public function process_url_move() {
        global $CFG, $DB, $PAGE;

        $blockid = optional_param('bui_moveid', null, PARAM_INTEGER);
        if (!$blockid) {
            return false;
        }

        require_sesskey();

        $block = $this->find_instance($blockid);

        if (!$this->page->user_can_edit_blocks()) {
            throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
        }

        $newregion = optional_param('bui_newregion', '', PARAM_ALPHANUMEXT);
        $newweight = optional_param('bui_newweight', null, PARAM_FLOAT);
        if (!$newregion || is_null($newweight)) {
            // Don't have a valid target position yet, must be just starting the move.
            $this->movingblock = $blockid;
            $this->page->ensure_param_not_in_url('bui_moveid');
            return false;
        }

        if (!$this->is_known_region($newregion)) {
            throw new moodle_exception('unknownblockregion', '', $this->page->url, $newregion);
        }

        // Move this block. This may involve moving other nearby blocks.
        $blocks = $this->birecordsbyregion[$newregion];

        $maxweight = self::MAX_WEIGHT;
        $minweight = -self::MAX_WEIGHT;

        // Initialise the used weights and spareweights array with the default values
        $spareweights = array();
        $usedweights = array();
        for ($i = $minweight; $i <= $maxweight; $i++) {
            $spareweights[$i] = $i;
            $usedweights[$i] = array();
        }

        // Check each block and sort out where we have used weights
        foreach ($blocks as $bi) {
            if ($bi->weight > $maxweight) {
                // If this statement is true then the blocks weight is more than the
                // current maximum. To ensure that we can get the best block position
                // we will initialise elements within the usedweights and spareweights
                // arrays between the blocks weight (which will then be the new max) and
                // the current max
                $parseweight = $bi->weight;
                while (!array_key_exists($parseweight, $usedweights)) {
                    $usedweights[$parseweight] = array();
                    $spareweights[$parseweight] = $parseweight;
                    $parseweight--;
                }
                $maxweight = $bi->weight;
            } else if ($bi->weight < $minweight) {
                // As above except this time the blocks weight is LESS than the
                // the current minimum, so we will initialise the array from the
                // blocks weight (new minimum) to the current minimum
                $parseweight = $bi->weight;
                while (!array_key_exists($parseweight, $usedweights)) {
                    $usedweights[$parseweight] = array();
                    $spareweights[$parseweight] = $parseweight;
                    $parseweight++;
                }
                $minweight = $bi->weight;
            }
            if ($bi->id != $block->instance->id) {
                unset($spareweights[$bi->weight]);
                $usedweights[$bi->weight][] = $bi->id;
            }
        }

        // First we find the nearest gap in the list of weights.
        $bestdistance = max(abs($newweight - self::MAX_WEIGHT), abs($newweight + self::MAX_WEIGHT)) + 1;
        $bestgap = null;
        foreach ($spareweights as $spareweight) {
            if (abs($newweight - $spareweight) < $bestdistance) {
                $bestdistance = abs($newweight - $spareweight);
                $bestgap = $spareweight;
            }
        }

        // If there is no gap, we have to go outside -self::MAX_WEIGHT .. self::MAX_WEIGHT.
        if (is_null($bestgap)) {
            $bestgap = self::MAX_WEIGHT + 1;
            while (!empty($usedweights[$bestgap])) {
                $bestgap++;
            }
        }

        // Now we know the gap we are aiming for, so move all the blocks along.
        if ($bestgap < $newweight) {
            $newweight = floor($newweight);
            for ($weight = $bestgap + 1; $weight <= $newweight; $weight++) {
                foreach ($usedweights[$weight] as $biid) {
                    $this->reposition_block($biid, $newregion, $weight - 1);
                }
            }
            $this->reposition_block($block->instance->id, $newregion, $newweight);
        } else {
            $newweight = ceil($newweight);
            for ($weight = $bestgap - 1; $weight >= $newweight; $weight--) {
                foreach ($usedweights[$weight] as $biid) {
                    $this->reposition_block($biid, $newregion, $weight + 1);
                }
            }
            $this->reposition_block($block->instance->id, $newregion, $newweight);
        }

        $this->page->ensure_param_not_in_url('bui_moveid');
        $this->page->ensure_param_not_in_url('bui_newregion');
        $this->page->ensure_param_not_in_url('bui_newweight');
        return true;
    }

    /**
* Turns the display of normal blocks either on or off.
*
* @param bool $setting
*/
    public function show_only_fake_blocks($setting = true) {
        $this->fakeblocksonly = $setting;
    }
}

/// Helper functions for working with block classes ============================

/**
* Call a class method (one that does not require a block instance) on a block class.
*
* @param string $blockname the name of the block.
* @param string $method the method name.
* @param array $param parameters to pass to the method.
* @return mixed whatever the method returns.
*/
function block_method_result($blockname, $method, $param = NULL) {
    if(!block_load_class($blockname)) {
        return NULL;
    }
    return call_user_func(array('block_'.$blockname, $method), $param);
}

/**
* Creates a new instance of the specified block class.
*
* @param string $blockname the name of the block.
* @param $instance block_instances DB table row (optional).
* @param moodle_page $page the page this block is appearing on.
* @return block_base the requested block instance.
*/
function block_instance($blockname, $instance = NULL, $page = NULL) {
    if(!block_load_class($blockname)) {
        return false;
    }
    $classname = 'block_'.$blockname;
    $retval = new $classname;
    if($instance !== NULL) {
        if (is_null($page)) {
            global $PAGE;
            $page = $PAGE;
        }
        $retval->_load_instance($instance, $page);
    }
    return $retval;
}

/**
* Load the block class for a particular type of block.
*
* @param string $blockname the name of the block.
* @return boolean success or failure.
*/
function block_load_class($blockname) {
    global $CFG;

    if(empty($blockname)) {
        return false;
    }

    $classname = 'block_'.$blockname;

    if(class_exists($classname)) {
        return true;
    }

    $blockpath = $CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php';

    if (file_exists($blockpath)) {
        require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
        include_once($blockpath);
    }else{
        //debugging("$blockname code does not exist in $blockpath", DEBUG_DEVELOPER);
        return false;
    }

    return class_exists($classname);
}

/**
* Given a specific page type, return all the page type patterns that might
* match it.
*
* @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
* @return array an array of all the page type patterns that might match this page type.
*/
function matching_page_type_patterns($pagetype) {
    $patterns = array($pagetype);
    $bits = explode('-', $pagetype);
    if (count($bits) == 3 && $bits[0] == 'mod') {
        if ($bits[2] == 'view') {
            $patterns[] = 'mod-*-view';
        } else if ($bits[2] == 'index') {
            $patterns[] = 'mod-*-index';
        }
    }
    while (count($bits) > 0) {
        $patterns[] = implode('-', $bits) . '-*';
        array_pop($bits);
    }
    $patterns[] = '*';
    return $patterns;
}

/**
* Given a specific page type, parent context and currect context, return all the page type patterns
* that might be used by this block.
*
* @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'.
* @param stdClass $parentcontext Block's parent context
* @param stdClass $currentcontext Current context of block
* @return array an array of all the page type patterns that might match this page type.
*/
function generate_page_type_patterns($pagetype, $parentcontext = null, $currentcontext = null) {
    global $CFG;

    $bits = explode('-', $pagetype);

    $component = clean_param(reset($bits), PARAM_ALPHANUMEXT);
    $function = 'default_pagetypelist';

    $core = get_core_subsystems();
    $plugins = get_plugin_types();

    // First check to see if the initial component is a core component
    // if its not check to see if it is a plugin component.
    if (array_key_exists($component, $core) && !empty($core[$component])) {
        $libfile = $CFG->dirroot.'/'.$core[$component].'/lib.php';
        if (file_exists($libfile)) {
            require_once($libfile);
            if (function_exists($component.'_pagetypelist')) {
                $function = $component.'_pagetypelist';
            }
        }
    } else if (array_key_exists($component, $plugins) && !empty($plugins[$component])) {
        $function = 'plugin_pagetypelist';
        if (function_exists($component.'_pagetypelist')) {
            $function = $component.'_pagetypelist';
        }
    }
    // Call the most appropriate function we could determine
    $patterns = $function($pagetype, $parentcontext, $currentcontext);
    if (empty($patterns)) {
        // If there are no patterns default to just the current pattern.
        $patterns = array($pagetype => $pagetype);
    }
    return $patterns;
}

/**
* Generates a default page type list when a more appropriate callback cannot be decided upon.
*
* @param string $pagetype
* @param stdClass $parentcontext
* @param stdClass $currentcontext
* @return array
*/
function default_pagetypelist($pagetype, $parentcontext = null, $currentcontext = null) {
    // Generate page type patterns based on current page type if
    // callbacks haven't been defined
    $patterns = array($pagetype => $pagetype);
    $bits = explode('-', $pagetype);
    while (count($bits) > 0) {
        $pattern = implode('-', $bits) . '-*';
        $pagetypestringname = 'page-'.str_replace('*', 'x', $pattern);
        // guessing page type description
        if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
            $patterns[$pattern] = get_string($pagetypestringname, 'pagetype');
        } else {
            $patterns[$pattern] = $pattern;
        }
        array_pop($bits);
    }
    $patterns['*'] = get_string('page-x', 'pagetype');
    return $patterns;
}

/**
* Generates a page type list for plugins
*
* @param string $pagetype
* @param stdClass $parentcontext
* @param stdClass $currentcontext
* @return array
*/
function plugin_pagetypelist($pagetype, $parentcontext = null, $currentcontext = null) {
    global $CFG;

    // for modules
    $bits = explode('-', $pagetype);
    $plugintype = $bits[0];
    $pluginname = $bits[1];
    $directory = get_plugin_directory($plugintype, $pluginname);
    if (empty($directory)) {
        return array();
    }
    $libfile = $directory.'/lib.php';
    require_once($libfile);
    $function = $pluginname.'_pagetypelist';
    if (!function_exists($function)) {
        return array();
    }
    $patterns = $function($pagetype, $parentcontext, $currentcontext);
    if ($parentcontext->contextlevel == CONTEXT_COURSE) {
        // including course page type
        require_once("$CFG->dirroot/course/lib.php");
        $patterns = array_merge(course_pagetypelist($pagetype, $parentcontext, $currentcontext), $patterns);
    }
    return $patterns;
}

/**
* Generates the page type list for the my moodle page
*
* @param string $pagetype
* @param stdClass $parentcontext
* @param stdClass $currentcontext
* @return array
*/
function my_pagetypelist($pagetype, $parentcontext = null, $currentcontext = null) {
    return array('my-index' => 'my-index');
}

/**
* Generates the page type list for a module by either locating and using the modules callback
* or by generating a default list.
*
* @param string $pagetype
* @param stdClass $parentcontext
* @param stdClass $currentcontext
* @return array
*/
function mod_pagetypelist($pagetype, $parentcontext = null, $currentcontext = null) {
    $patterns = plugin_pagetypelist($pagetype, $parentcontext, $currentcontext);
    if (empty($patterns)) {
        // if modules don't have callbacks
        // generate two default page type patterns for modules only
        $bits = explode('-', $pagetype);
        $patterns = array($pagetype => $pagetype);
        if ($bits[2] == 'view') {
            $patterns['mod-*-view'] = get_string('page-mod-x-view', 'pagetype');
        } else if ($bits[2] == 'index') {
            $patterns['mod-*-index'] = get_string('page-mod-x-index', 'pagetype');
        }
    }
    return $patterns;
}
/// Functions update the blocks if required by the request parameters ==========

/**
* Return a {@link block_contents} representing the add a new block UI, if
* this user is allowed to see it.
*
* @return block_contents an appropriate block_contents, or null if the user
* cannot add any blocks here.
*/
function block_add_block_ui($page, $output) {
    global $CFG, $OUTPUT;
    if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
        return null;
    }

    $bc = new block_contents();
    $bc->title = get_string('addblock');
    $bc->add_class('block_adminblock');

    $missingblocks = $page->blocks->get_addable_blocks();
    if (empty($missingblocks)) {
        $bc->content = get_string('noblockstoaddhere');
        return $bc;
    }

    $menu = array();
    foreach ($missingblocks as $block) {
        $blockobject = block_instance($block->name);
        if ($blockobject !== false && $blockobject->user_can_addto($page)) {
            $menu[$block->name] = $blockobject->get_title();
        }
    }
    textlib_get_instance()->asort($menu);

    $actionurl = new moodle_url($page->url, array('sesskey'=>sesskey()));
    $select = new single_select($actionurl, 'bui_addblock', $menu, null, array(''=>get_string('adddots')), 'add_block');
    $bc->content = $OUTPUT->render($select);
    return $bc;
}

// Functions that have been deprecated by block_manager =======================

/**
* @deprecated since Moodle 2.0 - use $page->blocks->get_addable_blocks();
*
* This function returns an array with the IDs of any blocks that you can add to your page.
* Parameters are passed by reference for speed; they are not modified at all.
*
* @param $page the page object.
* @param $blockmanager Not used.
* @return array of block type ids.
*/
function blocks_get_missing(&$page, &$blockmanager) {
    debugging('blocks_get_missing is deprecated. Please use $page->blocks->get_addable_blocks() instead.', DEBUG_DEVELOPER);
    $blocks = $page->blocks->get_addable_blocks();
    $ids = array();
    foreach ($blocks as $block) {
        $ids[] = $block->id;
    }
    return $ids;
}

/**
* Actually delete from the database any blocks that are currently on this page,
* but which should not be there according to blocks_name_allowed_in_format.
*
* @todo Write/Fix this function. Currently returns immediately
* @param $course
*/
function blocks_remove_inappropriate($course) {
    // TODO
    return;
    /*
$blockmanager = blocks_get_by_page($page);

if (empty($blockmanager)) {
return;
}

if (($pageformat = $page->pagetype) == NULL) {
return;
}

foreach($blockmanager as $region) {
foreach($region as $instance) {
$block = blocks_get_record($instance->blockid);
if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
blocks_delete_instance($instance->instance);
}
}
}*/
}

/**
* Check that a given name is in a permittable format
*
* @param string $name
* @param string $pageformat
* @return bool
*/
function blocks_name_allowed_in_format($name, $pageformat) {
    $accept = NULL;
    $maxdepth = -1;
    $formats = block_method_result($name, 'applicable_formats');
    if (!$formats) {
        $formats = array();
    }
    foreach ($formats as $format => $allowed) {
        $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
        $depth = substr_count($format, '-');
        if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
            $maxdepth = $depth;
            $accept = $allowed;
        }
    }
    if ($accept === NULL) {
        $accept = !empty($formats['all']);
    }
    return $accept;
}

/**
* Delete a block, and associated data.
*
* @param object $instance a row from the block_instances table
* @param bool $nolongerused legacy parameter. Not used, but kept for backwards compatibility.
* @param bool $skipblockstables for internal use only. Makes @see blocks_delete_all_for_context() more efficient.
*/
function blocks_delete_instance($instance, $nolongerused = false, $skipblockstables = false) {
    global $DB;

    if ($block = block_instance($instance->blockname, $instance)) {
        $block->instance_delete();
    }
    delete_context(CONTEXT_BLOCK, $instance->id);

    if (!$skipblockstables) {
        $DB->delete_records('block_positions', array('blockinstanceid' => $instance->id));
        $DB->delete_records('block_instances', array('id' => $instance->id));
        $DB->delete_records_list('user_preferences', 'name', array('block'.$instance->id.'hidden','docked_block_instance_'.$instance->id));
    }
}

/**
* Delete all the blocks that belong to a particular context.
*
* @param int $contextid the context id.
*/
function blocks_delete_all_for_context($contextid) {
    global $DB;
    $instances = $DB->get_recordset('block_instances', array('parentcontextid' => $contextid));
    foreach ($instances as $instance) {
        blocks_delete_instance($instance, true);
    }
    $instances->close();
    $DB->delete_records('block_instances', array('parentcontextid' => $contextid));
    $DB->delete_records('block_positions', array('contextid' => $contextid));
}

/**
* Set a block to be visible or hidden on a particular page.
*
* @param object $instance a row from the block_instances, preferably LEFT JOINed with the
* block_positions table as return by block_manager.
* @param moodle_page $page the back to set the visibility with respect to.
* @param integer $newvisibility 1 for visible, 0 for hidden.
*/
function blocks_set_visibility($instance, $page, $newvisibility) {
    global $DB;
    if (!empty($instance->blockpositionid)) {
        // Already have local information on this page.
        $DB->set_field('block_positions', 'visible', $newvisibility, array('id' => $instance->blockpositionid));
        return;
    }

    // Create a new block_positions record.
    $bp = new stdClass;
    $bp->blockinstanceid = $instance->id;
    $bp->contextid = $page->context->id;
    $bp->pagetype = $page->pagetype;
    if ($page->subpage) {
        $bp->subpage = $page->subpage;
    }
    $bp->visible = $newvisibility;
    $bp->region = $instance->defaultregion;
    $bp->weight = $instance->defaultweight;
    $DB->insert_record('block_positions', $bp);
}

/**
* @deprecated since 2.0
* Delete all the blocks from a particular page.
*
* @param string $pagetype the page type.
* @param integer $pageid the page id.
* @return bool success or failure.
*/
function blocks_delete_all_on_page($pagetype, $pageid) {
    global $DB;

    debugging('Call to deprecated function blocks_delete_all_on_page. ' .
            'This function cannot work any more. Doing nothing. ' .
            'Please update your code to use a block_manager method $PAGE->blocks->....', DEBUG_DEVELOPER);
    return false;
}

/**
* Dispite what this function is called, it seems to be mostly used to populate
* the default blocks when a new course (or whatever) is created.
*
* @deprecated since 2.0
*
* @param object $page the page to add default blocks to.
* @return boolean success or failure.
*/
function blocks_repopulate_page($page) {
    global $CFG;

    debugging('Call to deprecated function blocks_repopulate_page. ' .
            'Use a more specific method like blocks_add_default_course_blocks, ' .
            'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER);

    /// If the site override has been defined, it is the only valid one.
    if (!empty($CFG->defaultblocks_override)) {
        $blocknames = $CFG->defaultblocks_override;
    } else {
        $blocknames = $page->blocks_get_default();
    }

    $blocks = blocks_parse_default_blocks_list($blocknames);
    $page->blocks->add_blocks($blocks);

    return true;
}

/**
* Get the block record for a particular blockid - that is, a particular type os block.
*
* @param $int blockid block type id. If null, an array of all block types is returned.
* @param bool $notusedanymore No longer used.
* @return array|object row from block table, or all rows.
*/
function blocks_get_record($blockid = NULL, $notusedanymore = false) {
    global $PAGE;
    $blocks = $PAGE->blocks->get_installed_blocks();
    if ($blockid === NULL) {
        return $blocks;
    } else if (isset($blocks[$blockid])) {
        return $blocks[$blockid];
    } else {
        return false;
    }
}

/**
* Find a given block by its blockid within a provide array
*
* @param int $blockid
* @param array $blocksarray
* @return bool|object Instance if found else false
*/
function blocks_find_block($blockid, $blocksarray) {
    if (empty($blocksarray)) {
        return false;
    }
    foreach($blocksarray as $blockgroup) {
        if (empty($blockgroup)) {
            continue;
        }
        foreach($blockgroup as $instance) {
            if($instance->blockid == $blockid) {
                return $instance;
            }
        }
    }
    return false;
}

// Functions for programatically adding default blocks to pages ================

/**
* Parse a list of default blocks. See config-dist for a description of the format.
*
* @param string $blocksstr
* @return array
*/
function blocks_parse_default_blocks_list($blocksstr) {
    $blocks = array();
    $bits = explode(':', $blocksstr);
    if (!empty($bits)) {
        $leftbits = trim(array_shift($bits));
        if ($leftbits != '') {
            $blocks[BLOCK_POS_LEFT] = explode(',', $leftbits);
        }
    }
    if (!empty($bits)) {
        $rightbits =trim(array_shift($bits));
        if ($rightbits != '') {
            $blocks[BLOCK_POS_RIGHT] = explode(',', $rightbits);
        }
    }
    return $blocks;
}

/**
* @return array the blocks that should be added to the site course by default.
*/
function blocks_get_default_site_course_blocks() {
    global $CFG;

    if (!empty($CFG->defaultblocks_site)) {
        return blocks_parse_default_blocks_list($CFG->defaultblocks_site);
    } else {
        return array(
            BLOCK_POS_LEFT => array('site_main_menu'),
            BLOCK_POS_RIGHT => array('course_summary', 'calendar_month')
        );
    }
}

/**
* Add the default blocks to a course.
*
* @param object $course a course object.
*/
function blocks_add_default_course_blocks($course) {
    global $CFG;

    if (!empty($CFG->defaultblocks_override)) {
        $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override);

    } else if ($course->id == SITEID) {
        $blocknames = blocks_get_default_site_course_blocks();

    } else {
        $defaultblocks = 'defaultblocks_' . $course->format;
        if (!empty($CFG->$defaultblocks)) {
            $blocknames = blocks_parse_default_blocks_list($CFG->$defaultblocks);

        } else {
            $formatconfig = $CFG->dirroot.'/course/format/'.$course->format.'/config.php';
            $format = array(); // initialize array in external file
            if (is_readable($formatconfig)) {
                include($formatconfig);
            }
            if (!empty($format['defaultblocks'])) {
                $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']);

            } else if (!empty($CFG->defaultblocks)){
                $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks);

            } else {
                $blocknames = array(
                    BLOCK_POS_LEFT => array(),
                    BLOCK_POS_RIGHT => array('search_forums', 'news_items', 'calendar_upcoming', 'recent_activity')
                );
            }
        }
    }

    if ($course->id == SITEID) {
        $pagetypepattern = 'site-index';
    } else {
        $pagetypepattern = 'course-view-*';
    }
    $page = new moodle_page();
    $page->set_course($course);
    $page->blocks->add_blocks($blocknames, $pagetypepattern);
}

/**
* Add the default system-context blocks. E.g. the admin tree.
*/
function blocks_add_default_system_blocks() {
    global $DB;

    $page = new moodle_page();
    $page->set_context(get_context_instance(CONTEXT_SYSTEM));
    $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true);
    $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2);

    if ($defaultmypage = $DB->get_record('my_pages', array('userid'=>null, 'name'=>'__default', 'private'=>1))) {
        $subpagepattern = $defaultmypage->id;
    } else {
        $subpagepattern = null;
    }

    $page->blocks->add_blocks(array(BLOCK_POS_RIGHT => array('private_files', 'online_users'), 'content' => array('course_overview')), 'my-index', $subpagepattern, false);
}
Something went wrong with that request. Please try again.