Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 2af268a1f3
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 2638 lines (2326 sloc) 108.135 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
<?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/>.

/**
* Calendar extension
*
* @package core_calendar
* @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
* Avgoustos Tsinakos
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

/**
* These are read by the administration component to provide default values
*/

/**
* CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
*/
define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);

/**
* CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
*/
define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);

/**
* CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
*/
define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);

// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday

/**
* CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
*/
define('CALENDAR_DEFAULT_WEEKEND', 65);

/**
* CALENDAR_URL - path to calendar's folder
*/
define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');

/**
* CALENDAR_TF_24 - Calendar time in 24 hours format
*/
define('CALENDAR_TF_24', '%H:%M');

/**
* CALENDAR_TF_12 - Calendar time in 12 hours format
*/
define('CALENDAR_TF_12', '%I:%M %p');

/**
* CALENDAR_EVENT_GLOBAL - Global calendar event types
*/
define('CALENDAR_EVENT_GLOBAL', 1);

/**
* CALENDAR_EVENT_COURSE - Course calendar event types
*/
define('CALENDAR_EVENT_COURSE', 2);

/**
* CALENDAR_EVENT_GROUP - group calendar event types
*/
define('CALENDAR_EVENT_GROUP', 4);

/**
* CALENDAR_EVENT_USER - user calendar event types
*/
define('CALENDAR_EVENT_USER', 8);

/**
* CALENDAR_STARTING_WEEKDAY - has since been deprecated please call calendar_get_starting_weekday() instead
*
* @deprecated Moodle 2.0 MDL-24284- please do not use this function any more.
* @todo MDL-31132 This will be deleted in Moodle 2.3.
* @see calendar_get_starting_weekday()
*/
define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);

/**
* Return the days of the week
*
* @return array array of days
*/
function calendar_get_days() {
    return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
}

/**
* Gets the first day of the week
*
* Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
*
* @return int
*/
function calendar_get_starting_weekday() {
    global $CFG;

    if (isset($CFG->calendar_startwday)) {
        $firstday = $CFG->calendar_startwday;
    } else {
        $firstday = get_string('firstdayofweek', 'langconfig');
    }

    if(!is_numeric($firstday)) {
        return CALENDAR_DEFAULT_STARTING_WEEKDAY;
    } else {
        return intval($firstday) % 7;
    }
}

/**
* Generates the HTML for a miniature calendar
*
* @param array $courses list of course
* @param array $groups list of group
* @param array $users user's info
* @param int $cal_month calendar month in numeric, default is set to false
* @param int $cal_year calendar month in numeric, default is set to false
* @return string $content return html table for mini calendar
*/
function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
    global $CFG, $USER, $OUTPUT;

    $display = new stdClass;
    $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
    $display->maxwday = $display->minwday + 6;

    $content = '';

    if(!empty($cal_month) && !empty($cal_year)) {
        $thisdate = usergetdate(time()); // Date and time the user sees at his location
        if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
            // Navigated to this month
            $date = $thisdate;
            $display->thismonth = true;
        } else {
            // Navigated to other month, let's do a nice trick and save us a lot of work...
            if(!checkdate($cal_month, 1, $cal_year)) {
                $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
                $display->thismonth = true;
            } else {
                $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
                $display->thismonth = false;
            }
        }
    } else {
        $date = usergetdate(time()); // Date and time the user sees at his location
        $display->thismonth = true;
    }

    // Fill in the variables we 're going to use, nice and tidy
    list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
    $display->maxdays = calendar_days_in_month($m, $y);

    if (get_user_timezone_offset() < 99) {
        // We 'll keep these values as GMT here, and offset them when the time comes to query the db
        $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
        $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
    } else {
        // no timezone info specified
        $display->tstart = mktime(0, 0, 0, $m, 1, $y);
        $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
    }

    $startwday = dayofweek(1, $m, $y);

    // Align the starting weekday to fall in our display range
    // This is simple, not foolproof.
    if($startwday < $display->minwday) {
        $startwday += 7;
    }

    // TODO: THIS IS TEMPORARY CODE!
    // [pj] I was just reading through this and realized that I when writing this code I was probably
    // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
    // make_timestamp would accomplish the same thing. So here goes a test:
    //$test_start = make_timestamp($y, $m, 1);
    //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
    //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
        //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
    //}
    //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
        //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
    //}


    // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
    $events = calendar_get_events(
        usertime($display->tstart) - dst_offset_on($display->tstart),
        usertime($display->tend) - dst_offset_on($display->tend),
        $users, $groups, $courses);

    // Set event course class for course events
    if (!empty($events)) {
        foreach ($events as $eventid => $event) {
            if (!empty($event->modulename)) {
                $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
                if (!groups_course_module_visible($cm)) {
                    unset($events[$eventid]);
                }
            }
        }
    }

    // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
    // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
    // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
    // arguments to this function.

    $hrefparams = array();
    if(!empty($courses)) {
        $courses = array_diff($courses, array(SITEID));
        if(count($courses) == 1) {
            $hrefparams['course'] = reset($courses);
        }
    }

    // We want to have easy access by day, since the display is on a per-day basis.
    // Arguments passed by reference.
    //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
    calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);

    //Accessibility: added summary and <abbr> elements.
    $days_title = calendar_get_days();

    $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
    $summary = get_string('tabledata', 'access', $summary);
    $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
    $content .= '<tr class="weekdays">'; // Header row: day names

    // Print out the names of the weekdays
    $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
    for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
        // This uses the % operator to get the correct weekday no matter what shift we have
        // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
        $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
            get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
    }

    $content .= '</tr><tr>'; // End of day names; prepare for day numbers

    // For the table display. $week is the row; $dayweek is the column.
    $dayweek = $startwday;

    // Paddding (the first week may have blank days in the beginning)
    for($i = $display->minwday; $i < $startwday; ++$i) {
        $content .= '<td class="dayblank">&nbsp;</td>'."\n";
    }

    $weekend = CALENDAR_DEFAULT_WEEKEND;
    if (isset($CFG->calendar_weekend)) {
        $weekend = intval($CFG->calendar_weekend);
    }

    // Now display all the calendar
    for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
        if($dayweek > $display->maxwday) {
            // We need to change week (table row)
            $content .= '</tr><tr>';
            $dayweek = $display->minwday;
        }

        // Reset vars
        $cell = '';
        if ($weekend & (1 << ($dayweek % 7))) {
            // Weekend. This is true no matter what the exact range is.
            $class = 'weekend day';
        } else {
            // Normal working day.
            $class = 'day';
        }

        // Special visual fx if an event is defined
        if(isset($eventsbyday[$day])) {
            $class .= ' hasevent';
            $hrefparams['view'] = 'day';
            $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);

            $popupcontent = '';
            foreach($eventsbyday[$day] as $eventid) {
                if (!isset($events[$eventid])) {
                    continue;
                }
                $event = $events[$eventid];
                $popupalt = '';
                $component = 'moodle';
                if(!empty($event->modulename)) {
                    $popupicon = 'icon';
                    $popupalt = $event->modulename;
                    $component = $event->modulename;
                } else if ($event->courseid == SITEID) { // Site event
                    $popupicon = 'c/site';
                } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
                    $popupicon = 'c/course';
                } else if ($event->groupid) { // Group event
                    $popupicon = 'c/group';
                } else if ($event->userid) { // User event
                    $popupicon = 'c/user';
                }

                $dayhref->set_anchor('event_'.$event->id);

                $popupcontent .= html_writer::start_tag('div');
                $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
                $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
                $popupcontent .= html_writer::end_tag('div');
            }

            //Accessibility: functionality moved to calendar_get_popup.
            if($display->thismonth && $day == $d) {
                $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
            } else {
                $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
            }

            // Class and cell content
            if(isset($typesbyday[$day]['startglobal'])) {
                $class .= ' calendar_event_global';
            } else if(isset($typesbyday[$day]['startcourse'])) {
                $class .= ' calendar_event_course';
            } else if(isset($typesbyday[$day]['startgroup'])) {
                $class .= ' calendar_event_group';
            } else if(isset($typesbyday[$day]['startuser'])) {
                $class .= ' calendar_event_user';
            }
            $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
        } else {
            $cell = $day;
        }

        $durationclass = false;
        if (isset($typesbyday[$day]['durationglobal'])) {
            $durationclass = ' duration_global';
        } else if(isset($typesbyday[$day]['durationcourse'])) {
            $durationclass = ' duration_course';
        } else if(isset($typesbyday[$day]['durationgroup'])) {
            $durationclass = ' duration_group';
        } else if(isset($typesbyday[$day]['durationuser'])) {
            $durationclass = ' duration_user';
        }
        if ($durationclass) {
            $class .= ' duration '.$durationclass;
        }

        // If event has a class set then add it to the table day <td> tag
        // Note: only one colour for minicalendar
        if(isset($eventsbyday[$day])) {
            foreach($eventsbyday[$day] as $eventid) {
                if (!isset($events[$eventid])) {
                    continue;
                }
                $event = $events[$eventid];
                if (!empty($event->class)) {
                    $class .= ' '.$event->class;
                }
                break;
            }
        }

        // Special visual fx for today
        //Accessibility: hidden text for today, and popup.
        if($display->thismonth && $day == $d) {
            $class .= ' today';
            $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));

            if(! isset($eventsbyday[$day])) {
                $class .= ' eventnone';
                $popup = calendar_get_popup(true, false);
                $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
            }
            $cell = get_accesshide($today.' ').$cell;
        }

        // Just display it
        if(!empty($class)) {
            $class = ' class="'.$class.'"';
        }
        $content .= '<td'.$class.'>'.$cell."</td>\n";
    }

    // Paddding (the last week may have blank days at the end)
    for($i = $dayweek; $i <= $display->maxwday; ++$i) {
        $content .= '<td class="dayblank">&nbsp;</td>';
    }
    $content .= '</tr>'; // Last row ends

    $content .= '</table>'; // Tabular display of days ends

    return $content;
}

