Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 424f91c056
Fetching contributors…

Cannot retrieve contributors at this time

file 4285 lines (3946 sloc) 183.854 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 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285
<?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/>.

/**
* This file contains classes used to manage the navigation structures in Moodle
* and was introduced as part of the changes occuring in Moodle 2.0
*
* @since 2.0
* @package core
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

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

/**
* The name that will be used to separate the navigation cache within SESSION
*/
define('NAVIGATION_CACHE_NAME', 'navigation');

/**
* This class is used to represent a node in a navigation tree
*
* This class is used to represent a node in a navigation tree within Moodle,
* the tree could be one of global navigation, settings navigation, or the navbar.
* Each node can be one of two types either a Leaf (default) or a branch.
* When a node is first created it is created as a leaf, when/if children are added
* the node then becomes a branch.
*
* @package moodlecore
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class navigation_node implements renderable {
    /** @var int Used to identify this node a leaf (default) 0 */
    const NODETYPE_LEAF = 0;
    /** @var int Used to identify this node a branch, happens with children 1 */
    const NODETYPE_BRANCH = 1;
    /** @var null Unknown node type null */
    const TYPE_UNKNOWN = null;
    /** @var int System node type 0 */
    const TYPE_ROOTNODE = 0;
    /** @var int System node type 1 */
    const TYPE_SYSTEM = 1;
    /** @var int Category node type 10 */
    const TYPE_CATEGORY = 10;
    /** @var int Course node type 20 */
    const TYPE_COURSE = 20;
    /** @var int Course Structure node type 30 */
    const TYPE_SECTION = 30;
    /** @var int Activity node type, e.g. Forum, Quiz 40 */
    const TYPE_ACTIVITY = 40;
    /** @var int Resource node type, e.g. Link to a file, or label 50 */
    const TYPE_RESOURCE = 50;
    /** @var int A custom node type, default when adding without specifing type 60 */
    const TYPE_CUSTOM = 60;
    /** @var int Setting node type, used only within settings nav 70 */
    const TYPE_SETTING = 70;
    /** @var int Setting node type, used only within settings nav 80 */
    const TYPE_USER = 80;
    /** @var int Setting node type, used for containers of no importance 90 */
    const TYPE_CONTAINER = 90;

    /** @var int Parameter to aid the coder in tracking [optional] */
    public $id = null;
    /** @var string|int The identifier for the node, used to retrieve the node */
    public $key = null;
    /** @var string The text to use for the node */
    public $text = null;
    /** @var string Short text to use if requested [optional] */
    public $shorttext = null;
    /** @var string The title attribute for an action if one is defined */
    public $title = null;
    /** @var string A string that can be used to build a help button */
    public $helpbutton = null;
    /** @var moodle_url|action_link|null An action for the node (link) */
    public $action = null;
    /** @var pix_icon The path to an icon to use for this node */
    public $icon = null;
    /** @var int See TYPE_* constants defined for this class */
    public $type = self::TYPE_UNKNOWN;
    /** @var int See NODETYPE_* constants defined for this class */
    public $nodetype = self::NODETYPE_LEAF;
    /** @var bool If set to true the node will be collapsed by default */
    public $collapse = false;
    /** @var bool If set to true the node will be expanded by default */
    public $forceopen = false;
    /** @var array An array of CSS classes for the node */
    public $classes = array();
    /** @var navigation_node_collection An array of child nodes */
    public $children = array();
    /** @var bool If set to true the node will be recognised as active */
    public $isactive = false;
    /** @var bool If set to true the node will be dimmed */
    public $hidden = false;
    /** @var bool If set to false the node will not be displayed */
    public $display = true;
    /** @var bool If set to true then an HR will be printed before the node */
    public $preceedwithhr = false;
    /** @var bool If set to true the the navigation bar should ignore this node */
    public $mainnavonly = false;
    /** @var bool If set to true a title will be added to the action no matter what */
    public $forcetitle = false;
    /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
    public $parent = null;
    /** @var bool Override to not display the icon even if one is provided **/
    public $hideicon = false;
    /** @var array */
    protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
    /** @var moodle_url */
    protected static $fullmeurl = null;
    /** @var bool toogles auto matching of active node */
    public static $autofindactive = true;

    /**
* Constructs a new navigation_node
*
* @param array|string $properties Either an array of properties or a string to use
* as the text for the node
*/
    public function __construct($properties) {
        if (is_array($properties)) {
            // Check the array for each property that we allow to set at construction.
            // text - The main content for the node
            // shorttext - A short text if required for the node
            // icon - The icon to display for the node
            // type - The type of the node
            // key - The key to use to identify the node
            // parent - A reference to the nodes parent
            // action - The action to attribute to this node, usually a URL to link to
            if (array_key_exists('text', $properties)) {
                $this->text = $properties['text'];
            }
            if (array_key_exists('shorttext', $properties)) {
                $this->shorttext = $properties['shorttext'];
            }
            if (!array_key_exists('icon', $properties)) {
                $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
            }
            $this->icon = $properties['icon'];
            if ($this->icon instanceof pix_icon) {
                if (empty($this->icon->attributes['class'])) {
                    $this->icon->attributes['class'] = 'navicon';
                } else {
                    $this->icon->attributes['class'] .= ' navicon';
                }
            }
            if (array_key_exists('type', $properties)) {
                $this->type = $properties['type'];
            } else {
                $this->type = self::TYPE_CUSTOM;
            }
            if (array_key_exists('key', $properties)) {
                $this->key = $properties['key'];
            }
            // This needs to happen last because of the check_if_active call that occurs
            if (array_key_exists('action', $properties)) {
                $this->action = $properties['action'];
                if (is_string($this->action)) {
                    $this->action = new moodle_url($this->action);
                }
                if (self::$autofindactive) {
                    $this->check_if_active();
                }
            }
            if (array_key_exists('parent', $properties)) {
                $this->set_parent($properties['parent']);
            }
        } else if (is_string($properties)) {
            $this->text = $properties;
        }
        if ($this->text === null) {
            throw new coding_exception('You must set the text for the node when you create it.');
        }
        // Default the title to the text
        $this->title = $this->text;
        // Instantiate a new navigation node collection for this nodes children
        $this->children = new navigation_node_collection();
    }

    /**
* Checks if this node is the active node.
*
* This is determined by comparing the action for the node against the
* defined URL for the page. A match will see this node marked as active.
*
* @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
* @return bool
*/
    public function check_if_active($strength=URL_MATCH_EXACT) {
        global $FULLME, $PAGE;
        // Set fullmeurl if it hasn't already been set
        if (self::$fullmeurl == null) {
            if ($PAGE->has_set_url()) {
                self::override_active_url(new moodle_url($PAGE->url));
            } else {
                self::override_active_url(new moodle_url($FULLME));
            }
        }

        // Compare the action of this node against the fullmeurl
        if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
            $this->make_active();
            return true;
        }
        return false;
    }

    /**
* This sets the URL that the URL of new nodes get compared to when locating
* the active node.
*
* The active node is the node that matches the URL set here. By default this
* is either $PAGE->url or if that hasn't been set $FULLME.
*
* @param moodle_url $url The url to use for the fullmeurl.
*/
    public static function override_active_url(moodle_url $url) {
        // Clone the URL, in case the calling script changes their URL later.
        self::$fullmeurl = new moodle_url($url);
    }

    /**
* Creates a navigation node, ready to add it as a child using add_node
* function. (The created node needs to be added before you can use it.)
* @param string $text
* @param moodle_url|action_link $action
* @param int $type
* @param string $shorttext
* @param string|int $key
* @param pix_icon $icon
* @return navigation_node
*/
    public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
            $shorttext=null, $key=null, pix_icon $icon=null) {
        // Properties array used when creating the new navigation node
        $itemarray = array(
            'text' => $text,
            'type' => $type
        );
        // Set the action if one was provided
        if ($action!==null) {
            $itemarray['action'] = $action;
        }
        // Set the shorttext if one was provided
        if ($shorttext!==null) {
            $itemarray['shorttext'] = $shorttext;
        }
        // Set the icon if one was provided
        if ($icon!==null) {
            $itemarray['icon'] = $icon;
        }
        // Set the key
        $itemarray['key'] = $key;
        // Construct and return
        return new navigation_node($itemarray);
    }

    /**
* Adds a navigation node as a child of this node.
*
* @param string $text
* @param moodle_url|action_link $action
* @param int $type
* @param string $shorttext
* @param string|int $key
* @param pix_icon $icon
* @return navigation_node
*/
    public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
        // Create child node
        $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);

        // Add the child to end and return
        return $this->add_node($childnode);
    }

    /**
* Adds a navigation node as a child of this one, given a $node object
* created using the create function.
* @param navigation_node $childnode Node to add
* @param int|string $key The key of a node to add this before. If not
* specified, adds at end of list
* @return navigation_node The added node
*/
    public function add_node(navigation_node $childnode, $beforekey=null) {
        // First convert the nodetype for this node to a branch as it will now have children
        if ($this->nodetype !== self::NODETYPE_BRANCH) {
            $this->nodetype = self::NODETYPE_BRANCH;
        }
        // Set the parent to this node
        $childnode->set_parent($this);

        // Default the key to the number of children if not provided
        if ($childnode->key === null) {
            $childnode->key = $this->children->count();
        }

        // Add the child using the navigation_node_collections add method
        $node = $this->children->add($childnode, $beforekey);

        // If added node is a category node or the user is logged in and it's a course
        // then mark added node as a branch (makes it expandable by AJAX)
        $type = $childnode->type;
        if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
            $node->nodetype = self::NODETYPE_BRANCH;
        }
        // If this node is hidden mark it's children as hidden also
        if ($this->hidden) {
            $node->hidden = true;
        }
        // Return added node (reference returned by $this->children->add()
        return $node;
    }

    /**
* Return a list of all the keys of all the child nodes.
* @return array the keys.
*/
    public function get_children_key_list() {
        return $this->children->get_key_list();
    }

    /**
* Searches for a node of the given type with the given key.
*
* This searches this node plus all of its children, and their children....
* If you know the node you are looking for is a child of this node then please
* use the get method instead.
*
* @param int|string $key The key of the node we are looking for
* @param int $type One of navigation_node::TYPE_*
* @return navigation_node|false
*/
    public function find($key, $type) {
        return $this->children->find($key, $type);
    }

    /**
* Get ths child of this node that has the given key + (optional) type.
*
* If you are looking for a node and want to search all children + thier children
* then please use the find method instead.
*
* @param int|string $key The key of the node we are looking for
* @param int $type One of navigation_node::TYPE_*
* @return navigation_node|false
*/
    public function get($key, $type=null) {
        return $this->children->get($key, $type);
    }

    /**
* Removes this node.
*
* @return bool
*/
    public function remove() {
        return $this->parent->children->remove($this->key, $this->type);
    }

    /**
* Checks if this node has or could have any children
*
* @return bool Returns true if it has children or could have (by AJAX expansion)
*/
    public function has_children() {
        return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
    }

    /**
* Marks this node as active and forces it open.
*
* Important: If you are here because you need to mark a node active to get
* the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
* You can use it to specify a different URL to match the active navigation node on
* rather than having to locate and manually mark a node active.
*/
    public function make_active() {
        $this->isactive = true;
        $this->add_class('active_tree_node');
        $this->force_open();
        if ($this->parent !== null) {
            $this->parent->make_inactive();
        }
    }

    /**
* Marks a node as inactive and recusised back to the base of the tree
* doing the same to all parents.
*/
    public function make_inactive() {
        $this->isactive = false;
        $this->remove_class('active_tree_node');
        if ($this->parent !== null) {
            $this->parent->make_inactive();
        }
    }

    /**
* Forces this node to be open and at the same time forces open all
* parents until the root node.
*
* Recursive.
*/
    public function force_open() {
        $this->forceopen = true;
        if ($this->parent !== null) {
            $this->parent->force_open();
        }
    }

    /**
* Adds a CSS class to this node.
*
* @param string $class
* @return bool
*/
    public function add_class($class) {
        if (!in_array($class, $this->classes)) {
            $this->classes[] = $class;
        }
        return true;
    }

    /**
* Removes a CSS class from this node.
*
* @param string $class
* @return bool True if the class was successfully removed.
*/
    public function remove_class($class) {
        if (in_array($class, $this->classes)) {
            $key = array_search($class,$this->classes);
            if ($key!==false) {
                unset($this->classes[$key]);
                return true;
            }
        }
        return false;
    }

    /**
* Sets the title for this node and forces Moodle to utilise it.
* @param string $title
*/
    public function title($title) {
        $this->title = $title;
        $this->forcetitle = true;
    }

    /**
* Resets the page specific information on this node if it is being unserialised.
*/
    public function __wakeup(){
        $this->forceopen = false;
        $this->isactive = false;
        $this->remove_class('active_tree_node');
    }

    /**
* Checks if this node or any of its children contain the active node.
*
* Recursive.
*
* @return bool
*/
    public function contains_active_node() {
        if ($this->isactive) {
            return true;
        } else {
            foreach ($this->children as $child) {
                if ($child->isactive || $child->contains_active_node()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
* Finds the active node.
*
* Searches this nodes children plus all of the children for the active node
* and returns it if found.
*
* Recursive.
*
* @return navigation_node|false
*/
    public function find_active_node() {
        if ($this->isactive) {
            return $this;
        } else {
            foreach ($this->children as &$child) {
                $outcome = $child->find_active_node();
                if ($outcome !== false) {
                    return $outcome;
                }
            }
        }
        return false;
    }

    /**
* Searches all children for the best matching active node
* @return navigation_node|false
*/
    public function search_for_active_node() {
        if ($this->check_if_active(URL_MATCH_BASE)) {
            return $this;
        } else {
            foreach ($this->children as &$child) {
                $outcome = $child->search_for_active_node();
                if ($outcome !== false) {
                    return $outcome;
                }
            }
        }
        return false;
    }

    /**
* Gets the content for this node.
*
* @param bool $shorttext If true shorttext is used rather than the normal text
* @return string
*/
    public function get_content($shorttext=false) {
        if ($shorttext && $this->shorttext!==null) {
            return format_string($this->shorttext);
        } else {
            return format_string($this->text);
        }
    }

    /**
* Gets the title to use for this node.
*
* @return string
*/
    public function get_title() {
        if ($this->forcetitle || $this->action != null){
            return $this->title;
        } else {
            return '';
        }
    }

    /**
* Gets the CSS class to add to this node to describe its type
*
* @return string
*/
    public function get_css_type() {
        if (array_key_exists($this->type, $this->namedtypes)) {
            return 'type_'.$this->namedtypes[$this->type];
        }
        return 'type_unknown';
    }

    /**
* Finds all nodes that are expandable by AJAX
*
* @param array $expandable An array by reference to populate with expandable nodes.
*/
    public function find_expandable(array &$expandable) {
        foreach ($this->children as &$child) {
            if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count() == 0 && $child->display) {
                $child->id = 'expandable_branch_'.(count($expandable)+1);
                $this->add_class('canexpand');
                $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
            }
            $child->find_expandable($expandable);
        }
    }

    /**
* Finds all nodes of a given type (recursive)
*
* @param int $type On of navigation_node::TYPE_*
* @return array
*/
    public function find_all_of_type($type) {
        $nodes = $this->children->type($type);
        foreach ($this->children as &$node) {
            $childnodes = $node->find_all_of_type($type);
            $nodes = array_merge($nodes, $childnodes);
        }
        return $nodes;
    }

    /**
* Removes this node if it is empty
*/
    public function trim_if_empty() {
        if ($this->children->count() == 0) {
            $this->remove();
        }
    }

    /**
* Creates a tab representation of this nodes children that can be used
* with print_tabs to produce the tabs on a page.
*
* call_user_func_array('print_tabs', $node->get_tabs_array());
*
* @param array $inactive
* @param bool $return
* @return array Array (tabs, selected, inactive, activated, return)
*/
    public function get_tabs_array(array $inactive=array(), $return=false) {
        $tabs = array();
        $rows = array();
        $selected = null;
        $activated = array();
        foreach ($this->children as $node) {
            $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
            if ($node->contains_active_node()) {
                if ($node->children->count() > 0) {
                    $activated[] = $node->key;
                    foreach ($node->children as $child) {
                        if ($child->contains_active_node()) {
                            $selected = $child->key;
                        }
                        $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
                    }
                } else {
                    $selected = $node->key;
                }
            }
        }
        return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
    }

    /**
* Sets the parent for this node and if this node is active ensures that the tree is properly
* adjusted as well.
*
* @param navigation_node $parent
*/
    public function set_parent(navigation_node $parent) {
        // Set the parent (thats the easy part)
        $this->parent = $parent;
        // Check if this node is active (this is checked during construction)
        if ($this->isactive) {
            // Force all of the parent nodes open so you can see this node
            $this->parent->force_open();
            // Make all parents inactive so that its clear where we are.
            $this->parent->make_inactive();
        }
    }
}

/**
* Navigation node collection
*
* This class is responsible for managing a collection of navigation nodes.
* It is required because a node's unique identifier is a combination of both its
* key and its type.
*
* Originally an array was used with a string key that was a combination of the two
* however it was decided that a better solution would be to use a class that
* implements the standard IteratorAggregate interface.
*
* @package moodlecore
* @subpackage navigation
* @copyright 2010 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class navigation_node_collection implements IteratorAggregate {
    /**
* A multidimensional array to where the first key is the type and the second
* key is the nodes key.
* @var array
*/
    protected $collection = array();
    /**
* An array that contains references to nodes in the same order they were added.
* This is maintained as a progressive array.
* @var array
*/
    protected $orderedcollection = array();
    /**
* A reference to the last node that was added to the collection
* @var navigation_node
*/
    protected $last = null;
    /**
* The total number of items added to this array.
* @var int
*/
    protected $count = 0;

    /**
* Adds a navigation node to the collection
*
* @param navigation_node $node Node to add
* @param string $beforekey If specified, adds before a node with this key,
* otherwise adds at end
* @return navigation_node Added node
*/
    public function add(navigation_node $node, $beforekey=null) {
        global $CFG;
        $key = $node->key;
        $type = $node->type;

        // First check we have a 2nd dimension for this type
        if (!array_key_exists($type, $this->orderedcollection)) {
            $this->orderedcollection[$type] = array();
        }
        // Check for a collision and report if debugging is turned on
        if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
            debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
        }

        // Find the key to add before
        $newindex = $this->count;
        $last = true;
        if ($beforekey !== null) {
            foreach ($this->collection as $index => $othernode) {
                if ($othernode->key === $beforekey) {
                    $newindex = $index;
                    $last = false;
                    break;
                }
            }
            if ($newindex === $this->count) {
                debugging('Navigation node add_before: Reference node not found ' . $beforekey .
                        ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
            }
        }

        // Add the node to the appropriate place in the by-type structure (which
        // is not ordered, despite the variable name)
        $this->orderedcollection[$type][$key] = $node;
        if (!$last) {
            // Update existing references in the ordered collection (which is the
            // one that isn't called 'ordered') to shuffle them along if required
            for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
                $this->collection[$oldindex] = $this->collection[$oldindex - 1];
            }
        }
        // Add a reference to the node to the progressive collection.
        $this->collection[$newindex] = &$this->orderedcollection[$type][$key];
        // Update the last property to a reference to this new node.
        $this->last = &$this->orderedcollection[$type][$key];

        // Reorder the array by index if needed
        if (!$last) {
            ksort($this->collection);
        }
        $this->count++;
        // Return the reference to the now added node
        return $node;
    }

    /**
* Return a list of all the keys of all the nodes.
* @return array the keys.
*/
    public function get_key_list() {
        $keys = array();
        foreach ($this->collection as $node) {
            $keys[] = $node->key;
        }
        return $keys;
    }

    /**
* Fetches a node from this collection.
*
* @param string|int $key The key of the node we want to find.
* @param int $type One of navigation_node::TYPE_*.
* @return navigation_node|null
*/
    public function get($key, $type=null) {
        if ($type !== null) {
            // If the type is known then we can simply check and fetch
            if (!empty($this->orderedcollection[$type][$key])) {
                return $this->orderedcollection[$type][$key];
            }
        } else {
            // Because we don't know the type we look in the progressive array
            foreach ($this->collection as $node) {
                if ($node->key === $key) {
                    return $node;
                }
            }
        }
        return false;
    }

    /**
* Searches for a node with matching key and type.
*
* This function searches both the nodes in this collection and all of
* the nodes in each collection belonging to the nodes in this collection.
*
* Recursive.
*
* @param string|int $key The key of the node we want to find.
* @param int $type One of navigation_node::TYPE_*.
* @return navigation_node|null
*/
    public function find($key, $type=null) {
        if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
            return $this->orderedcollection[$type][$key];
        } else {
            $nodes = $this->getIterator();
            // Search immediate children first
            foreach ($nodes as &$node) {
                if ($node->key === $key && ($type === null || $type === $node->type)) {
                    return $node;
                }
            }
            // Now search each childs children
            foreach ($nodes as &$node) {
                $result = $node->children->find($key, $type);
                if ($result !== false) {
                    return $result;
                }
            }
        }
        return false;
    }

    /**
* Fetches the last node that was added to this collection
*
* @return navigation_node
*/
    public function last() {
        return $this->last;
    }

    /**
* Fetches all nodes of a given type from this collection
*/
    public function type($type) {
        if (!array_key_exists($type, $this->orderedcollection)) {
            $this->orderedcollection[$type] = array();
        }
        return $this->orderedcollection[$type];
    }
    /**
* Removes the node with the given key and type from the collection
*
* @param string|int $key
* @param int $type
* @return bool
*/
    public function remove($key, $type=null) {
        $child = $this->get($key, $type);
        if ($child !== false) {
            foreach ($this->collection as $colkey => $node) {
                if ($node->key == $key && $node->type == $type) {
                    unset($this->collection[$colkey]);
                    break;
                }
            }
            unset($this->orderedcollection[$child->type][$child->key]);
            $this->count--;
            return true;
        }
        return false;
    }

    /**
* Gets the number of nodes in this collection
*
* This option uses an internal count rather than counting the actual options to avoid
* a performance hit through the count function.
*
* @return int
*/
    public function count() {
        return $this->count;
    }
    /**
* Gets an array iterator for the collection.
*
* This is required by the IteratorAggregator interface and is used by routines
* such as the foreach loop.
*
* @return ArrayIterator
*/
    public function getIterator() {
        return new ArrayIterator($this->collection);
    }
}