/**
* Gets the calendar popup
*
* It called at multiple points in from calendar_get_mini.
* Copied and modified from calendar_get_mini.
*
* @param bool $is_today false except when called on the current day.
* @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
* @param string $popupcontent content for the popup window/layout
* @return string of eventid for the calendar_tooltip popup window/layout
*/
function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
    global $PAGE;
    static $popupcount;
    if ($popupcount === null) {
        $popupcount = 1;
    }
    $popupcaption = '';
    if($is_today) {
        $popupcaption = get_string('today', 'calendar').' ';
    }
    if (false === $event_timestart) {
        $popupcaption .= userdate(time(), get_string('strftimedayshort'));
        $popupcontent = get_string('eventnone', 'calendar');

    } else {
        $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
    }
    $id = 'calendar_tooltip_'.$popupcount;
    $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));

    $popupcount++;
    return 'id="'.$id.'"';
}

/**
* Gets the calendar upcoming event
*
* @param array $courses array of courses
* @param array|int|bool $groups array of groups, group id or boolean for all/no group events
* @param array|int|bool $users array of users, user id or boolean for all/no user events
* @param int $daysinfuture number of days in the future we 'll look
* @param int $maxevents maximum number of events
* @param int $fromtime start time
* @return array $output array of upcoming events
*/
function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
    global $CFG, $COURSE, $DB;

    $display = new stdClass;
    $display->range = $daysinfuture; // How many days in the future we 'll look
    $display->maxevents = $maxevents;

    $output = array();

    // Prepare "course caching", since it may save us a lot of queries
    $coursecache = array();

    $processed = 0;
    $now = time(); // We 'll need this later
    $usermidnighttoday = usergetmidnight($now);

    if ($fromtime) {
        $display->tstart = $fromtime;
    } else {
        $display->tstart = $usermidnighttoday;
    }

    // This works correctly with respect to the user's DST, but it is accurate
    // only because $fromtime is always the exact midnight of some day!
    $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;

    // Get the events matching our criteria
    $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);

    // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
    // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
    // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
    // arguments to this function.

    $hrefparams = array();
    if(!empty($courses)) {
        $courses = array_diff($courses, array(SITEID));
        if(count($courses) == 1) {
            $hrefparams['course'] = reset($courses);
        }
    }

    if ($events !== false) {

        $modinfo =& get_fast_modinfo($COURSE);

        foreach($events as $event) {


            if (!empty($event->modulename)) {
                if ($event->courseid == $COURSE->id) {
                    if (isset($modinfo->instances[$event->modulename][$event->instance])) {
                        $cm = $modinfo->instances[$event->modulename][$event->instance];
                        if (!$cm->uservisible) {
                            continue;
                        }
                    }
                } else {
                    if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
                        continue;
                    }
                    if (!coursemodule_visible_for_user($cm)) {
                        continue;
                    }
                }
                if ($event->modulename == 'assignment'){
                    // create calendar_event to test edit_event capability
                    // this new event will also prevent double creation of calendar_event object
                    $checkevent = new calendar_event($event);
                    // TODO: rewrite this hack somehow
                    if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
                        if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
                            // print_error("invalidid", 'assignment');
                            continue;
                        }
                        // assign assignment to assignment object to use hidden_is_hidden method
                        require_once($CFG->dirroot.'/mod/assignment/lib.php');

                        if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
                            continue;
                        }
                        require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');

                        $assignmentclass = 'assignment_'.$assignment->assignmenttype;
                        $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);

                        if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
                            $event->description = get_string('notavailableyet', 'assignment');
                        }
                    }
                }
            }

            if ($processed >= $display->maxevents) {
                break;
            }

            $event->time = calendar_format_event_time($event, $now, $hrefparams);
            $output[] = $event;
            ++$processed;
        }
    }
    return $output;
}

/**
* Add calendar event metadata
*
* @param stdClass $event event info
* @return stdClass $event metadata
*/
function calendar_add_event_metadata($event) {
    global $CFG, $OUTPUT;

    //Support multilang in event->name
    $event->name = format_string($event->name,true);

    if(!empty($event->modulename)) { // Activity event
        // The module name is set. I will assume that it has to be displayed, and
        // also that it is an automatically-generated event. And of course that the
        // fields for get_coursemodule_from_instance are set correctly.
        $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);

        if ($module === false) {
            return;
        }

        $modulename = get_string('modulename', $event->modulename);
        if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
            // will be used as alt text if the event icon
            $eventtype = get_string($event->eventtype, $event->modulename);
        } else {
            $eventtype = '';
        }
        $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';

        $context = get_context_instance(CONTEXT_COURSE, $module->course);
        $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));

        $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
        $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
        $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
        $event->cmid = $module->id;


    } else if($event->courseid == SITEID) { // Site event
        $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
        $event->cssclass = 'calendar_event_global';
    } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
        calendar_get_course_cached($coursecache, $event->courseid);

        $context = get_context_instance(CONTEXT_COURSE, $event->courseid);
        $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));

        $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
        $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
        $event->cssclass = 'calendar_event_course';
    } else if ($event->groupid) { // Group event
        $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
        $event->cssclass = 'calendar_event_group';
    } else if($event->userid) { // User event
        $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
        $event->cssclass = 'calendar_event_user';
    }
    return $event;
}

/**
* Prints a calendar event
*
* @deprecated Moodle 2.0 - MDL-22887 please do not use this function any more.
* @todo MDL-31133 - will be removed in Moodle 2.3
* @see core_calendar_renderer event function
*/
function calendar_print_event($event, $showactions=true) {
    global $CFG, $USER, $OUTPUT, $PAGE;
    debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
    $renderer = $PAGE->get_renderer('core_calendar');
    if (!($event instanceof calendar_event)) {
        $event = new calendar_event($event);
    }
    echo $renderer->event($event);
}

/**
* Get calendar events
*
* @param int $tstart Start time of time range for events
* @param int $tend End time of time range for events
* @param array|int|boolean $users array of users, user id or boolean for all/no user events
* @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
* @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
* @param boolean $withduration whether only events starting within time range selected
* or events in progress/already started selected as well
* @param boolean $ignorehidden whether to select only visible events or all events
* @return array $events of selected events or an empty array if there aren't any (or there was an error)
*/
function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
    global $DB;

    $whereclause = '';
    // Quick test
    if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
        return array();
    }

    if(is_array($users) && !empty($users)) {
        // Events from a number of users
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
    } else if(is_numeric($users)) {
        // Events from one user
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
    } else if($users === true) {
        // Events from ALL users
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
    } else if($users === false) {
        // No user at all, do nothing
    }

    if(is_array($groups) && !empty($groups)) {
        // Events from a number of groups
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' groupid IN ('.implode(',', $groups).')';
    } else if(is_numeric($groups)) {
        // Events from one group
        if(!empty($whereclause)) $whereclause .= ' OR ';
        $whereclause .= ' groupid = '.$groups;
    } else if($groups === true) {
        // Events from ALL groups
        if(!empty($whereclause)) $whereclause .= ' OR ';
        $whereclause .= ' groupid != 0';
    }
    // boolean false (no groups at all): we don't need to do anything

    if(is_array($courses) && !empty($courses)) {
        if(!empty($whereclause)) {
            $whereclause .= ' OR';
        }
        $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
    } else if(is_numeric($courses)) {
        // One course
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
    } else if ($courses === true) {
        // Events from ALL courses
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (groupid = 0 AND courseid != 0)';
    }

    // Security check: if, by now, we have NOTHING in $whereclause, then it means
    // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
    // events no matter what. Allowing the code to proceed might return a completely
    // valid query with only time constraints, thus selecting ALL events in that time frame!
    if(empty($whereclause)) {
        return array();
    }

    if($withduration) {
        $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
    }
    else {
        $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
    }
    if(!empty($whereclause)) {
        // We have additional constraints
        $whereclause = $timeclause.' AND ('.$whereclause.')';
    }
    else {
        // Just basic time filtering
        $whereclause = $timeclause;
    }

    if ($ignorehidden) {
        $whereclause .= ' AND visible = 1';
    }

    $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
    if ($events === false) {
        $events = array();
    }
    return $events;
}

/**
* Get control options for Calendar
*
* @param string $type of calendar
* @param array $data calendar information
* @return string $content return available control for the calender in html
*/
function calendar_top_controls($type, $data) {
    global $CFG;
    $content = '';
    if(!isset($data['d'])) {
        $data['d'] = 1;
    }

    // Ensure course id passed if relevant
    // Required due to changes in view/lib.php mainly (calendar_session_vars())
    $courseid = '';
    if (!empty($data['id'])) {
        $courseid = '&amp;course='.$data['id'];
    }

    if(!checkdate($data['m'], $data['d'], $data['y'])) {
        $time = time();
    }
    else {
        $time = make_timestamp($data['y'], $data['m'], $data['d']);
    }
    $date = usergetdate($time);

    $data['m'] = $date['mon'];
    $data['y'] = $date['year'];

    //Accessibility: calendar block controls, replaced <table> with <div>.
    //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
    //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);

    switch($type) {
        case 'frontpage':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
            $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);

            $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
            if (!empty($data['id'])) {
                $calendarlink->param('course', $data['id']);
            }

            if (right_to_left()) {
                $left = $nextlink;
                $right = $prevlink;
            } else {
                $left = $prevlink;
                $right = $nextlink;
            }

            $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
            $content .= $left.'<span class="hide"> | </span>';
            $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
            $content .= '<span class="hide"> | </span>'. $right;
            $content .= "<span class=\"clearer\"><!-- --></span>\n";
            $content .= html_writer::end_tag('div');

            break;
        case 'course':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
            $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);

            $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
            if (!empty($data['id'])) {
                $calendarlink->param('course', $data['id']);
            }

            if (right_to_left()) {
                $left = $nextlink;
                $right = $prevlink;
            } else {
                $left = $prevlink;
                $right = $nextlink;
            }

            $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
            $content .= $left.'<span class="hide"> | </span>';
            $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
            $content .= '<span class="hide"> | </span>'. $right;
            $content .= "<span class=\"clearer\"><!-- --></span>";
            $content .= html_writer::end_tag('div');
            break;
        case 'upcoming':
            $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
            if (!empty($data['id'])) {
                $calendarlink->param('course', $data['id']);
            }
            $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
            $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
            break;
        case 'display':
            $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
            if (!empty($data['id'])) {
                $calendarlink->param('course', $data['id']);
            }
            $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
            $content .= html_writer::tag('h3', $calendarlink);
            break;
        case 'month':
            list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
            list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
            $prevdate = make_timestamp($prevyear, $prevmonth, 1);
            $nextdate = make_timestamp($nextyear, $nextmonth, 1);
            $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
            $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);

            if (right_to_left()) {
                $left = $nextlink;
                $right = $prevlink;
            } else {
                $left = $prevlink;
                $right = $nextlink;
            }

            $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
            $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
            $content .= '<span class="hide"> | </span>' . $right;
            $content .= '<span class="clearer"><!-- --></span>';
            $content .= html_writer::end_tag('div')."\n";
            break;
        case 'day':
            $days = calendar_get_days();
            $data['d'] = $date['mday']; // Just for convenience
            $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
            $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
            $prevname = calendar_wday_name($days[$prevdate['wday']]);
            $nextname = calendar_wday_name($days[$nextdate['wday']]);
            $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
            $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);

            if (right_to_left()) {
                $left = $nextlink;
                $right = $prevlink;
            } else {
                $left = $prevlink;
                $right = $nextlink;
            }

            $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
            $content .= $left;
            $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
            $content .= '<span class="hide"> | </span>'. $right;
            $content .= "<span class=\"clearer\"><!-- --></span>";
            $content .= html_writer::end_tag('div')."\n";

            break;
    }
    return $content;
}

/**
* Get the controls filter for calendar.
*
* Filter is used to hide calendar info from the display page
*
* @param moodle_url $returnurl return-url for filter controls
* @return string $content return filter controls in html
*/
function calendar_filter_controls(moodle_url $returnurl) {
    global $CFG, $USER, $OUTPUT;

    $groupevents = true;

    $id = optional_param( 'id',0,PARAM_INT );

    $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));

    $content = '<table>';
    $content .= '<tr>';

    $seturl->param('var', 'showglobal');
    if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
        $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
    } else {
        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
    }

    $seturl->param('var', 'showcourses');
    if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
        $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
    } else {
        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
    }

    if (isloggedin() && !isguestuser()) {
        $content .= "</tr>\n<tr>";

        if ($groupevents) {
            // This course MIGHT have group events defined, so show the filter
            $seturl->param('var', 'showgroups');
            if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
                $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
                $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
            } else {
                $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
                $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
            }
        } else {
            // This course CANNOT have group events, so lose the filter
            $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
        }

        $seturl->param('var', 'showuser');
        if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
            $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
            $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
        } else {
            $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
            $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
        }
    }
    $content .= "</tr>\n</table>\n";

    return $content;
}

/**
* Return the representation day
*
* @param int $tstamp Timestamp in GMT
* @param int $now current Unix timestamp
* @param bool $usecommonwords
* @return string the formatted date/time
*/
function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {

    static $shortformat;
    if(empty($shortformat)) {
        $shortformat = get_string('strftimedayshort');
    }

    if($now === false) {
        $now = time();
    }

    // To have it in one place, if a change is needed
    $formal = userdate($tstamp, $shortformat);

    $datestamp = usergetdate($tstamp);
    $datenow = usergetdate($now);

    if($usecommonwords == false) {
        // We don't want words, just a date
        return $formal;
    }
    else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
        // Today
        return get_string('today', 'calendar');
    }
    else if(
        ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
        ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
        ) {
        // Yesterday
        return get_string('yesterday', 'calendar');
    }
    else if(
        ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
        ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
        ) {
        // Tomorrow
        return get_string('tomorrow', 'calendar');
    }
    else {
        return $formal;
    }
}