/**
* The global navigation class used for... the global navigation
*
* This class is used by PAGE to store the global navigation for the site
* and is then used by the settings nav and navbar to save on processing and DB calls
*
* See
* <ul>
* <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
* <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
* </ul>
*
* @package moodlecore
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class global_navigation extends navigation_node {
    /**
* The Moodle page this navigation object belongs to.
* @var moodle_page
*/
    protected $page;
    /** @var bool */
    protected $initialised = false;
    /** @var array */
    protected $mycourses = array();
    /** @var array */
    protected $rootnodes = array();
    /** @var bool */
    protected $showemptysections = false;
    /** @var bool */
    protected $showcategories = null;
    /** @var array */
    protected $extendforuser = array();
    /** @var navigation_cache */
    protected $cache;
    /** @var array */
    protected $addedcourses = array();
    /** @var array */
    protected $addedcategories = array();
    /** @var int */
    protected $expansionlimit = 0;
    /** @var int */
    protected $useridtouseforparentchecks = 0;

    /**
* Constructs a new global navigation
*
* @param moodle_page $page The page this navigation object belongs to
*/
    public function __construct(moodle_page $page) {
        global $CFG, $SITE, $USER;

        if (during_initial_install()) {
            return;
        }

        if (get_home_page() == HOMEPAGE_SITE) {
            // We are using the site home for the root element
            $properties = array(
                'key' => 'home',
                'type' => navigation_node::TYPE_SYSTEM,
                'text' => get_string('home'),
                'action' => new moodle_url('/')
            );
        } else {
            // We are using the users my moodle for the root element
            $properties = array(
                'key' => 'myhome',
                'type' => navigation_node::TYPE_SYSTEM,
                'text' => get_string('myhome'),
                'action' => new moodle_url('/my/')
            );
        }

        // Use the parents consturctor.... good good reuse
        parent::__construct($properties);

        // Initalise and set defaults
        $this->page = $page;
        $this->forceopen = true;
        $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
    }

    /**
* Mutator to set userid to allow parent to see child's profile
* page navigation. See MDL-25805 for initial issue. Linked to it
* is an issue explaining why this is a REALLY UGLY HACK thats not
* for you to use!
*
* @param int $userid userid of profile page that parent wants to navigate around.
*/
    public function set_userid_for_parent_checks($userid) {
        $this->useridtouseforparentchecks = $userid;
    }


    /**
* Initialises the navigation object.
*
* This causes the navigation object to look at the current state of the page
* that it is associated with and then load the appropriate content.
*
* This should only occur the first time that the navigation structure is utilised
* which will normally be either when the navbar is called to be displayed or
* when a block makes use of it.
*
* @return bool
*/
    public function initialise() {
        global $CFG, $SITE, $USER, $DB;
        // Check if it has alread been initialised
        if ($this->initialised || during_initial_install()) {
            return true;
        }
        $this->initialised = true;

        // Set up the five base root nodes. These are nodes where we will put our
        // content and are as follows:
        // site: Navigation for the front page.
        // myprofile: User profile information goes here.
        // mycourses: The users courses get added here.
        // courses: Additional courses are added here.
        // users: Other users information loaded here.
        $this->rootnodes = array();
        if (get_home_page() == HOMEPAGE_SITE) {
            // The home element should be my moodle because the root element is the site
            if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
                $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
            }
        } else {
            // The home element should be the site because the root node is my moodle
            $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
            if ($CFG->defaulthomepage == HOMEPAGE_MY) {
                // We need to stop automatic redirection
                $this->rootnodes['home']->action->param('redirect', '0');
            }
        }
        $this->rootnodes['site'] = $this->add_course($SITE);
        $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
        $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
        $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
        $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');

        // Fetch all of the users courses.
        $limit = 20;
        if (!empty($CFG->navcourselimit)) {
            $limit = $CFG->navcourselimit;
        }

        $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
        $showallcourses = (count($mycourses) == 0 || !empty($CFG->navshowallcourses));
        $showcategories = ($showallcourses && $this->show_categories());
        $issite = ($this->page->course->id == SITEID);
        $ismycourse = (array_key_exists($this->page->course->id, $mycourses));

        // Check if any courses were returned.
        if (count($mycourses) > 0) {
            // Add all of the users courses to the navigation
            foreach ($mycourses as $course) {
                $course->coursenode = $this->add_course($course, false, true);
            }
        }

        if ($showallcourses) {
            // Load all courses
            $this->load_all_courses();
        }

        // We always load the frontpage course to ensure it is available without
        // JavaScript enabled.
        $frontpagecourse = $this->load_course($SITE);
        $this->add_front_page_course_essentials($frontpagecourse, $SITE);
        $this->load_course_sections($SITE, $frontpagecourse);

        $canviewcourseprofile = true;

        if (!$issite) {
            // Next load context specific content into the navigation
            switch ($this->page->context->contextlevel) {
                case CONTEXT_SYSTEM :
                    // This has already been loaded we just need to map the variable
                    $coursenode = $frontpagecourse;
                    $this->load_all_categories(null, $showcategories);
                    break;
                case CONTEXT_COURSECAT :
                    // This has already been loaded we just need to map the variable
                    $coursenode = $frontpagecourse;
                    $this->load_all_categories($this->page->context->instanceid, $showcategories);
                    break;
                case CONTEXT_BLOCK :
                case CONTEXT_COURSE :
                    // Load the course associated with the page into the navigation
                    $course = $this->page->course;
                    if ($showcategories && !$ismycourse) {
                        $this->load_all_categories($course->category, $showcategories);
                    }
                    $coursenode = $this->load_course($course);

                    // If the course wasn't added then don't try going any further.
                    if (!$coursenode) {
                        $canviewcourseprofile = false;
                        break;
                    }

                    // If the user is not enrolled then we only want to show the
                    // course node and not populate it.

                    // Not enrolled, can't view, and hasn't switched roles
                    if (!can_access_course($course)) {
                        // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
                        // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
                        $isparent = false;
                        if ($this->useridtouseforparentchecks) {
                            if ($this->useridtouseforparentchecks != $USER->id) {
                                $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST);
                                if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))
                                        and has_capability('moodle/user:viewdetails', $usercontext)) {
                                    $isparent = true;
                                }
                            }
                        }

                        if (!$isparent) {
                            $coursenode->make_active();
                            $canviewcourseprofile = false;
                            break;
                        }
                    }
                    // Add the essentials such as reports etc...
                    $this->add_course_essentials($coursenode, $course);
                    if ($this->format_display_course_content($course->format)) {
                        // Load the course sections
                        $sections = $this->load_course_sections($course, $coursenode);
                    }
                    if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
                        $coursenode->make_active();
                    }
                    break;
                case CONTEXT_MODULE :
                    $course = $this->page->course;
                    $cm = $this->page->cm;

                    if ($showcategories && !$ismycourse) {
                        $this->load_all_categories($course->category, $showcategories);
                    }

                    // Load the course associated with the page into the navigation
                    $coursenode = $this->load_course($course);

                    // If the course wasn't added then don't try going any further.
                    if (!$coursenode) {
                        $canviewcourseprofile = false;
                        break;
                    }

                    // If the user is not enrolled then we only want to show the
                    // course node and not populate it.
                    if (!can_access_course($course)) {
                        $coursenode->make_active();
                        $canviewcourseprofile = false;
                        break;
                    }

                    $this->add_course_essentials($coursenode, $course);
                    // Load the course sections into the page
                    $sections = $this->load_course_sections($course, $coursenode);
                    if ($course->id != SITEID) {
                        // Find the section for the $CM associated with the page and collect
                        // its section number.
                        if (isset($cm->sectionnum)) {
                            $cm->sectionnumber = $cm->sectionnum;
                        } else {
                            foreach ($sections as $section) {
                                if ($section->id == $cm->section) {
                                    $cm->sectionnumber = $section->section;
                                    break;
                                }
                            }
                        }

                        // Load all of the section activities for the section the cm belongs to.
                        if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
                            list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
                            $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray);
                        } else {
                            $activities = array();
                            if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
                                // "stealth" activity from unavailable section
                                $activities[$cm->id] = $activity;
                            }
                        }
                    } else {
                        $activities = array();
                        $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
                    }
                    if (!empty($activities[$cm->id])) {
                        // Finally load the cm specific navigaton information
                        $this->load_activity($cm, $course, $activities[$cm->id]);
                        // Check if we have an active ndoe
                        if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
                            // And make the activity node active.
                            $activities[$cm->id]->make_active();
                        }
                    } else {
                        //TODO: something is wrong, what to do? (Skodak)
                    }
                    break;
                case CONTEXT_USER :
                    $course = $this->page->course;
                    if ($showcategories && !$ismycourse) {
                        $this->load_all_categories($course->category, $showcategories);
                    }
                    // Load the course associated with the user into the navigation
                    $coursenode = $this->load_course($course);

                    // If the course wasn't added then don't try going any further.
                    if (!$coursenode) {
                        $canviewcourseprofile = false;
                        break;
                    }

                    // If the user is not enrolled then we only want to show the
                    // course node and not populate it.
                    if (!can_access_course($course)) {
                        $coursenode->make_active();
                        $canviewcourseprofile = false;
                        break;
                    }
                    $this->add_course_essentials($coursenode, $course);
                    $sections = $this->load_course_sections($course, $coursenode);
                    break;
            }
        } else {
            // We need to check if the user is viewing a front page module.
            // If so then there is potentially more content to load yet for that
            // module.
            if ($this->page->context->contextlevel == CONTEXT_MODULE) {
                $activitynode = $this->rootnodes['site']->get($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
                if ($activitynode) {
                    $this->load_activity($this->page->cm, $this->page->course, $activitynode);
                }
            }
        }

        $limit = 20;
        if (!empty($CFG->navcourselimit)) {
            $limit = $CFG->navcourselimit;
        }
        if ($showcategories) {
            $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
            foreach ($categories as &$category) {
                if ($category->children->count() >= $limit) {
                    $url = new moodle_url('/course/category.php', array('id'=>$category->key));
                    $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
                }
            }
        } else if ($this->rootnodes['courses']->children->count() >= $limit) {
            $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
        }

        // Load for the current user
        $this->load_for_user();
        if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
            $this->load_for_user(null, true);
        }
        // Load each extending user into the navigation.
        foreach ($this->extendforuser as $user) {
            if ($user->id != $USER->id) {
                $this->load_for_user($user);
            }
        }

        // Give the local plugins a chance to include some navigation if they want.
        foreach (get_list_of_plugins('local') as $plugin) {
            if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
                continue;
            }
            require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
            $function = $plugin.'_extends_navigation';
            if (function_exists($function)) {
                $function($this);
            }
        }

        // Remove any empty root nodes
        foreach ($this->rootnodes as $node) {
            // Dont remove the home node
            if ($node->key !== 'home' && !$node->has_children()) {
                $node->remove();
            }
        }

        if (!$this->contains_active_node()) {
            $this->search_for_active_node();
        }

        // If the user is not logged in modify the navigation structure as detailed
        // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
        if (!isloggedin()) {
            $activities = clone($this->rootnodes['site']->children);
            $this->rootnodes['site']->remove();
            $children = clone($this->children);
            $this->children = new navigation_node_collection();
            foreach ($activities as $child) {
                $this->children->add($child);
            }
            foreach ($children as $child) {
                $this->children->add($child);
            }
        }
        return true;
    }

    /**
* Returns true is courses should be shown within categories on the navigation.
*
* @return bool
*/
    protected function show_categories() {
        global $CFG, $DB;
        if ($this->showcategories === null) {
            $this->showcategories = !empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1;
        }
        return $this->showcategories;
    }

    /**
* Checks the course format to see whether it wants the navigation to load
* additional information for the course.
*
* This function utilises a callback that can exist within the course format lib.php file
* The callback should be a function called:
* callback_{formatname}_display_content()
* It doesn't get any arguments and should return true if additional content is
* desired. If the callback doesn't exist we assume additional content is wanted.
*
* @param string $format The course format
* @return bool
*/
    protected function format_display_course_content($format) {
        global $CFG;
        $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
        if (file_exists($formatlib)) {
            require_once($formatlib);
            $displayfunc = 'callback_'.$format.'_display_content';
            if (function_exists($displayfunc) && !$displayfunc()) {
                return $displayfunc();
            }
        }
        return true;
    }

    /**
* Loads of the the courses in Moodle into the navigation.
*
* @global moodle_database $DB
* @param string|array $categoryids Either a string or array of category ids to load courses for
* @return array An array of navigation_node
*/
    protected function load_all_courses($categoryids=null) {
        global $CFG, $DB, $USER;

        if ($categoryids !== null) {
            if (is_array($categoryids)) {
                list ($categoryselect, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'catid');
            } else {
                $categoryselect = '= :categoryid';
                $params = array('categoryid', $categoryids);
            }
            $params['siteid'] = SITEID;
            $categoryselect = ' AND c.category '.$categoryselect;
        } else {
            $params = array('siteid' => SITEID);
            $categoryselect = '';
        }

        list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
        list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses) + array(SITEID), SQL_PARAMS_NAMED, 'lcourse', false);
        $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category, cat.path AS categorypath $ccselect