/**
* return the formatted representation time
*
* @param int $time the timestamp in UTC, as obtained from the database
* @return string the formatted date/time
*/
function calendar_time_representation($time) {
    static $langtimeformat = NULL;
    if($langtimeformat === NULL) {
        $langtimeformat = get_string('strftimetime');
    }
    $timeformat = get_user_preferences('calendar_timeformat');
    if(empty($timeformat)){
        $timeformat = get_config(NULL,'calendar_site_timeformat');
    }
    // The ? is needed because the preference might be present, but empty
    return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
}

/**
* Adds day, month, year arguments to a URL and returns a moodle_url object.
*
* @param string|moodle_url $linkbase
* @param int $d The number of the day.
* @param int $m The number of the month.
* @param int $y The number of the year.
* @return moodle_url|null $linkbase
*/
function calendar_get_link_href($linkbase, $d, $m, $y) {
    if (empty($linkbase)) {
        return '';
    }
    if (!($linkbase instanceof moodle_url)) {
        $linkbase = new moodle_url();
    }
    if (!empty($d)) {
        $linkbase->param('cal_d', $d);
    }
    if (!empty($m)) {
        $linkbase->param('cal_m', $m);
    }
    if (!empty($y)) {
        $linkbase->param('cal_y', $y);
    }
    return $linkbase;
}

/**
* This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
*
* @deprecated Moodle 2.0 - MDL-24284 please do not use this function any more.
* @todo MDL-31134 - will be removed in Moodle 2.3
* @see calendar_get_link_href()
*
* @param string $text
* @param string|moodle_url $linkbase
* @param int|null $d The number of the day.
* @param int|null $m The number of the month.
* @param int|null $y The number of the year.
* @return string HTML link
*/
function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
    $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
    if (empty($url)) {
        return $text;
    }
    return html_writer::link($url, $text);
}

/**
* Build and return a previous month HTML link, with an arrow.
*
* @param string $text The text label.
* @param string|moodle_url $linkbase The URL stub.
* @param int $d The number of the date.
* @param int $m The number of the month.
* @param int $y year The number of the year.
* @param bool $accesshide Default visible, or hide from all except screenreaders.
* @return string HTML string.
*/
function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
    $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
    if (empty($href)) {
        return $text;
    }
    return link_arrow_left($text, (string)$href, $accesshide, 'previous');
}

/**
* Build and return a next month HTML link, with an arrow.
*
* @param string $text The text label.
* @param string|moodle_url $linkbase The URL stub.
* @param int $d the number of the Day
* @param int $m The number of the month.
* @param int $y The number of the year.
* @param bool $accesshide Default visible, or hide from all except screenreaders.
* @return string HTML string.
*/
function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
    $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
    if (empty($href)) {
        return $text;
    }
    return link_arrow_right($text, (string)$href, $accesshide, 'next');
}

/**
* Return the name of the weekday
*
* @param string $englishname
* @return string of the weekeday
*/
function calendar_wday_name($englishname) {
    return get_string(strtolower($englishname), 'calendar');
}

/**
* Return the number of days in month
*
* @param int $month the number of the month.
* @param int $year the number of the year
* @return int
*/
function calendar_days_in_month($month, $year) {
   return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
}

/**
* Get the upcoming event block
*
* @param array $events list of events
* @param moodle_url|string $linkhref link to event referer
* @return string|null $content html block content
*/
function calendar_get_block_upcoming($events, $linkhref = NULL) {
    $content = '';
    $lines = count($events);
    if (!$lines) {
        return $content;
    }

    for ($i = 0; $i < $lines; ++$i) {
        if (!isset($events[$i]->time)) { // Just for robustness
            continue;
        }
        $events[$i] = calendar_add_event_metadata($events[$i]);
        $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
        if (!empty($events[$i]->referer)) {
            // That's an activity event, so let's provide the hyperlink
            $content .= $events[$i]->referer;
        } else {
            if(!empty($linkhref)) {
                $ed = usergetdate($events[$i]->timestart);
                $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
                $href->set_anchor('event_'.$events[$i]->id);
                $content .= html_writer::link($href, $events[$i]->name);
            }
            else {
                $content .= $events[$i]->name;
            }
        }
        $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
        $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
        if ($i < $lines - 1) $content .= '<hr />';
    }

    return $content;
}

/**
* Get the next following month
*
* If the current month is December, it will get the first month of the following year.
*
*
* @param int $month the number of the month.
* @param int $year the number of the year.
* @return array the following month
*/
function calendar_add_month($month, $year) {
    if($month == 12) {
        return array(1, $year + 1);
    }
    else {
        return array($month + 1, $year);
    }
}

/**
* Get the previous month
*
* If the current month is January, it will get the last month of the previous year.
*
* @param int $month the number of the month.
* @param int $year the number of the year.
* @return array previous month
*/
function calendar_sub_month($month, $year) {
    if($month == 1) {
        return array(12, $year - 1);
    }
    else {
        return array($month - 1, $year);
    }
}

/**
* Get per-day basis events
*
* @param array $events list of events
* @param int $month the number of the month
* @param int $year the number of the year
* @param array $eventsbyday event on specific day
* @param array $durationbyday duration of the event in days
* @param array $typesbyday event type (eg: global, course, user, or group)
* @param array $courses list of courses
* @return void
*/
function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
    $eventsbyday = array();
    $typesbyday = array();
    $durationbyday = array();

    if($events === false) {
        return;
    }

    foreach($events as $event) {

        $startdate = usergetdate($event->timestart);
        // Set end date = start date if no duration
        if ($event->timeduration) {
            $enddate = usergetdate($event->timestart + $event->timeduration - 1);
        } else {
            $enddate = $startdate;
        }

        // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
        if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
            // Out of bounds
            continue;
        }

        $eventdaystart = intval($startdate['mday']);

        if($startdate['mon'] == $month && $startdate['year'] == $year) {
            // Give the event to its day
            $eventsbyday[$eventdaystart][] = $event->id;

            // Mark the day as having such an event
            if($event->courseid == SITEID && $event->groupid == 0) {
                $typesbyday[$eventdaystart]['startglobal'] = true;
                // Set event class for global event
                $events[$event->id]->class = 'calendar_event_global';
            }
            else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
                $typesbyday[$eventdaystart]['startcourse'] = true;
                // Set event class for course event
                $events[$event->id]->class = 'calendar_event_course';
            }
            else if($event->groupid) {
                $typesbyday[$eventdaystart]['startgroup'] = true;
                // Set event class for group event
                $events[$event->id]->class = 'calendar_event_group';
            }
            else if($event->userid) {
                $typesbyday[$eventdaystart]['startuser'] = true;
                // Set event class for user event
                $events[$event->id]->class = 'calendar_event_user';
            }
        }

        if($event->timeduration == 0) {
            // Proceed with the next
            continue;
        }

        // The event starts on $month $year or before. So...
        $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;

        // Also, it ends on $month $year or later...
        $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);

        // Mark all days between $lowerbound and $upperbound (inclusive) as duration
        for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
            $durationbyday[$i][] = $event->id;
            if($event->courseid == SITEID && $event->groupid == 0) {
                $typesbyday[$i]['durationglobal'] = true;
            }
            else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
                $typesbyday[$i]['durationcourse'] = true;
            }
            else if($event->groupid) {
                $typesbyday[$i]['durationgroup'] = true;
            }
            else if($event->userid) {
                $typesbyday[$i]['durationuser'] = true;
            }
        }

    }
    return;
}

/**
* Get current module cache
*
* @param array $coursecache list of course cache
* @param string $modulename name of the module
* @param int $instance module instance number
* @return stdClass|bool $module information
*/
function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
    $module = get_coursemodule_from_instance($modulename, $instance);

    if($module === false) return false;
    if(!calendar_get_course_cached($coursecache, $module->course)) {
        return false;
    }
    return $module;
}

/**
* Get current course cache
*
* @param array $coursecache list of course cache
* @param int $courseid id of the course
* @return stdClass $coursecache[$courseid] return the specific course cache
*/
function calendar_get_course_cached(&$coursecache, $courseid) {
    global $COURSE, $DB;

    if (!isset($coursecache[$courseid])) {
        if ($courseid == $COURSE->id) {
            $coursecache[$courseid] = $COURSE;
        } else {
            $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
        }
    }
    return $coursecache[$courseid];
}

/**
* Returns the courses to load events for, the
*
* @param array $courseeventsfrom An array of courses to load calendar events for
* @param bool $ignorefilters specify the use of filters, false is set as default
* @return array An array of courses, groups, and user to load calendar events for based upon filters
*/
function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
    global $USER, $CFG, $DB;

    // For backwards compatability we have to check whether the courses array contains
    // just id's in which case we need to load course objects.
    $coursestoload = array();
    foreach ($courseeventsfrom as $id => $something) {
        if (!is_object($something)) {
            $coursestoload[] = $id;
            unset($courseeventsfrom[$id]);
        }
    }
    if (!empty($coursestoload)) {
        // TODO remove this in 2.2
        debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
        $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
    }

    $courses = array();
    $user = false;
    $group = false;

    $isloggedin = isloggedin();

    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
        $courses = array_keys($courseeventsfrom);
    }
    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
        $courses[] = SITEID;
    }
    $courses = array_unique($courses);
    sort($courses);

    if (!empty($courses) && in_array(SITEID, $courses)) {
        // Sort courses for consistent colour highlighting
        // Effectively ignoring SITEID as setting as last course id
        $key = array_search(SITEID, $courses);
        unset($courses[$key]);
        $courses[] = SITEID;
    }

    if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
        $user = $USER->id;
    }

    if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {

        if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_system_context())) {
            $group = true;
        } else if ($isloggedin) {
            $groupids = array();

            // We already have the courses to examine in $courses
            // For each course...
            foreach ($courseeventsfrom as $courseid => $course) {
                // If the user is an editing teacher in there,
                if (!empty($USER->groupmember[$course->id])) {
                    // We've already cached the users groups for this course so we can just use that
                    $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
                } else if (($course->groupmode != NOGROUPS || !$course->groupmodeforce) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $course->id))) {
                    // If this course has groups, show events from all of them
                    $coursegroups = groups_get_user_groups($course->id, $USER->id);
                    $groupids = array_merge($groupids, $coursegroups['0']);
                }
            }
            if (!empty($groupids)) {
                $group = $groupids;
            }
        }
    }
    if (empty($courses)) {
        $courses = false;
    }

    return array($courses, $group, $user);
}

/**
* Return the capability for editing calendar event
*
* @param calendar_event $event event object
* @return bool capability to edit event
*/
function calendar_edit_event_allowed($event) {
    global $USER, $DB;

    // Must be logged in
    if (!isloggedin()) {
        return false;
    }

    // can not be using guest account
    if (isguestuser()) {
        return false;
    }

    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    // if user has manageentries at site level, return true
    if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
        return true;
    }

    // if groupid is set, it's definitely a group event
    if (!empty($event->groupid)) {
        // Allow users to add/edit group events if:
        // 1) They have manageentries (= entries for whole course)
        // 2) They have managegroupentries AND are in the group
        $group = $DB->get_record('groups', array('id'=>$event->groupid));
        return $group && (
            has_capability('moodle/calendar:manageentries', $event->context) ||
            (has_capability('moodle/calendar:managegroupentries', $event->context)
                && groups_is_member($event->groupid)));
    } else if (!empty($event->courseid)) {
    // if groupid is not set, but course is set,
    // it's definiely a course event
        return has_capability('moodle/calendar:manageentries', $event->context);
    } else if (!empty($event->userid) && $event->userid == $USER->id) {
    // if course is not set, but userid id set, it's a user event
        return (has_capability('moodle/calendar:manageownentries', $event->context));
    } else if (!empty($event->userid)) {
        return (has_capability('moodle/calendar:manageentries', $event->context));
    }
    return false;
}

/**
* Returns the default courses to display on the calendar when there isn't a specific
* course to display.
*
* @return array $courses Array of courses to display
*/
function calendar_get_default_courses() {
    global $CFG, $DB;

    if (!isloggedin()) {
        return array();
    }

    $courses = array();
    if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
        list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
        $sql = "SELECT c.* $select
FROM {course} c
JOIN {event} e ON e.courseid = c.id
$join";
        $courses = $DB->get_records_sql($sql, null, 0, 20);
        foreach ($courses as $course) {
            context_instance_preload($course);
        }
        return $courses;
    }

    $courses = enrol_get_my_courses();

    return $courses;
}

/**
* Display calendar preference button
*
* @param stdClass $course course object
* @return string return preference button in html
*/
function calendar_preferences_button(stdClass $course) {
    global $OUTPUT;

    // Guests have no preferences
    if (!isloggedin() || isguestuser()) {
        return '';
    }

    return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
}

/**
* Get event format time
*
* @param calendar_event $event event object
* @param int $now current time in gmt
* @param array $linkparams list of params for event link
* @param bool $usecommonwords the words as formatted date/time.
* @param int $showtime determine the show time GMT timestamp
* @return string $eventtime link/string for event time
*/
function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
    $startdate = usergetdate($event->timestart);
    $enddate = usergetdate($event->timestart + $event->timeduration);
    $usermidnightstart = usergetmidnight($event->timestart);

    if($event->timeduration) {
        // To avoid doing the math if one IF is enough :)
        $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
    }
    else {
        $usermidnightend = $usermidnightstart;
    }

    if (empty($linkparams) || !is_array($linkparams)) {
        $linkparams = array();
    }
    $linkparams['view'] = 'day';

    // OK, now to get a meaningful display...
    // First of all we have to construct a human-readable date/time representation

    if($event->timeduration) {
        // It has a duration
        if($usermidnightstart == $usermidnightend ||
           ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
           ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
            // But it's all on the same day
            $timestart = calendar_time_representation($event->timestart);
            $timeend = calendar_time_representation($event->timestart + $event->timeduration);
            $time = $timestart.' <strong>&raquo;</strong> '.$timeend;

            if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
                $time = get_string('allday', 'calendar');
            }

            // Set printable representation
            if (!$showtime) {
                $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
                $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
                $eventtime = html_writer::link($url, $day).', '.$time;
            } else {
                $eventtime = $time;
            }
        } else {
            // It spans two or more days
            $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
            if ($showtime == $usermidnightstart) {
                $daystart = '';
            }
            $timestart = calendar_time_representation($event->timestart);
            $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
            if ($showtime == $usermidnightend) {
                $dayend = '';
            }
            $timeend = calendar_time_representation($event->timestart + $event->timeduration);

            // Set printable representation
            if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
                $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
                $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
            } else {
                $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
                $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';

                $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
                $eventtime .= html_writer::link($url, $dayend).$timeend;
            }
        }
    } else {
        $time = calendar_time_representation($event->timestart);

        // Set printable representation
        if (!$showtime) {
            $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
            $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
            $eventtime = html_writer::link($url, $day).', '.trim($time);
        } else {
            $eventtime = $time;
        }
    }

    if($event->timestart + $event->timeduration < $now) {
        // It has expired
        $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
    }

    return $eventtime;
}

/**
* Display month selector options
*
* @param string $name for the select element
* @param string|array $selected options for select elements
*/
function calendar_print_month_selector($name, $selected) {
    $months = array();
    for ($i=1; $i<=12; $i++) {
        $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
    }
    echo html_writer::select($months, $name, $selected, false);
}

/**
* Checks to see if the requested type of event should be shown for the given user.
*
* @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
* The type to check the display for (default is to display all)
* @param stdClass|int|null $user The user to check for - by default the current user
* @return bool True if the tyep should be displayed false otherwise
*/
function calendar_show_event_type($type, $user = null) {
    $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
    if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
        global $SESSION;
        if (!isset($SESSION->calendarshoweventtype)) {
            $SESSION->calendarshoweventtype = $default;
        }
        return $SESSION->calendarshoweventtype & $type;
    } else {
        return get_user_preferences('calendar_savedflt', $default, $user) & $type;
    }
}