FROM {course} c
$ccjoin
LEFT JOIN {course_categories} cat ON cat.id=c.category
WHERE c.id {$courseids} {$categoryselect}
ORDER BY c.sortorder ASC";
        $limit = 20;
        if (!empty($CFG->navcourselimit)) {
            $limit = $CFG->navcourselimit;
        }
        $courses = $DB->get_records_sql($sql, $params + $courseparams, 0, $limit);

        $coursenodes = array();
        foreach ($courses as $course) {
            context_instance_preload($course);
            $coursenodes[$course->id] = $this->add_course($course);
        }
        return $coursenodes;
    }

    /**
* Loads all categories (top level or if an id is specified for that category)
*
* @param int $categoryid The category id to load or null/0 to load all base level categories
* @param bool $showbasecategories If set to true all base level categories will be loaded as well
* as the requested category and any parent categories.
* @return void
*/
    protected function load_all_categories($categoryid = null, $showbasecategories = false) {
        global $DB;

        // Check if this category has already been loaded
        if ($categoryid !== null && array_key_exists($categoryid, $this->addedcategories) && $this->addedcategories[$categoryid]->children->count() > 0) {
            return $this->addedcategories[$categoryid];
        }

        $coursestoload = array();
        if (empty($categoryid)) { // can be 0
            // We are going to load all of the first level categories (categories without parents)
            $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder ASC, id ASC');
        } else if (array_key_exists($categoryid, $this->addedcategories)) {
            // The category itself has been loaded already so we just need to ensure its subcategories
            // have been loaded
            list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
            if ($showbasecategories) {
                // We need to include categories with parent = 0 as well
                $sql = "SELECT *
FROM {course_categories} cc
WHERE (parent = :categoryid OR parent = 0) AND
parent {$sql}
ORDER BY depth DESC, sortorder ASC, id ASC";
            } else {
                $sql = "SELECT *
FROM {course_categories} cc
WHERE parent = :categoryid AND
parent {$sql}
ORDER BY depth DESC, sortorder ASC, id ASC";
            }
            $params['categoryid'] = $categoryid;
            $categories = $DB->get_records_sql($sql, $params);
            if (count($categories) == 0) {
                // There are no further categories that require loading.
                return;
            }
        } else {
            // This category hasn't been loaded yet so we need to fetch it, work out its category path
            // and load this category plus all its parents and subcategories
            $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
            $coursestoload = explode('/', trim($category->path, '/'));
            list($select, $params) = $DB->get_in_or_equal($coursestoload);
            $select = 'id '.$select.' OR parent '.$select;
            if ($showbasecategories) {
                $select .= ' OR parent = 0';
            }
            $params = array_merge($params, $params);
            $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
        }

        // Now we have an array of categories we need to add them to the navigation.
        while (!empty($categories)) {
            $category = reset($categories);
            if (array_key_exists($category->id, $this->addedcategories)) {
                // Do nothing
            } else if ($category->parent == '0') {
                $this->add_category($category, $this->rootnodes['courses']);
            } else if (array_key_exists($category->parent, $this->addedcategories)) {
                $this->add_category($category, $this->addedcategories[$category->parent]);
            } else {
                // This category isn't in the navigation and niether is it's parent (yet).
                // We need to go through the category path and add all of its components in order.
                $path = explode('/', trim($category->path, '/'));
                foreach ($path as $catid) {
                    if (!array_key_exists($catid, $this->addedcategories)) {
                        // This category isn't in the navigation yet so add it.
                        $subcategory = $categories[$catid];
                        if ($subcategory->parent == '0') {
                            // Yay we have a root category - this likely means we will now be able
                            // to add categories without problems.
                            $this->add_category($subcategory, $this->rootnodes['courses']);
                        } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
                            // The parent is in the category (as we'd expect) so add it now.
                            $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
                            // Remove the category from the categories array.
                            unset($categories[$catid]);
                        } else {
                            // We should never ever arrive here - if we have then there is a bigger
                            // problem at hand.
                            throw new coding_exception('Category path order is incorrect and/or there are missing categories');
                        }
                    }
                }
            }
            // Remove the category from the categories array now that we know it has been added.
            unset($categories[$category->id]);
        }
        // Check if there are any categories to load.
        if (count($coursestoload) > 0) {
            $this->load_all_courses($coursestoload);
        }
    }

    /**
* Adds a structured category to the navigation in the correct order/place
*
* @param stdClass $category
* @param navigation_node $parent
*/
    protected function add_category(stdClass $category, navigation_node $parent) {
        if (array_key_exists($category->id, $this->addedcategories)) {
            return;
        }
        $url = new moodle_url('/course/category.php', array('id' => $category->id));
        $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
        $categoryname = format_string($category->name, true, array('context' => $context));
        $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id);
        if (empty($category->visible)) {
            if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
                $categorynode->hidden = true;
            } else {
                $categorynode->display = false;
            }
        }
        $this->addedcategories[$category->id] = &$categorynode;
    }

    /**
* Loads the given course into the navigation
*
* @param stdClass $course
* @return navigation_node
*/
    protected function load_course(stdClass $course) {
        if ($course->id == SITEID) {
            return $this->rootnodes['site'];
        } else if (array_key_exists($course->id, $this->addedcourses)) {
            return $this->addedcourses[$course->id];
        } else {
            return $this->add_course($course);
        }
    }

    /**
* Loads all of the courses section into the navigation.
*
* This function utilisies a callback that can be implemented within the course
* formats lib.php file to customise the navigation that is generated at this
* point for the course.
*
* By default (if not defined) the method {@see load_generic_course_sections} is
* called instead.
*
* @param stdClass $course Database record for the course
* @param navigation_node $coursenode The course node within the navigation
* @return array Array of navigation nodes for the section with key = section id
*/
    protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
        global $CFG;
        $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
        $structurefunc = 'callback_'.$course->format.'_load_content';
        if (function_exists($structurefunc)) {
            return $structurefunc($this, $course, $coursenode);
        } else if (file_exists($structurefile)) {
            require_once $structurefile;
            if (function_exists($structurefunc)) {
                return $structurefunc($this, $course, $coursenode);
            } else {
                return $this->load_generic_course_sections($course, $coursenode);
            }
        } else {
            return $this->load_generic_course_sections($course, $coursenode);
        }
    }

    /**
* Generates an array of sections and an array of activities for the given course.
*
* This method uses the cache to improve performance and avoid the get_fast_modinfo call
*
* @param stdClass $course
* @return array Array($sections, $activities)
*/
    protected function generate_sections_and_activities(stdClass $course) {
        global $CFG;
        require_once($CFG->dirroot.'/course/lib.php');

        if (!$this->cache->cached('course_sections_'.$course->id) || !$this->cache->cached('course_activites_'.$course->id)) {
            $modinfo = get_fast_modinfo($course);
            $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);

            $activities = array();

            foreach ($sections as $key => $section) {
                $sections[$key]->hasactivites = false;
                if (!array_key_exists($section->section, $modinfo->sections)) {
                    continue;
                }
                foreach ($modinfo->sections[$section->section] as $cmid) {
                    $cm = $modinfo->cms[$cmid];
                    if (!$cm->uservisible) {
                        continue;
                    }
                    $activity = new stdClass;
                    $activity->section = $section->section;
                    $activity->name = $cm->name;
                    $activity->icon = $cm->icon;
                    $activity->iconcomponent = $cm->iconcomponent;
                    $activity->id = $cm->id;
                    $activity->hidden = (!$cm->visible);
                    $activity->modname = $cm->modname;
                    $activity->nodetype = navigation_node::NODETYPE_LEAF;
                    $activity->onclick = $cm->get_on_click();
                    $url = $cm->get_url();
                    if (!$url) {
                        $activity->url = null;
                        $activity->display = false;
                    } else {
                        $activity->url = $cm->get_url()->out();
                        $activity->display = true;
                        if (self::module_extends_navigation($cm->modname)) {
                            $activity->nodetype = navigation_node::NODETYPE_BRANCH;
                        }
                    }
                    $activities[$cmid] = $activity;
                    $sections[$key]->hasactivites = true;
                }
            }
            $this->cache->set('course_sections_'.$course->id, $sections);
            $this->cache->set('course_activites_'.$course->id, $activities);
        } else {
            $sections = $this->cache->{'course_sections_'.$course->id};
            $activities = $this->cache->{'course_activites_'.$course->id};
        }
        return array($sections, $activities);
    }

    /**
* Generically loads the course sections into the course's navigation.
*
* @param stdClass $course
* @param navigation_node $coursenode
* @param string $courseformat The course format
* @return array An array of course section nodes
*/
    public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
        global $CFG, $DB, $USER;
        require_once($CFG->dirroot.'/course/lib.php');

        list($sections, $activities) = $this->generate_sections_and_activities($course);

        $namingfunction = 'callback_'.$courseformat.'_get_section_name';
        $namingfunctionexists = (function_exists($namingfunction));

        $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);

        $urlfunction = 'callback_'.$courseformat.'_get_section_url';
        if (empty($CFG->navlinkcoursesections) || !function_exists($urlfunction)) {
            $urlfunction = null;
        }

        $keyfunction = 'callback_'.$courseformat.'_request_key';
        $key = course_get_display($course->id);
        if (defined('AJAX_SCRIPT') && AJAX_SCRIPT == '0' && function_exists($keyfunction) && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
            $key = optional_param($keyfunction(), $key, PARAM_INT);
        }

        $navigationsections = array();
        foreach ($sections as $sectionid => $section) {
            $section = clone($section);
            if ($course->id == SITEID) {
                $this->load_section_activities($coursenode, $section->section, $activities);
            } else {
                if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !$section->hasactivites)) {
                    continue;
                }
                if ($namingfunctionexists) {
                    $sectionname = $namingfunction($course, $section, $sections);
                } else {
                    $sectionname = get_string('section').' '.$section->section;
                }

                $url = null;
                if (!empty($urlfunction)) {
                    $url = $urlfunction($course->id, $section->section);
                }
                $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
                $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
                $sectionnode->hidden = (!$section->visible);
                if ($key != '0' && $section->section != '0' && $section->section == $key && $this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites) {
                    $sectionnode->make_active();
                    $this->load_section_activities($sectionnode, $section->section, $activities);
                }
                $section->sectionnode = $sectionnode;
                $navigationsections[$sectionid] = $section;
            }
        }
        return $navigationsections;
    }
    /**
* Loads all of the activities for a section into the navigation structure.
*
* @todo 2.2 - $activities should always be an array and we should no longer check for it being a
* course_modinfo object
*
* @param navigation_node $sectionnode
* @param int $sectionnumber
* @param course_modinfo $modinfo Object returned from {@see get_fast_modinfo()}
* @return array Array of activity nodes
*/
    protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $activities) {
        // A static counter for JS function naming
        static $legacyonclickcounter = 0;

        if ($activities instanceof course_modinfo) {
            debugging('global_navigation::load_section_activities argument 3 should now recieve an array of activites. See that method for an example.', DEBUG_DEVELOPER);
            list($sections, $activities) = $this->generate_sections_and_activities($activities->course);
        }

        $activitynodes = array();
        foreach ($activities as $activity) {
            if ($activity->section != $sectionnumber) {
                continue;
            }
            if ($activity->icon) {
                $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
            } else {
                $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
            }

            // Prepare the default name and url for the node
            $activityname = format_string($activity->name, true, array('context' => get_context_instance(CONTEXT_MODULE, $activity->id)));
            $action = new moodle_url($activity->url);

            // Check if the onclick property is set (puke!)
            if (!empty($activity->onclick)) {
                // Increment the counter so that we have a unique number.
                $legacyonclickcounter++;
                // Generate the function name we will use
                $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
                $propogrationhandler = '';
                // Check if we need to cancel propogation. Remember inline onclick
                // events would return false if they wanted to prevent propogation and the
                // default action.
                if (strpos($activity->onclick, 'return false')) {
                    $propogrationhandler = 'e.halt();';
                }
                // Decode the onclick - it has already been encoded for display (puke)
                $onclick = htmlspecialchars_decode($activity->onclick);
                // Build the JS function the click event will call
                $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
                $this->page->requires->js_init_code($jscode);
                // Override the default url with the new action link
                $action = new action_link($action, $activityname, new component_action('click', $functionname));
            }

            $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
            $activitynode->title(get_string('modulename', $activity->modname));
            $activitynode->hidden = $activity->hidden;
            $activitynode->display = $activity->display;
            $activitynode->nodetype = $activity->nodetype;
            $activitynodes[$activity->id] = $activitynode;
        }

        return $activitynodes;
    }
    /**
* Loads a stealth module from unavailable section
* @param navigation_node $coursenode
* @param stdClass $modinfo
* @return navigation_node or null if not accessible
*/
    protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
        if (empty($modinfo->cms[$this->page->cm->id])) {
            return null;
        }
        $cm = $modinfo->cms[$this->page->cm->id];
        if (!$cm->uservisible) {
            return null;
        }
        if ($cm->icon) {
            $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
        } else {
            $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
        }
        $url = $cm->get_url();
        $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
        $activitynode->title(get_string('modulename', $cm->modname));
        $activitynode->hidden = (!$cm->visible);
        if (!$url) {
            // Don't show activities that don't have links!
            $activitynode->display = false;
        } else if (self::module_extends_navigation($cm->modname)) {
            $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
        }
        return $activitynode;
    }
    /**
* Loads the navigation structure for the given activity into the activities node.
*
* This method utilises a callback within the modules lib.php file to load the
* content specific to activity given.
*
* The callback is a method: {modulename}_extend_navigation()
* Examples:
* * {@see forum_extend_navigation()}
* * {@see workshop_extend_navigation()}
*
* @param cm_info|stdClass $cm
* @param stdClass $course
* @param navigation_node $activity
* @return bool
*/
    protected function load_activity($cm, stdClass $course, navigation_node $activity) {
        global $CFG, $DB;

        // make sure we have a $cm from get_fast_modinfo as this contains activity access details
        if (!($cm instanceof cm_info)) {
            $modinfo = get_fast_modinfo($course);
            $cm = $modinfo->get_cm($cm->id);
        }

        $activity->make_active();
        $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
        $function = $cm->modname.'_extend_navigation';

        if (file_exists($file)) {
            require_once($file);
            if (function_exists($function)) {
                $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
                $function($activity, $course, $activtyrecord, $cm);
                return true;
            }
        }
        $activity->nodetype = navigation_node::NODETYPE_LEAF;
        return false;
    }
    /**
* Loads user specific information into the navigation in the appropriate place.
*
* If no user is provided the current user is assumed.
*
* @param stdClass $user
* @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
* @return bool
*/
    protected function load_for_user($user=null, $forceforcontext=false) {
        global $DB, $CFG, $USER;

        if ($user === null) {
            // We can't require login here but if the user isn't logged in we don't
            // want to show anything
            if (!isloggedin() || isguestuser()) {
                return false;
            }
            $user = $USER;
        } else if (!is_object($user)) {
            // If the user is not an object then get them from the database
            list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
            $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
            $user = $DB->get_record_sql($sql, array('userid' => (int)$user), MUST_EXIST);
            context_instance_preload($user);
        }

        $iscurrentuser = ($user->id == $USER->id);

        $usercontext = get_context_instance(CONTEXT_USER, $user->id);

        // Get the course set against the page, by default this will be the site
        $course = $this->page->course;
        $baseargs = array('id'=>$user->id);
        if ($course->id != SITEID && (!$iscurrentuser || $forceforcontext)) {
            $coursenode = $this->load_course($course);
            $baseargs['course'] = $course->id;
            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
            $issitecourse = false;
        } else {
            // Load all categories and get the context for the system
            $coursecontext = get_context_instance(CONTEXT_SYSTEM);
            $issitecourse = true;
        }

        // Create a node to add user information under.
        if ($iscurrentuser && !$forceforcontext) {
            // If it's the current user the information will go under the profile root node
            $usernode = $this->rootnodes['myprofile'];
            $course = get_site();
            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
            $issitecourse = true;
        } else {
            if (!$issitecourse) {
                // Not the current user so add it to the participants node for the current course
                $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
                $userviewurl = new moodle_url('/user/view.php', $baseargs);
            } else {
                // This is the site so add a users node to the root branch
                $usersnode = $this->rootnodes['users'];
                if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
                    $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
                }
                $userviewurl = new moodle_url('/user/profile.php', $baseargs);
            }
            if (!$usersnode) {
                // We should NEVER get here, if the course hasn't been populated
                // with a participants node then the navigaiton either wasn't generated
                // for it (you are missing a require_login or set_context call) or
                // you don't have access.... in the interests of no leaking informatin
                // we simply quit...
                return false;
            }
            // Add a branch for the current user
            $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);

            if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
                $usernode->make_active();
            }
        }

        // If the user is the current user or has permission to view the details of the requested
        // user than add a view profile link.
        if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
            if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
                $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
            } else {
                $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
            }
        }

        if (!empty($CFG->navadduserpostslinks)) {
            // Add nodes for forum posts and discussions if the user can view either or both
            // There are no capability checks here as the content of the page is based
            // purely on the forums the current user has access too.
            $forumtab = $usernode->add(get_string('forumposts', 'forum'));
            $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
            $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
        }

        // Add blog nodes
        if (!empty($CFG->bloglevel)) {
            if (!$this->cache->cached('userblogoptions'.$user->id)) {
                require_once($CFG->dirroot.'/blog/lib.php');
                // Get all options for the user
                $options = blog_get_options_for_user($user);
                $this->cache->set('userblogoptions'.$user->id, $options);
            } else {
                $options = $this->cache->{'userblogoptions'.$user->id};
            }

            if (count($options) > 0) {
                $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                foreach ($options as $type => $option) {
                    if ($type == "rss") {
                        $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                    } else {
                        $blogs->add($option['string'], $option['link']);
                    }
                }
            }
        }

        if (!empty($CFG->messaging)) {
            $messageargs = null;
            if ($USER->id!=$user->id) {
                $messageargs = array('id'=>$user->id);
            }
            $url = new moodle_url('/message/index.php',$messageargs);
            $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
        }

        $context = get_context_instance(CONTEXT_USER, $USER->id);
        if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
            $url = new moodle_url('/user/files.php');
            $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
        }

        // Add a node to view the users notes if permitted
        if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
            $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
            if ($coursecontext->instanceid) {
                $url->param('course', $coursecontext->instanceid);
            }
            $usernode->add(get_string('notes', 'notes'), $url);
        }

        // Add reports node
        $reporttab = $usernode->add(get_string('activityreports'));
        $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
        foreach ($reports as $reportfunction) {
            $reportfunction($reporttab, $user, $course);
        }
        $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
        if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
            // Add grade hardcoded grade report if necessary
            $gradeaccess = false;
            if (has_capability('moodle/grade:viewall', $coursecontext)) {
                //ok - can view all course grades
                $gradeaccess = true;
            } else if ($course->showgrades) {
                if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
                    //ok - can view own grades
                    $gradeaccess = true;
                } else if (has_capability('moodle/grade:viewall', $usercontext)) {
                    // ok - can view grades of this user - parent most probably
                    $gradeaccess = true;
                } else if ($anyreport) {
                    // ok - can view grades of this user - parent most probably
                    $gradeaccess = true;
                }
            }
            if ($gradeaccess) {
                $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id, 'user'=>$usercontext->instanceid)));
            }
        }
        // Check the number of nodes in the report node... if there are none remove the node
        $reporttab->trim_if_empty();

        // If the user is the current user add the repositories for the current user
        $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
        if ($iscurrentuser) {
            if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
                require_once($CFG->dirroot . '/repository/lib.php');
                $editabletypes = repository::get_editable_types($usercontext);
                $haseditabletypes = !empty($editabletypes);
                unset($editabletypes);
                $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
            } else {
                $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
            }
            if ($haseditabletypes) {
                $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
            }
        } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {

            // Add view grade report is permitted
            $reports = get_plugin_list('gradereport');
            arsort($reports); // user is last, we want to test it first

            $userscourses = enrol_get_users_courses($user->id);
            $userscoursesnode = $usernode->add(get_string('courses'));

            foreach ($userscourses as $usercourse) {
                $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
                $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
                $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);

                $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
                if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
                    foreach ($reports as $plugin => $plugindir) {
                        if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
                            //stop when the first visible plugin is found
                            $gradeavailable = true;
                            break;
                        }
                    }
                }

                if ($gradeavailable) {
                    $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
                    $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
                }

                // Add a node to view the users notes if permitted
                if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
                    $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
                    $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
                }

                if (can_access_course($usercourse, $user->id)) {
                    $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
                }

                $reporttab = $usercoursenode->add(get_string('activityreports'));

                $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
                foreach ($reports as $reportfunction) {
                    $reportfunction($reporttab, $user, $usercourse);
                }

                $reporttab->trim_if_empty();
            }
        }
        return true;
    }

    /**
* This method simply checks to see if a given module can extend the navigation.
*
* TODO: A shared caching solution should be used to save details on what extends navigation
*
* @param string $modname
* @return bool
*/
    protected static function module_extends_navigation($modname) {
        global $CFG;
        static $extendingmodules = array();
        if (!array_key_exists($modname, $extendingmodules)) {
            $extendingmodules[$modname] = false;
            $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
            if (file_exists($file)) {
                $function = $modname.'_extend_navigation';
                require_once($file);
                $extendingmodules[$modname] = (function_exists($function));
            }
        }
        return $extendingmodules[$modname];
    }
    /**
* Extends the navigation for the given user.
*
* @param stdClass $user A user from the database
*/
    public function extend_for_user($user) {
        $this->extendforuser[] = $user;
    }

    /**
* Returns all of the users the navigation is being extended for
*
* @return array
*/
    public function get_extending_users() {
        return $this->extendforuser;
    }
    /**
* Adds the given course to the navigation structure.
*
* @param stdClass $course
* @return navigation_node
*/
    public function add_course(stdClass $course, $forcegeneric = false, $ismycourse = false) {
        global $CFG;

        // We found the course... we can return it now :)
        if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
            return $this->addedcourses[$course->id];
        }

        $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);

        if ($course->id != SITEID && !$course->visible) {
            if (is_role_switched($course->id)) {
                // user has to be able to access course in order to switch, let's skip the visibility test here
            } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                return false;
            }
        }

        $issite = ($course->id == SITEID);
        $ismycourse = ($ismycourse && !$forcegeneric);
        $shortname = format_string($course->shortname, true, array('context' => $coursecontext));

        if ($issite) {
            $parent = $this;
            $url = null;
            if (empty($CFG->usesitenameforsitepages)) {
                $shortname = get_string('sitepages');
            }
        } else if ($ismycourse) {
            $parent = $this->rootnodes['mycourses'];
            $url = new moodle_url('/course/view.php', array('id'=>$course->id));
        } else {
            $parent = $this->rootnodes['courses'];
            $url = new moodle_url('/course/view.php', array('id'=>$course->id));
        }

        if (!$ismycourse && !$issite && !empty($course->category)) {
            if ($this->show_categories()) {
                // We need to load the category structure for this course
                $this->load_all_categories($course->category);
            }
            if (array_key_exists($course->category, $this->addedcategories)) {
                $parent = $this->addedcategories[$course->category];
                // This could lead to the course being created so we should check whether it is the case again
                if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
                    return $this->addedcourses[$course->id];
                }
            }
        }

        $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
        $coursenode->nodetype = self::NODETYPE_BRANCH;
        $coursenode->hidden = (!$course->visible);
        $coursenode->title(format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
        if (!$forcegeneric) {
            $this->addedcourses[$course->id] = &$coursenode;
        }
        if ($ismycourse && !empty($CFG->navshowallcourses)) {
            // We need to add this course to the general courses node as well as the
            // my courses node, rerun the function with the kill param
            $genericcourse = $this->add_course($course, true);
            if ($genericcourse->isactive) {
                $genericcourse->make_inactive();
                $genericcourse->collapse = true;
                if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
                    $parent = $genericcourse->parent;
                    while ($parent && $parent->type == self::TYPE_CATEGORY) {
                        $parent->collapse = true;
                        $parent = $parent->parent;
                    }
                }
            }
        }

        return $coursenode;
    }
    /**
* Adds essential course nodes to the navigation for the given course.
*
* This method adds nodes such as reports, blogs and participants
*
* @param navigation_node $coursenode
* @param stdClass $course
* @return bool
*/
    public function add_course_essentials($coursenode, stdClass $course) {
        global $CFG;

        if ($course->id == SITEID) {
            return $this->add_front_page_course_essentials($coursenode, $course);
        }

        if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
            return true;
        }

        //Participants
        if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
            $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
            $currentgroup = groups_get_course_group($course, true);
            if ($course->id == SITEID) {
                $filterselect = '';
            } else if ($course->id && !$currentgroup) {
                $filterselect = $course->id;
            } else {
                $filterselect = $currentgroup;
            }
            $filterselect = clean_param($filterselect, PARAM_INT);
            if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
               and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
                $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
                $participants->add(get_string('blogs','blog'), $blogsurls->out());
            }
            if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
                $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
            }
        } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
            $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
        }

        // View course reports
        if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
            $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
            $coursereports = get_plugin_list('coursereport'); // deprecated
            foreach ($coursereports as $report=>$dir) {
                $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
                if (file_exists($libfile)) {
                    require_once($libfile);
                    $reportfunction = $report.'_report_extend_navigation';
                    if (function_exists($report.'_report_extend_navigation')) {
                        $reportfunction($reportnav, $course, $this->page->context);
                    }
                }
            }

            $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
            foreach ($reports as $reportfunction) {
                $reportfunction($reportnav, $course, $this->page->context);
            }
        }
        return true;
    }
    /**
* This generates the the structure of the course that won't be generated when
* the modules and sections are added.
*
* Things such as the reports branch, the participants branch, blogs... get
* added to the course node by this method.
*
* @param navigation_node $coursenode
* @param stdClass $course
* @return bool True for successfull generation
*/
    public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
        global $CFG;

        if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
            return true;
        }

        // Hidden node that we use to determine if the front page navigation is loaded.
        // This required as there are not other guaranteed nodes that may be loaded.
        $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;

        //Participants
        if (has_capability('moodle/course:viewparticipants', get_system_context())) {
            $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
        }

        $filterselect = 0;

        // Blogs
        if (!empty($CFG->bloglevel)
          and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
          and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
            $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
            $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
        }

        // Notes
        if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
            $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
        }

        // Tags
        if (!empty($CFG->usetags) && isloggedin()) {
            $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
        }

        if (isloggedin()) {
            // Calendar
            $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
            $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
        }

        // View course reports
        if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
            $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
            $coursereports = get_plugin_list('coursereport'); // deprecated
            foreach ($coursereports as $report=>$dir) {
                $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
                if (file_exists($libfile)) {
                    require_once($libfile);
                    $reportfunction = $report.'_report_extend_navigation';
                    if (function_exists($report.'_report_extend_navigation')) {
                        $reportfunction($reportnav, $course, $this->page->context);
                    }
                }
            }

            $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
            foreach ($reports as $reportfunction) {
                $reportfunction($reportnav, $course, $this->page->context);
            }
        }
        return true;
    }

    /**
* Clears the navigation cache
*/
    public function clear_cache() {
        $this->cache->clear();
    }

    /**
* Sets an expansion limit for the navigation
*
* The expansion limit is used to prevent the display of content that has a type
* greater than the provided $type.
*
* Can be used to ensure things such as activities or activity content don't get
* shown on the navigation.
* They are still generated in order to ensure the navbar still makes sense.
*
* @param int $type One of navigation_node::TYPE_*
* @return <type>
*/
    public function set_expansion_limit($type) {
        $nodes = $this->find_all_of_type($type);
        foreach ($nodes as &$node) {
            // We need to generate the full site node
            if ($type == self::TYPE_COURSE && $node->key == SITEID) {
                continue;
            }
            foreach ($node->children as &$child) {
                // We still want to show course reports and participants containers
                // or there will be navigation missing.
                if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
                    continue;
                }
                $child->display = false;
            }
        }
        return true;
    }
    /**
* Attempts to get the navigation with the given key from this nodes children.
*
* This function only looks at this nodes children, it does NOT look recursivily.
* If the node can't be found then false is returned.
*
* If you need to search recursivily then use the {@see find()} method.
*
* Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
* may be of more use to you.
*
* @param string|int $key The key of the node you wish to receive.
* @param int $type One of navigation_node::TYPE_*
* @return navigation_node|false
*/
    public function get($key, $type = null) {
        if (!$this->initialised) {
            $this->initialise();
        }
        return parent::get($key, $type);
    }

    /**
* Searches this nodes children and thier children to find a navigation node
* with the matching key and type.
*
* This method is recursive and searches children so until either a node is
* found of there are no more nodes to search.
*
* If you know that the node being searched for is a child of this node
* then use the {@see get()} method instead.
*
* Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
* may be of more use to you.
*
* @param string|int $key The key of the node you wish to receive.
* @param int $type One of navigation_node::TYPE_*
* @return navigation_node|false
*/
    public function find($key, $type) {
        if (!$this->initialised) {
            $this->initialise();
        }
        return parent::find($key, $type);
    }
}