/**
* Sets the display of the event type given $display.
*
* If $display = true the event type will be shown.
* If $display = false the event type will NOT be shown.
* If $display = null the current value will be toggled and saved.
*
* @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
* @param bool $display option to display event type
* @param stdClass|int $user moodle user object or id, null means current user
*/
function calendar_set_event_type_display($type, $display = null, $user = null) {
    $persist = get_user_preferences('calendar_persistflt', 0, $user);
    $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
    if ($persist === 0) {
        global $SESSION;
        if (!isset($SESSION->calendarshoweventtype)) {
            $SESSION->calendarshoweventtype = $default;
        }
        $preference = $SESSION->calendarshoweventtype;
    } else {
        $preference = get_user_preferences('calendar_savedflt', $default, $user);
    }
    $current = $preference & $type;
    if ($display === null) {
        $display = !$current;
    }
    if ($display && !$current) {
        $preference += $type;
    } else if (!$display && $current) {
        $preference -= $type;
    }
    if ($persist === 0) {
        $SESSION->calendarshoweventtype = $preference;
    } else {
        if ($preference == $default) {
            unset_user_preference('calendar_savedflt', $user);
        } else {
            set_user_preference('calendar_savedflt', $preference, $user);
        }
    }
}

/**
* Get calendar's allowed types
*
* @param stdClass $allowed list of allowed edit for event type
* @param stdClass|int $course object of a course or course id
*/
function calendar_get_allowed_types(&$allowed, $course = null) {
    global $USER, $CFG, $DB;
    $allowed = new stdClass();
    $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
    $allowed->groups = false; // This may change just below
    $allowed->courses = false; // This may change just below
    $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));

    if (!empty($course)) {
        if (!is_object($course)) {
            $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
        }
        if ($course->id != SITEID) {
            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);

            if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
                $allowed->courses = array($course->id => 1);

                if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
                    $allowed->groups = groups_get_all_groups($course->id);
                }
            } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
                if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
                    $allowed->groups = groups_get_all_groups($course->id);
                }
            }
        }
    }
}

/**
* See if user can add calendar entries at all
* used to print the "New Event" button
*
* @param stdClass $course object of a course or course id
* @return bool has the capability to add at least one event type
*/
function calendar_user_can_add_event($course) {
    if (!isloggedin() || isguestuser()) {
        return false;
    }
    calendar_get_allowed_types($allowed, $course);
    return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
}

/**
* Check wether the current user is permitted to add events
*
* @param stdClass $event object of event
* @return bool has the capability to add event
*/
function calendar_add_event_allowed($event) {
    global $USER, $DB;

    // can not be using guest account
    if (!isloggedin() or isguestuser()) {
        return false;
    }

    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    // if user has manageentries at site level, always return true
    if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
        return true;
    }

    switch ($event->eventtype) {
        case 'course':
            return has_capability('moodle/calendar:manageentries', $event->context);

        case 'group':
            // Allow users to add/edit group events if:
            // 1) They have manageentries (= entries for whole course)
            // 2) They have managegroupentries AND are in the group
            $group = $DB->get_record('groups', array('id'=>$event->groupid));
            return $group && (
                has_capability('moodle/calendar:manageentries', $event->context) ||
                (has_capability('moodle/calendar:managegroupentries', $event->context)
                    && groups_is_member($event->groupid)));

        case 'user':
            if ($event->userid == $USER->id) {
                return (has_capability('moodle/calendar:manageownentries', $event->context));
            }
            //there is no 'break;' intentionally

        case 'site':
            return has_capability('moodle/calendar:manageentries', $event->context);

        default:
            return has_capability('moodle/calendar:manageentries', $event->context);
    }
}

/**
* Manage calendar events
*
* This class provides the required functionality in order to manage calendar events.
* It was introduced as part of Moodle 2.0 and was created in order to provide a
* better framework for dealing with calendar events in particular regard to file
* handling through the new file API
*
* @package core_calendar
* @category calendar
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
* @property int $id The id within the event table
* @property string $name The name of the event
* @property string $description The description of the event
* @property int $format The format of the description FORMAT_?
* @property int $courseid The course the event is associated with (0 if none)
* @property int $groupid The group the event is associated with (0 if none)
* @property int $userid The user the event is associated with (0 if none)
* @property int $repeatid If this is a repeated event this will be set to the
* id of the original
* @property string $modulename If added by a module this will be the module name
* @property int $instance If added by a module this will be the module instance
* @property string $eventtype The event type
* @property int $timestart The start time as a timestamp
* @property int $timeduration The duration of the event in seconds
* @property int $visible 1 if the event is visible
* @property int $uuid ?
* @property int $sequence ?
* @property int $timemodified The time last modified as a timestamp
*/
class calendar_event {

    /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
    protected $properties = null;

    /**
* @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
    protected $_description = null;

    /** @var array The options to use with this description editor */
    protected $editoroptions = array(
            'subdirs'=>false,
            'forcehttps'=>false,
            'maxfiles'=>-1,
            'maxbytes'=>null,
            'trusttext'=>false);

    /** @var object The context to use with the description editor */
    protected $editorcontext = null;

    /**
* Instantiates a new event and optionally populates its properties with the
* data provided
*
* @param stdClass $data Optional. An object containing the properties to for
* an event
*/
    public function __construct($data=null) {
        global $CFG, $USER;

        // First convert to object if it is not already (should either be object or assoc array)
        if (!is_object($data)) {
            $data = (object)$data;
        }

        $this->editoroptions['maxbytes'] = $CFG->maxbytes;

        $data->eventrepeats = 0;

        if (empty($data->id)) {
            $data->id = null;
        }

        // Default to a user event
        if (empty($data->eventtype)) {
            $data->eventtype = 'user';
        }

        // Default to the current user
        if (empty($data->userid)) {
            $data->userid = $USER->id;
        }

        if (!empty($data->timeduration) && is_array($data->timeduration)) {
            $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
        }
        if (!empty($data->description) && is_array($data->description)) {
            $data->format = $data->description['format'];
            $data->description = $data->description['text'];
        } else if (empty($data->description)) {
            $data->description = '';
            $data->format = editors_get_preferred_format();
        }
        // Ensure form is defaulted correctly
        if (empty($data->format)) {
            $data->format = editors_get_preferred_format();
        }

        if (empty($data->context)) {
            $data->context = $this->calculate_context($data);
        }
        $this->properties = $data;
    }

    /**
* Magic property method
*
* Attempts to call a set_$key method if one exists otherwise falls back
* to simply set the property
*
* @param string $key property name
* @param mixed $value value of the property
*/
    public function __set($key, $value) {
        if (method_exists($this, 'set_'.$key)) {
            $this->{'set_'.$key}($value);
        }
        $this->properties->{$key} = $value;
    }

    /**
* Magic get method
*
* Attempts to call a get_$key method to return the property and ralls over
* to return the raw property
*
* @param string $key property name
* @return mixed property value
*/
    public function __get($key) {
        if (method_exists($this, 'get_'.$key)) {
            return $this->{'get_'.$key}();
        }
        if (!isset($this->properties->{$key})) {
            throw new coding_exception('Undefined property requested');
        }
        return $this->properties->{$key};
    }

    /**
* Stupid PHP needs an isset magic method if you use the get magic method and
* still want empty calls to work.... blah ~!
*
* @param string $key $key property name
* @return bool|mixed property value, false if property is not exist
*/
    public function __isset($key) {
        return !empty($this->properties->{$key});
    }

    /**
* Calculate the context value needed for calendar_event.
* Event's type can be determine by the available value store in $data
* It is important to check for the existence of course/courseid to determine
* the course event.
* Default value is set to CONTEXT_USER
*
* @param stdClass $data information about event
* @return stdClass The context object.
*/
    protected function calculate_context(stdClass $data) {
        global $USER, $DB;

        $context = null;
        if (isset($data->courseid) && $data->courseid > 0) {
            $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
        } else if (isset($data->course) && $data->course > 0) {
            $context = get_context_instance(CONTEXT_COURSE, $data->course);
        } else if (isset($data->groupid) && $data->groupid > 0) {
            $group = $DB->get_record('groups', array('id'=>$data->groupid));
            $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
        } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
            $context = get_context_instance(CONTEXT_USER, $data->userid);
        } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
                   isset($data->instance) && $data->instance > 0) {
            $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
            $context = get_context_instance(CONTEXT_COURSE, $cm->course);
        } else {
            $context = get_context_instance(CONTEXT_USER);
        }

        return $context;
    }

    /**
* Returns an array of editoroptions for this event: Called by __get
* Please use $blah = $event->editoroptions;
*
* @return array event editor options
*/
    protected function get_editoroptions() {
        return $this->editoroptions;
    }

    /**
* Returns an event description: Called by __get
* Please use $blah = $event->description;
*
* @return string event description
*/
    protected function get_description() {
        global $CFG;

        require_once($CFG->libdir . '/filelib.php');

        if ($this->_description === null) {
            // Check if we have already resolved the context for this event
            if ($this->editorcontext === null) {
                // Switch on the event type to decide upon the appropriate context
                // to use for this event
                $this->editorcontext = $this->properties->context;
                if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
                        && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
                    return clean_text($this->properties->description, $this->properties->format);
                }
            }

            // Work out the item id for the editor, if this is a repeated event then the files will
            // be associated with the original
            if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
                $itemid = $this->properties->repeatid;
            } else {
                $itemid = $this->properties->id;
            }

            // Convert file paths in the description so that things display correctly
            $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
            // Clean the text so no nasties get through
            $this->_description = clean_text($this->_description, $this->properties->format);
        }
        // Finally return the description
        return $this->_description;
    }

    /**
* Return the number of repeat events there are in this events series
*
* @return int number of event repeated
*/
    public function count_repeats() {
        global $DB;
        if (!empty($this->properties->repeatid)) {
            $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
            // We don't want to count ourselves
            $this->properties->eventrepeats--;
        }
        return $this->properties->eventrepeats;
    }

    /**
* Update or create an event within the database
*
* Pass in a object containing the event properties and this function will
* insert it into the database and deal with any associated files
*
* @see add_event()
* @see update_event()
*
* @param stdClass $data object of event
* @param bool $checkcapability if moodle should check calendar managing capability or not
* @return bool event updated
*/
    public function update($data, $checkcapability=true) {
        global $CFG, $DB, $USER;

        foreach ($data as $key=>$value) {
            $this->properties->$key = $value;
        }

        $this->properties->timemodified = time();
        $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));

        if (empty($this->properties->id) || $this->properties->id < 1) {

            if ($checkcapability) {
                if (!calendar_add_event_allowed($this->properties)) {
                    print_error('nopermissiontoupdatecalendar');
                }
            }

            if ($usingeditor) {
                switch ($this->properties->eventtype) {
                    case 'user':
                        $this->editorcontext = $this->properties->context;
                        $this->properties->courseid = 0;
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
                    case 'site':
                        $this->editorcontext = $this->properties->context;
                        $this->properties->courseid = SITEID;
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
                    case 'course':
                        $this->editorcontext = $this->properties->context;
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
                    case 'group':
                        $this->editorcontext = $this->properties->context;
                        $this->properties->userid = $USER->id;
                        break;
                    default:
                        // Ewww we should NEVER get here, but just incase we do lets
                        // fail gracefully
                        $usingeditor = false;
                        break;
                }

                $editor = $this->properties->description;
                $this->properties->format = $this->properties->description['format'];
                $this->properties->description = $this->properties->description['text'];
            }

            // Insert the event into the database
            $this->properties->id = $DB->insert_record('event', $this->properties);

            if ($usingeditor) {
                $this->properties->description = file_save_draft_area_files(
                                                $editor['itemid'],
                                                $this->editorcontext->id,
                                                'calendar',
                                                'event_description',
                                                $this->properties->id,
                                                $this->editoroptions,
                                                $editor['text'],
                                                $this->editoroptions['forcehttps']);

                $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
            }

            // Log the event entry.
            add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);

            $repeatedids = array();

            if (!empty($this->properties->repeat)) {
                $this->properties->repeatid = $this->properties->id;
                $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));

                $eventcopy = clone($this->properties);
                unset($eventcopy->id);

                for($i = 1; $i < $eventcopy->repeats; $i++) {

                    $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);

                    // Get the event id for the log record.
                    $eventcopyid = $DB->insert_record('event', $eventcopy);

                    // If the context has been set delete all associated files
                    if ($usingeditor) {
                        $fs = get_file_storage();
                        $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
                        foreach ($files as $file) {
                            $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
                        }
                    }

                    $repeatedids[] = $eventcopyid;
                    // Log the event entry.
                    add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
                }
            }

            // Hook for tracking added events
            self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
            return true;
        } else {

            if ($checkcapability) {
                if(!calendar_edit_event_allowed($this->properties)) {
                    print_error('nopermissiontoupdatecalendar');
                }
            }

            if ($usingeditor) {
                if ($this->editorcontext !== null) {
                    $this->properties->description = file_save_draft_area_files(
                                                    $this->properties->description['itemid'],
                                                    $this->editorcontext->id,
                                                    'calendar',
                                                    'event_description',
                                                    $this->properties->id,
                                                    $this->editoroptions,
                                                    $this->properties->description['text'],
                                                    $this->editoroptions['forcehttps']);
                } else {
                    $this->properties->format = $this->properties->description['format'];
                    $this->properties->description = $this->properties->description['text'];
                }
            }

            $event = $DB->get_record('event', array('id'=>$this->properties->id));

            $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));

            if ($updaterepeated) {
                // Update all
                if ($this->properties->timestart != $event->timestart) {
                    $timestartoffset = $this->properties->timestart - $event->timestart;
                    $sql = "UPDATE {event}
SET name = ?,
description = ?,
timestart = timestart + ?,
timeduration = ?,
timemodified = ?
WHERE repeatid = ?";
                    $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
                } else {
                    $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
                    $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
                }
                $DB->execute($sql, $params);

                // Log the event update.
                add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
            } else {
                $DB->update_record('event', $this->properties);
                $event = calendar_event::load($this->properties->id);
                $this->properties = $event->properties();
                add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
            }

            // Hook for tracking event updates
            self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
            return true;
        }
    }

    /**
* Deletes an event and if selected an repeated events in the same series
*
* This function deletes an event, any associated events if $deleterepeated=true,
* and cleans up any files associated with the events.
*
* @see delete_event()
*
* @param bool $deleterepeated delete event repeatedly
* @return bool succession of deleting event
*/
    public function delete($deleterepeated=false) {
        global $DB;

        // If $this->properties->id is not set then something is wrong
        if (empty($this->properties->id)) {
            debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
            return false;
        }

        // Delete the event
        $DB->delete_records('event', array('id'=>$this->properties->id));

        // If the editor context hasn't already been set then set it now
        if ($this->editorcontext === null) {
            $this->editorcontext = $this->properties->context;
        }

        // If the context has been set delete all associated files
        if ($this->editorcontext !== null) {
            $fs = get_file_storage();
            $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
            foreach ($files as $file) {
                $file->delete();
            }
        }

        // Fire the event deleted hook
        self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));

        // If we need to delete repeated events then we will fetch them all and delete one by one
        if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
            // Get all records where the repeatid is the same as the event being removed
            $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
            // For each of the returned events populate a calendar_event object and call delete
            // make sure the arg passed is false as we are already deleting all repeats
            foreach ($events as $event) {
                $event = new calendar_event($event);
                $event->delete(false);
            }
        }

        return true;
    }

    /**
* Fetch all event properties
*
* This function returns all of the events properties as an object and optionally
* can prepare an editor for the description field at the same time. This is
* designed to work when the properties are going to be used to set the default
* values of a moodle forms form.
*
* @param bool $prepareeditor If set to true a editor is prepared for use with
* the mforms editor element. (for description)
* @return stdClass Object containing event properties
*/
    public function properties($prepareeditor=false) {
        global $USER, $CFG, $DB;

        // First take a copy of the properties. We don't want to actually change the
        // properties or we'd forever be converting back and forwards between an
        // editor formatted description and not
        $properties = clone($this->properties);
        // Clean the description here
        $properties->description = clean_text($properties->description, $properties->format);

        // If set to true we need to prepare the properties for use with an editor
        // and prepare the file area
        if ($prepareeditor) {

            // We may or may not have a property id. If we do then we need to work
            // out the context so we can copy the existing files to the draft area
            if (!empty($properties->id)) {

                if ($properties->eventtype === 'site') {
                    // Site context
                    $this->editorcontext = $this->properties->context;
                } else if ($properties->eventtype === 'user') {
                    // User context
                    $this->editorcontext = $this->properties->context;
                } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
                    // First check the course is valid
                    $course = $DB->get_record('course', array('id'=>$properties->courseid));
                    if (!$course) {
                        print_error('invalidcourse');
                    }
                    // Course context
                    $this->editorcontext = $this->properties->context;
                    // We have a course and are within the course context so we had
                    // better use the courses max bytes value
                    $this->editoroptions['maxbytes'] = $course->maxbytes;
                } else {
                    // If we get here we have a custom event type as used by some
                    // modules. In this case the event will have been added by
                    // code and we won't need the editor
                    $this->editoroptions['maxbytes'] = 0;
                    $this->editoroptions['maxfiles'] = 0;
                }

                if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
                    $contextid = false;
                } else {
                    // Get the context id that is what we really want
                    $contextid = $this->editorcontext->id;
                }
            } else {

                // If we get here then this is a new event in which case we don't need a
                // context as there is no existing files to copy to the draft area.
                $contextid = null;
            }

            // If the contextid === false we don't support files so no preparing
            // a draft area
            if ($contextid !== false) {
                // Just encase it has already been submitted
                $draftiddescription = file_get_submitted_draft_itemid('description');
                // Prepare the draft area, this copies existing files to the draft area as well
                $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
            } else {
                $draftiddescription = 0;
            }

            // Structure the description field as the editor requires
            $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
        }

        // Finally return the properties
        return $properties;
    }

    /**
* Toggles the visibility of an event
*
* @param null|bool $force If it is left null the events visibility is flipped,
* If it is false the event is made hidden, if it is true it
* is made visible.
* @return bool if event is successfully updated, toggle will be visible
*/
    public function toggle_visibility($force=null) {
        global $CFG, $DB;

        // Set visible to the default if it is not already set
        if (empty($this->properties->visible)) {
            $this->properties->visible = 1;
        }

        if ($force === true || ($force !== false && $this->properties->visible == 0)) {
            // Make this event visible
            $this->properties->visible = 1;
            // Fire the hook
            self::calendar_event_hook('show_event', array($this->properties));
        } else {
            // Make this event hidden
            $this->properties->visible = 0;
            // Fire the hook
            self::calendar_event_hook('hide_event', array($this->properties));
        }

        // Update the database to reflect this change
        return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
    }

    /**
* Attempts to call the hook for the specified action should a calendar type
* by set $CFG->calendar, and the appopriate function defined
*
* @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
* @param array $args The args to pass to the hook, usually the event is the first element
* @return bool attempts to call event hook
*/
    public static function calendar_event_hook($action, array $args) {
        global $CFG;
        static $extcalendarinc;
        if ($extcalendarinc === null) {
            if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
                include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
                $extcalendarinc = true;
            } else {
                $extcalendarinc = false;
            }
        }
        if($extcalendarinc === false) {
            return false;
        }
        $hook = $CFG->calendar .'_'.$action;
        if (function_exists($hook)) {
            call_user_func_array($hook, $args);
            return true;
        }
        return false;
    }

    /**
* Returns a calendar_event object when provided with an event id
*
* This function makes use of MUST_EXIST, if the event id passed in is invalid
* it will result in an exception being thrown
*
* @param int|object $param event object or event id
* @return calendar_event|false status for loading calendar_event
*/
    public static function load($param) {
        global $DB;
        if (is_object($param)) {
            $event = new calendar_event($param);
        } else {
            $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
            $event = new calendar_event($event);
        }
        return $event;
    }

    /**
* Creates a new event and returns a calendar_event object
*
* @param object|array $properties An object containing event properties
* @return calendar_event|false The event object or false if it failed
*/
    public static function create($properties) {
        if (is_array($properties)) {
            $properties = (object)$properties;
        }
        if (!is_object($properties)) {
            throw new coding_exception('When creating an event properties should be either an object or an assoc array');
        }
        $event = new calendar_event($properties);
        if ($event->update($properties)) {
            return $event;
        } else {
            return false;
        }
    }
}