/**
* The limited global navigation class used for the AJAX extension of the global
* navigation class.
*
* The primary methods that are used in the global navigation class have been overriden
* to ensure that only the relevant branch is generated at the root of the tree.
* This can be done because AJAX is only used when the backwards structure for the
* requested branch exists.
* This has been done only because it shortens the amounts of information that is generated
* which of course will speed up the response time.. because no one likes laggy AJAX.
*
* @package moodlecore
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class global_navigation_for_ajax extends global_navigation {

    protected $branchtype;
    protected $instanceid;

    /** @var array */
    protected $expandable = array();

    /**
* Constructs the navigation for use in AJAX request
*/
    public function __construct($page, $branchtype, $id) {
        $this->page = $page;
        $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
        $this->children = new navigation_node_collection();
        $this->branchtype = $branchtype;
        $this->instanceid = $id;
        $this->initialise();
    }
    /**
* Initialise the navigation given the type and id for the branch to expand.
*
* @return array The expandable nodes
*/
    public function initialise() {
        global $CFG, $DB, $SITE;

        if ($this->initialised || during_initial_install()) {
            return $this->expandable;
        }
        $this->initialised = true;

        $this->rootnodes = array();
        $this->rootnodes['site'] = $this->add_course($SITE);
        $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');

        // Branchtype will be one of navigation_node::TYPE_*
        switch ($this->branchtype) {
            case self::TYPE_CATEGORY :
                $this->load_all_categories($this->instanceid);
                $limit = 20;
                if (!empty($CFG->navcourselimit)) {
                    $limit = (int)$CFG->navcourselimit;
                }
                $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
                foreach ($courses as $course) {
                    $this->add_course($course);
                }
                break;
            case self::TYPE_COURSE :
                $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
                require_course_login($course);
                $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
                $coursenode = $this->add_course($course);
                $this->add_course_essentials($coursenode, $course);
                if ($this->format_display_course_content($course->format)) {
                    $this->load_course_sections($course, $coursenode);
                }
                break;
            case self::TYPE_SECTION :
                $sql = 'SELECT c.*, cs.section AS sectionnumber
FROM {course} c
LEFT JOIN {course_sections} cs ON cs.course = c.id
WHERE cs.id = ?';
                $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
                require_course_login($course);
                $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
                $coursenode = $this->add_course($course);
                $this->add_course_essentials($coursenode, $course);
                $sections = $this->load_course_sections($course, $coursenode);
                list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
                $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
                break;
            case self::TYPE_ACTIVITY :
                $sql = "SELECT c.*
FROM {course} c
JOIN {course_modules} cm ON cm.course = c.id
WHERE cm.id = :cmid";
                $params = array('cmid' => $this->instanceid);
                $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
                $modinfo = get_fast_modinfo($course);
                $cm = $modinfo->get_cm($this->instanceid);
                require_course_login($course, true, $cm);
                $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
                $coursenode = $this->load_course($course);
                if ($course->id == SITEID) {
                    $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
                } else {
                    $sections = $this->load_course_sections($course, $coursenode);
                    list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
                    $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
                    $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
                }
                break;
            default:
                throw new Exception('Unknown type');
                return $this->expandable;
        }

        if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
            $this->load_for_user(null, true);
        }

        $this->find_expandable($this->expandable);
        return $this->expandable;
    }

    /**
* Returns an array of expandable nodes
* @return array
*/
    public function get_expandable() {
        return $this->expandable;
    }
}