/**
* Calendar information class
*
* This class is used simply to organise the information pertaining to a calendar
* and is used primarily to make information easily available.
*
* @package core_calendar
* @category calendar
* @copyright 2010 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class calendar_information {
    /** @var int The day */
    public $day;

    /** @var int The month */
    public $month;

    /** @var int The year */
    public $year;

    /** @var int A course id */
    public $courseid = null;

    /** @var array An array of courses */
    public $courses = array();

    /** @var array An array of groups */
    public $groups = array();

    /** @var array An array of users */
    public $users = array();

    /**
* Creates a new instance
*
* @param int $day the number of the day
* @param int $month the number of the month
* @param int $year the number of the year
*/
    public function __construct($day=0, $month=0, $year=0) {

        $date = usergetdate(time());

        if (empty($day)) {
            $day = $date['mday'];
        }

        if (empty($month)) {
            $month = $date['mon'];
        }

        if (empty($year)) {
            $year = $date['year'];
        }

        $this->day = $day;
        $this->month = $month;
        $this->year = $year;
    }

    /**
* Initialize calendar information
*
* @param stdClass $course object
* @param array $coursestoload An array of courses [$course->id => $course]
* @param bool $ignorefilters options to use filter
*/
    public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
        $this->courseid = $course->id;
        $this->course = $course;
        list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
        $this->courses = $courses;
        $this->groups = $group;
        $this->users = $user;
    }

    /**
* Ensures the date for the calendar is correct and either sets it to now
* or throws a moodle_exception if not
*
* @param bool $defaultonow use current time
* @throws moodle_exception
* @return bool validation of checkdate
*/
    public function checkdate($defaultonow = true) {
        if (!checkdate($this->month, $this->day, $this->year)) {
            if ($defaultonow) {
                $now = usergetdate(time());
                $this->day = intval($now['mday']);
                $this->month = intval($now['mon']);
                $this->year = intval($now['year']);
                return true;
            } else {
                throw new moodle_exception('invaliddate');
            }
        }
        return true;
    }
    /**
* Gets todays timestamp for the calendar
*
* @return int today timestamp
*/
    public function timestamp_today() {
        return make_timestamp($this->year, $this->month, $this->day);
    }
    /**
* Gets tomorrows timestamp for the calendar
*
* @return int tomorrow timestamp
*/
    public function timestamp_tomorrow() {
        return make_timestamp($this->year, $this->month, $this->day+1);
    }
    /**
* Adds the pretend blocks for teh calendar
*
* @param core_calendar_renderer $renderer
* @param bool $showfilters display filters, false is set as default
* @param string|null $view preference view options (eg: day, month, upcoming)
*/
    public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
        if ($showfilters) {
            $filters = new block_contents();
            $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
            $filters->footer = '';
            $filters->title = get_string('eventskey', 'calendar');
            $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
        }
        $block = new block_contents;
        $block->content = $renderer->fake_block_threemonths($this);
        $block->footer = '';
        $block->title = get_string('monthlyview', 'calendar');
        $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
    }
}
Something went wrong with that request. Please try again.