/**
* Navbar class
*
* This class is used to manage the navbar, which is initialised from the navigation
* object held by PAGE
*
* @package moodlecore
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class navbar extends navigation_node {
    /** @var bool */
    protected $initialised = false;
    /** @var mixed */
    protected $keys = array();
    /** @var null|string */
    protected $content = null;
    /** @var moodle_page object */
    protected $page;
    /** @var bool */
    protected $ignoreactive = false;
    /** @var bool */
    protected $duringinstall = false;
    /** @var bool */
    protected $hasitems = false;
    /** @var array */
    protected $items;
    /** @var array */
    public $children = array();
    /** @var bool */
    public $includesettingsbase = false;
    /**
* The almighty constructor
*
* @param moodle_page $page
*/
    public function __construct(moodle_page $page) {
        global $CFG;
        if (during_initial_install()) {
            $this->duringinstall = true;
            return false;
        }
        $this->page = $page;
        $this->text = get_string('home');
        $this->shorttext = get_string('home');
        $this->action = new moodle_url($CFG->wwwroot);
        $this->nodetype = self::NODETYPE_BRANCH;
        $this->type = self::TYPE_SYSTEM;
    }

    /**
* Quick check to see if the navbar will have items in.
*
* @return bool Returns true if the navbar will have items, false otherwise
*/
    public function has_items() {
        if ($this->duringinstall) {
            return false;
        } else if ($this->hasitems !== false) {
            return true;
        }
        $this->page->navigation->initialise($this->page);

        $activenodefound = ($this->page->navigation->contains_active_node() ||
                            $this->page->settingsnav->contains_active_node());

        $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
        $this->hasitems = $outcome;
        return $outcome;
    }

    /**
* Turn on/off ignore active
*
* @param bool $setting
*/
    public function ignore_active($setting=true) {
        $this->ignoreactive = ($setting);
    }
    public function get($key, $type = null) {
        foreach ($this->children as &$child) {
            if ($child->key === $key && ($type == null || $type == $child->type)) {
                return $child;
            }
        }
        return false;
    }
    /**
* Returns an array of navigation_node's that make up the navbar.
*
* @return array
*/
    public function get_items() {
        $items = array();
        // Make sure that navigation is initialised
        if (!$this->has_items()) {
            return $items;
        }
        if ($this->items !== null) {
            return $this->items;
        }

        if (count($this->children) > 0) {
            // Add the custom children
            $items = array_reverse($this->children);
        }

        $navigationactivenode = $this->page->navigation->find_active_node();
        $settingsactivenode = $this->page->settingsnav->find_active_node();

        // Check if navigation contains the active node
        if (!$this->ignoreactive) {

            if ($navigationactivenode && $settingsactivenode) {
                // Parse a combined navigation tree
                while ($settingsactivenode && $settingsactivenode->parent !== null) {
                    if (!$settingsactivenode->mainnavonly) {
                        $items[] = $settingsactivenode;
                    }
                    $settingsactivenode = $settingsactivenode->parent;
                }
                if (!$this->includesettingsbase) {
                    // Removes the first node from the settings (root node) from the list
                    array_pop($items);
                }
                while ($navigationactivenode && $navigationactivenode->parent !== null) {
                    if (!$navigationactivenode->mainnavonly) {
                        $items[] = $navigationactivenode;
                    }
                    $navigationactivenode = $navigationactivenode->parent;
                }
            } else if ($navigationactivenode) {
                // Parse the navigation tree to get the active node
                while ($navigationactivenode && $navigationactivenode->parent !== null) {
                    if (!$navigationactivenode->mainnavonly) {
                        $items[] = $navigationactivenode;
                    }
                    $navigationactivenode = $navigationactivenode->parent;
                }
            } else if ($settingsactivenode) {
                // Parse the settings navigation to get the active node
                while ($settingsactivenode && $settingsactivenode->parent !== null) {
                    if (!$settingsactivenode->mainnavonly) {
                        $items[] = $settingsactivenode;
                    }
                    $settingsactivenode = $settingsactivenode->parent;
                }
            }
        }

        $items[] = new navigation_node(array(
            'text'=>$this->page->navigation->text,
            'shorttext'=>$this->page->navigation->shorttext,
            'key'=>$this->page->navigation->key,
            'action'=>$this->page->navigation->action
        ));

        $this->items = array_reverse($items);
        return $this->items;
    }

    /**
* Add a new navigation_node to the navbar, overrides parent::add
*
* This function overrides {@link navigation_node::add()} so that we can change
* the way nodes get added to allow us to simply call add and have the node added to the
* end of the navbar
*
* @param string $text
* @param string|moodle_url $action
* @param int $type
* @param string|int $key
* @param string $shorttext
* @param string $icon
* @return navigation_node
*/
    public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
        if ($this->content !== null) {
            debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
        }

        // Properties array used when creating the new navigation node
        $itemarray = array(
            'text' => $text,
            'type' => $type
        );
        // Set the action if one was provided
        if ($action!==null) {
            $itemarray['action'] = $action;
        }
        // Set the shorttext if one was provided
        if ($shorttext!==null) {
            $itemarray['shorttext'] = $shorttext;
        }
        // Set the icon if one was provided
        if ($icon!==null) {
            $itemarray['icon'] = $icon;
        }
        // Default the key to the number of children if not provided
        if ($key === null) {
            $key = count($this->children);
        }
        // Set the key
        $itemarray['key'] = $key;
        // Set the parent to this node
        $itemarray['parent'] = $this;
        // Add the child using the navigation_node_collections add method
        $this->children[] = new navigation_node($itemarray);
        return $this;
    }
}

/**
* Class used to manage the settings option for the current page
*
* This class is used to manage the settings options in a tree format (recursively)
* and was created initially for use with the settings blocks.
*
* @package moodlecore
* @subpackage navigation
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class settings_navigation extends navigation_node {
    /** @var stdClass */
    protected $context;
    /** @var moodle_page */
    protected $page;
    /** @var string */
    protected $adminsection;
    /** @var bool */
    protected $initialised = false;
    /** @var array */
    protected $userstoextendfor = array();
    /** @var navigation_cache **/
    protected $cache;

    /**
* Sets up the object with basic settings and preparse it for use
*
* @param moodle_page $page
*/
    public function __construct(moodle_page &$page) {
        if (during_initial_install()) {
            return false;
        }
        $this->page = $page;
        // Initialise the main navigation. It is most important that this is done
        // before we try anything
        $this->page->navigation->initialise();
        // Initialise the navigation cache
        $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
        $this->children = new navigation_node_collection();
    }
    /**
* Initialise the settings navigation based on the current context
*
* This function initialises the settings navigation tree for a given context
* by calling supporting functions to generate major parts of the tree.
*
*/
    public function initialise() {
        global $DB, $SESSION;

        if (during_initial_install()) {
            return false;
        } else if ($this->initialised) {
            return true;
        }
        $this->id = 'settingsnav';
        $this->context = $this->page->context;

        $context = $this->context;
        if ($context->contextlevel == CONTEXT_BLOCK) {
            $this->load_block_settings();
            $context = $context->get_parent_context();
        }

        switch ($context->contextlevel) {
            case CONTEXT_SYSTEM:
                if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
                    $this->load_front_page_settings(($context->id == $this->context->id));
                }
                break;
            case CONTEXT_COURSECAT:
                $this->load_category_settings();
                break;
            case CONTEXT_COURSE:
                if ($this->page->course->id != SITEID) {
                    $this->load_course_settings(($context->id == $this->context->id));
                } else {
                    $this->load_front_page_settings(($context->id == $this->context->id));
                }
                break;
            case CONTEXT_MODULE:
                $this->load_module_settings();
                $this->load_course_settings();
                break;
            case CONTEXT_USER:
                if ($this->page->course->id != SITEID) {
                    $this->load_course_settings();
                }
                break;
        }

        $settings = $this->load_user_settings($this->page->course->id);

        if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
            $admin = $this->load_administration_settings();
            $SESSION->load_navigation_admin = ($admin->has_children());
        } else {
            $admin = false;
        }

        if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
            $admin->force_open();
        } else if ($context->contextlevel == CONTEXT_USER && $settings) {
            $settings->force_open();
        }

        // Check if the user is currently logged in as another user
        if (session_is_loggedinas()) {
            // Get the actual user, we need this so we can display an informative return link
            $realuser = session_get_realuser();
            // Add the informative return to original user link
            $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
            $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
        }

        foreach ($this->children as $key=>$node) {
            if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
                $node->remove();
            }
        }
        $this->initialised = true;
    }
    /**
* Override the parent function so that we can add preceeding hr's and set a
* root node class against all first level element
*
* It does this by first calling the parent's add method {@link navigation_node::add()}
* and then proceeds to use the key to set class and hr
*
* @param string $text
* @param sting|moodle_url $url
* @param string $shorttext
* @param string|int $key
* @param int $type
* @param string $icon
* @return navigation_node
*/
    public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
        $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
        $node->add_class('root_node');
        return $node;
    }

    /**
* This function allows the user to add something to the start of the settings
* navigation, which means it will be at the top of the settings navigation block
*
* @param string $text
* @param sting|moodle_url $url
* @param string $shorttext
* @param string|int $key
* @param int $type
* @param string $icon
* @return navigation_node
*/
    public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
        $children = $this->children;
        $childrenclass = get_class($children);
        $this->children = new $childrenclass;
        $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
        foreach ($children as $child) {
            $this->children->add($child);
        }
        return $node;
    }
    /**
* Load the site administration tree
*
* This function loads the site administration tree by using the lib/adminlib library functions
*
* @param navigation_node $referencebranch A reference to a branch in the settings
* navigation tree
* @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
* tree and start at the beginning
* @return mixed A key to access the admin tree by
*/
    protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
        global $CFG;

        // Check if we are just starting to generate this navigation.
        if ($referencebranch === null) {

            // Require the admin lib then get an admin structure
            if (!function_exists('admin_get_root')) {
                require_once($CFG->dirroot.'/lib/adminlib.php');
            }
            $adminroot = admin_get_root(false, false);
            // This is the active section identifier
            $this->adminsection = $this->page->url->param('section');

            // Disable the navigation from automatically finding the active node
            navigation_node::$autofindactive = false;
            $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
            foreach ($adminroot->children as $adminbranch) {
                $this->load_administration_settings($referencebranch, $adminbranch);
            }
            navigation_node::$autofindactive = true;

            // Use the admin structure to locate the active page
            if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
                $currentnode = $this;
                while (($pathkey = array_pop($current->path))!==null && $currentnode) {
                    $currentnode = $currentnode->get($pathkey);
                }
                if ($currentnode) {
                    $currentnode->make_active();
                }
            } else {
                $this->scan_for_active_node($referencebranch);
            }
            return $referencebranch;
        } else if ($adminbranch->check_access()) {
            // We have a reference branch that we can access and is not hidden `hurrah`
            // Now we need to display it and any children it may have
            $url = null;
            $icon = null;
            if ($adminbranch instanceof admin_settingpage) {
                $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
            } else if ($adminbranch instanceof admin_externalpage) {
                $url = $adminbranch->url;
            }

            // Add the branch
            $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);

            if ($adminbranch->is_hidden()) {
                if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
                    $reference->add_class('hidden');
                } else {
                    $reference->display = false;
                }
            }

            // Check if we are generating the admin notifications and whether notificiations exist
            if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
                $reference->add_class('criticalnotification');
            }
            // Check if this branch has children
            if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
                foreach ($adminbranch->children as $branch) {
                    // Generate the child branches as well now using this branch as the reference
                    $this->load_administration_settings($reference, $branch);
                }
            } else {
                $reference->icon = new pix_icon('i/settings', '');
            }
        }
    }

    /**
* This function recursivily scans nodes until it finds the active node or there
* are no more nodes.
* @param navigation_node $node
*/
    protected function scan_for_active_node(navigation_node $node) {
        if (!$node->check_if_active() && $node->children->count()>0) {
            foreach ($node->children as &$child) {
                $this->scan_for_active_node($child);
            }
        }
    }

    /**
* Gets a navigation node given an array of keys that represent the path to
* the desired node.
*
* @param array $path
* @return navigation_node|false
*/
    protected function get_by_path(array $path) {
        $node = $this->get(array_shift($path));
        foreach ($path as $key) {
            $node->get($key);
        }
        return $node;
    }

    /**
* Generate the list of modules for the given course.
*
* @param stdClass $course The course to get modules for
*/
    protected function get_course_modules($course) {
        global $CFG;
        $mods = $modnames = $modnamesplural = $modnamesused = array();
        // This function is included when we include course/lib.php at the top
        // of this file
        get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
        $resources = array();
        $activities = array();
        foreach($modnames as $modname=>$modnamestr) {
            if (!course_allowed_module($course, $modname)) {
                continue;
            }

            $libfile = "$CFG->dirroot/mod/$modname/lib.php";
            if (!file_exists($libfile)) {
                continue;
            }
            include_once($libfile);
            $gettypesfunc = $modname.'_get_types';
            if (function_exists($gettypesfunc)) {
                $types = $gettypesfunc();
                foreach($types as $type) {
                    if (!isset($type->modclass) || !isset($type->typestr)) {
                        debugging('Incorrect activity type in '.$modname);
                        continue;
                    }
                    if ($type->modclass == MOD_CLASS_RESOURCE) {
                        $resources[html_entity_decode($type->type)] = $type->typestr;
                    } else {
                        $activities[html_entity_decode($type->type)] = $type->typestr;
                    }
                }
            } else {
                $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
                if ($archetype == MOD_ARCHETYPE_RESOURCE) {
                    $resources[$modname] = $modnamestr;
                } else {
                    // all other archetypes are considered activity
                    $activities[$modname] = $modnamestr;
                }
            }
        }
        return array($resources, $activities);
    }

    /**
* This function loads the course settings that are available for the user
*
* @param bool $forceopen If set to true the course node will be forced open
* @return navigation_node|false
*/
    protected function load_course_settings($forceopen = false) {
        global $CFG;

        $course = $this->page->course;
        $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);

        // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section

        $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
        if ($forceopen) {
            $coursenode->force_open();
        }

        if (has_capability('moodle/course:update', $coursecontext)) {
            // Add the turn on/off settings
            $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
            if ($this->page->user_is_editing()) {
                $url->param('edit', 'off');
                $editstring = get_string('turneditingoff');
            } else {
                $url->param('edit', 'on');
                $editstring = get_string('turneditingon');
            }
            $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));

            if ($this->page->user_is_editing()) {
                // Removed as per MDL-22732
                // $this->add_course_editing_links($course);
            }

            // Add the course settings link
            $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
            $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));

            // Add the course completion settings link
            if ($CFG->enablecompletion && $course->enablecompletion) {
                $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
                $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
            }
        }

        // add enrol nodes
        enrol_add_course_navigation($coursenode, $course);

        // Manage filters
        if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
            $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
            $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
        }

        // Add view grade report is permitted
        $reportavailable = false;
        if (has_capability('moodle/grade:viewall', $coursecontext)) {
            $reportavailable = true;
        } else if (!empty($course->showgrades)) {
            $reports = get_plugin_list('gradereport');
            if (is_array($reports) && count($reports)>0) { // Get all installed reports
                arsort($reports); // user is last, we want to test it first
                foreach ($reports as $plugin => $plugindir) {
                    if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
                        //stop when the first visible plugin is found
                        $reportavailable = true;
                        break;
                    }
                }
            }
        }
        if ($reportavailable) {
            $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
            $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
        }

        // Add outcome if permitted
        if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
            $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
            $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
        }

        // Backup this course
        if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
            $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
            $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
        }

        // Restore to this course
        if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
            $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
            $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
        }

        // Import data from other courses
        if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
            $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
            $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
        }

        // Publish course on a hub
        if (has_capability('moodle/course:publish', $coursecontext)) {
            $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
            $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
        }

        // Reset this course
        if (has_capability('moodle/course:reset', $coursecontext)) {
            $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
            $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
        }

        // Questions
        require_once($CFG->dirroot.'/question/editlib.php');
        question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();

        if (has_capability('moodle/course:update', $coursecontext)) {
            // Repository Instances
            if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
                require_once($CFG->dirroot . '/repository/lib.php');
                $editabletypes = repository::get_editable_types($coursecontext);
                $haseditabletypes = !empty($editabletypes);
                unset($editabletypes);
                $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
            } else {
                $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
            }
            if ($haseditabletypes) {
                $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
                $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
            }
        }

        // Manage files
        if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
            // hidden in new courses and courses where legacy files were turned off
            $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
            $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
        }

        // Switch roles
        $roles = array();
        $assumedrole = $this->in_alternative_role();
        if ($assumedrole !== false) {
            $roles[0] = get_string('switchrolereturn');
        }
        if (has_capability('moodle/role:switchroles', $coursecontext)) {
            $availableroles = get_switchable_roles($coursecontext);
            if (is_array($availableroles)) {
                foreach ($availableroles as $key=>$role) {
                    if ($assumedrole == (int)$key) {
                        continue;
                    }
                    $roles[$key] = $role;
                }
            }
        }
        if (is_array($roles) && count($roles)>0) {
            $switchroles = $this->add(get_string('switchroleto'));
            if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
                $switchroles->force_open();
            }
            $returnurl = $this->page->url;
            $returnurl->param('sesskey', sesskey());
            foreach ($roles as $key => $name) {
                $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
                $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
            }
        }
        // Return we are done
        return $coursenode;
    }

    /**
* Adds branches and links to the settings navigation to add course activities
* and resources.
*
* @param stdClass $course
*/
    protected function add_course_editing_links($course) {
        global $CFG;

        require_once($CFG->dirroot.'/course/lib.php');

        // Add `add` resources|activities branches
        $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
        if (file_exists($structurefile)) {
            require_once($structurefile);
            $requestkey = call_user_func('callback_'.$course->format.'_request_key');
            $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
        } else {
            $requestkey = get_string('section');
            $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
        }

        $sections = get_all_sections($course->id);

        $addresource = $this->add(get_string('addresource'));
        $addactivity = $this->add(get_string('addactivity'));
        if ($formatidentifier!==0) {
            $addresource->force_open();
            $addactivity->force_open();
        }

        $this->get_course_modules($course);

        $textlib = textlib_get_instance();

        foreach ($sections as $section)