Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 1defeabf2c
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 4531 lines (3913 sloc) 181.053 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* This file contains the definition for the class assignment
*
* This class provides all the functionality for the new assign module.
*
* @package mod_assign
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

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

/**
* Assignment submission statuses
*/
define('ASSIGN_SUBMISSION_STATUS_DRAFT', 'draft'); // student thinks it is a draft
define('ASSIGN_SUBMISSION_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished

/**
* Search filters for grading page
*/
define('ASSIGN_FILTER_SUBMITTED', 'submitted');
define('ASSIGN_FILTER_SINGLE_USER', 'singleuser');
define('ASSIGN_FILTER_REQUIRE_GRADING', 'require_grading');

/** Include accesslib.php */
require_once($CFG->libdir.'/accesslib.php');
/** Include formslib.php */
require_once($CFG->libdir.'/formslib.php');
/** Include repository/lib.php */
require_once($CFG->dirroot . '/repository/lib.php');
/** Include local mod_form.php */
require_once($CFG->dirroot.'/mod/assign/mod_form.php');
/** gradelib.php */
require_once($CFG->libdir.'/gradelib.php');
/** grading lib.php */
require_once($CFG->dirroot.'/grade/grading/lib.php');
/** Include feedbackplugin.php */
require_once($CFG->dirroot.'/mod/assign/feedbackplugin.php');
/** Include submissionplugin.php */
require_once($CFG->dirroot.'/mod/assign/submissionplugin.php');
/** Include renderable.php */
require_once($CFG->dirroot.'/mod/assign/renderable.php');
/** Include gradingtable.php */
require_once($CFG->dirroot.'/mod/assign/gradingtable.php');
/** Include eventslib.php */
require_once($CFG->libdir.'/eventslib.php');


/**
* Standard base class for mod_assign (assignment types).
*
* @package mod_assign
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class assign {


    /** @var stdClass the assignment record that contains the global settings for this assign instance */
    private $instance;

    /** @var context the context of the course module for this assign instance (or just the course if we are
creating a new one) */
    private $context;

    /** @var stdClass the course this assign instance belongs to */
    private $course;

    /** @var stdClass the admin config for all assign instances */
    private $adminconfig;


    /** @var assign_renderer the custom renderer for this module */
    private $output;

    /** @var stdClass the course module for this assign instance */
    private $coursemodule;

    /** @var array cache for things like the coursemodule name or the scale menu - only lives for a single
request */
    private $cache;

    /** @var array list of the installed submission plugins */
    private $submissionplugins;

    /** @var array list of the installed feedback plugins */
    private $feedbackplugins;

    /** @var string action to be used to return to this page (without repeating any form submissions etc.) */
    private $returnaction = 'view';

    /** @var array params to be used to return to this page */
    private $returnparams = array();

    /** @var string modulename prevents excessive calls to get_string */
    private static $modulename = null;

    /** @var string modulenameplural prevents excessive calls to get_string */
    private static $modulenameplural = null;

    /**
* Constructor for the base assign class
*
* @param mixed $coursemodulecontext context|null the course module context (or the course context if the coursemodule has not been created yet)
* @param mixed $coursemodule the current course module if it was already loaded - otherwise this class will load one from the context as required
* @param mixed $course the current course if it was already loaded - otherwise this class will load one from the context as required
*/
    public function __construct($coursemodulecontext, $coursemodule, $course) {
        global $PAGE;

        $this->context = $coursemodulecontext;
        $this->coursemodule = $coursemodule;
        $this->course = $course;
        $this->cache = array(); // temporary cache only lives for a single request - used to reduce db lookups

        $this->submissionplugins = $this->load_plugins('assignsubmission');
        $this->feedbackplugins = $this->load_plugins('assignfeedback');
    }

    /**
* Set the action and parameters that can be used to return to the current page
*
* @param string $action The action for the current page
* @param array $params An array of name value pairs which form the parameters to return to the current page
* @return void
*/
    public function register_return_link($action, $params) {
        $this->returnaction = $action;
        $this->returnparams = $params;
    }

    /**
* Return an action that can be used to get back to the current page
* @return string action
*/
    public function get_return_action() {
        return $this->returnaction;
    }

    /**
* Based on the current assignment settings should we display the intro
* @return bool showintro
*/
    private function show_intro() {
        if ($this->get_instance()->alwaysshowdescription ||
                time() > $this->get_instance()->allowsubmissionsfromdate) {
            return true;
        }
        return false;
    }

    /**
* Return a list of parameters that can be used to get back to the current page
* @return array params
*/
    public function get_return_params() {
        return $this->returnparams;
    }

    /**
* Set the submitted form data
* @param stdClass $data The form data (instance)
*/
    public function set_instance(stdClass $data) {
        $this->instance = $data;
    }

    /**
* Set the context
* @param context $context The new context
*/
    public function set_context(context $context) {
        $this->context = $context;
    }

    /**
* Set the course data
* @param stdClass $course The course data
*/
    public function set_course(stdClass $course) {
        $this->course = $course;
    }

    /**
* get list of feedback plugins installed
* @return array
*/
    public function get_feedback_plugins() {
        return $this->feedbackplugins;
    }

    /**
* get list of submission plugins installed
* @return array
*/
    public function get_submission_plugins() {
        return $this->submissionplugins;
    }

    /**
* Is blind marking enabled and reveal identities not set yet?
*
* @return bool
*/
    public function is_blind_marking() {
        return $this->get_instance()->blindmarking && !$this->get_instance()->revealidentities;
    }

    /**
* Does an assignment have submission(s) or grade(s) already?
*
* @return bool
*/
    public function has_submissions_or_grades() {
        $allgrades = $this->count_grades();
        $allsubmissions = $this->count_submissions();
        if (($allgrades == 0) && ($allsubmissions == 0)) {
            return false;
        }
        return true;
    }

    /**
* get a specific submission plugin by its type
* @param string $subtype assignsubmission | assignfeedback
* @param string $type
* @return mixed assign_plugin|null
*/
    public function get_plugin_by_type($subtype, $type) {
        $shortsubtype = substr($subtype, strlen('assign'));
        $name = $shortsubtype . 'plugins';
        if ($name != 'feedbackplugins' && $name != 'submissionplugins') {
            return null;
        }
        $pluginlist = $this->$name;
        foreach ($pluginlist as $plugin) {
            if ($plugin->get_type() == $type) {
                return $plugin;
            }
        }
        return null;
    }

    /**
* Get a feedback plugin by type
* @param string $type - The type of plugin e.g comments
* @return mixed assign_feedback_plugin|null
*/
    public function get_feedback_plugin_by_type($type) {
        return $this->get_plugin_by_type('assignfeedback', $type);
    }

    /**
* Get a submission plugin by type
* @param string $type - The type of plugin e.g comments
* @return mixed assign_submission_plugin|null
*/
    public function get_submission_plugin_by_type($type) {
        return $this->get_plugin_by_type('assignsubmission', $type);
    }

    /**
* Load the plugins from the sub folders under subtype
* @param string $subtype - either submission or feedback
* @return array - The sorted list of plugins
*/
    private function load_plugins($subtype) {
        global $CFG;
        $result = array();

        $names = get_plugin_list($subtype);

        foreach ($names as $name => $path) {
            if (file_exists($path . '/locallib.php')) {
                require_once($path . '/locallib.php');

                $shortsubtype = substr($subtype, strlen('assign'));
                $pluginclass = 'assign_' . $shortsubtype . '_' . $name;

                $plugin = new $pluginclass($this, $name);

                if ($plugin instanceof assign_plugin) {
                    $idx = $plugin->get_sort_order();
                    while (array_key_exists($idx, $result)) $idx +=1;
                    $result[$idx] = $plugin;
                }
            }
        }
        ksort($result);
        return $result;
    }

    /**
* Display the assignment, used by view.php
*
* The assignment is displayed differently depending on your role,
* the settings for the assignment and the status of the assignment.
* @param string $action The current action if any.
* @return void
*/
    public function view($action='') {

        $o = '';
        $mform = null;

        // handle form submissions first
        if ($action == 'savesubmission') {
            $action = 'editsubmission';
            if ($this->process_save_submission($mform)) {
                $action = 'view';
            }
        } else if ($action == 'lock') {
            $this->process_lock();
            $action = 'grading';
        } else if ($action == 'reverttodraft') {
            $this->process_revert_to_draft();
            $action = 'grading';
        } else if ($action == 'unlock') {
            $this->process_unlock();
            $action = 'grading';
        } else if ($action == 'confirmsubmit') {
            $action = 'submit';
            if ($this->process_submit_for_grading($mform)) {
                $action = 'view';
            }
        } else if ($action == 'gradingbatchoperation') {
            $action = $this->process_grading_batch_operation($mform);
        } else if ($action == 'submitgrade') {
            if (optional_param('saveandshownext', null, PARAM_RAW)) {
                //save and show next
                $action = 'grade';
                if ($this->process_save_grade($mform)) {
                    $action = 'nextgrade';
                }
            } else if (optional_param('nosaveandprevious', null, PARAM_RAW)) {
                $action = 'previousgrade';
            } else if (optional_param('nosaveandnext', null, PARAM_RAW)) {
                //show next button
                $action = 'nextgrade';
            } else if (optional_param('savegrade', null, PARAM_RAW)) {
                //save changes button
                $action = 'grade';
                if ($this->process_save_grade($mform)) {
                    $action = 'grading';
                }
            } else {
                //cancel button
                $action = 'grading';
            }
        } else if ($action == 'quickgrade') {
            $message = $this->process_save_quick_grades();
            $action = 'quickgradingresult';
        } else if ($action == 'saveoptions') {
            $this->process_save_grading_options();
            $action = 'grading';
        } else if ($action == 'saveextension') {
            $action = 'grantextension';
            if ($this->process_save_extension($mform)) {
                $action = 'grading';
            }
        } else if ($action == 'revealidentitiesconfirm') {
            $this->process_reveal_identities();
            $action = 'grading';
        }

        $returnparams = array('rownum'=>optional_param('rownum', 0, PARAM_INT));
        $this->register_return_link($action, $returnparams);

        // now show the right view page
        if ($action == 'previousgrade') {
            $mform = null;
            $o .= $this->view_single_grade_page($mform, -1);
        } else if ($action == 'quickgradingresult') {
            $mform = null;
            $o .= $this->view_quickgrading_result($message);
        } else if ($action == 'nextgrade') {
            $mform = null;
            $o .= $this->view_single_grade_page($mform, 1);
        } else if ($action == 'grade') {
            $o .= $this->view_single_grade_page($mform);
        } else if ($action == 'viewpluginassignfeedback') {
            $o .= $this->view_plugin_content('assignfeedback');
        } else if ($action == 'viewpluginassignsubmission') {
            $o .= $this->view_plugin_content('assignsubmission');
        } else if ($action == 'editsubmission') {
            $o .= $this->view_edit_submission_page($mform);
        } else if ($action == 'grading') {
            $o .= $this->view_grading_page();
        } else if ($action == 'downloadall') {
            $o .= $this->download_submissions();
        } else if ($action == 'submit') {
            $o .= $this->check_submit_for_grading($mform);
        } else if ($action == 'grantextension') {
            $o .= $this->view_grant_extension($mform);
        } else if ($action == 'revealidentities') {
            $o .= $this->view_reveal_identities_confirm($mform);
        } else if ($action == 'plugingradingbatchoperation') {
            $o .= $this->view_plugin_grading_batch_operation($mform);
        } else if ($action == 'viewpluginpage') {
             $o .= $this->view_plugin_page();
        } else {
            $o .= $this->view_submission_page();
        }

        return $o;
    }


    /**
* Add this instance to the database
*
* @param stdClass $formdata The data submitted from the form
* @param bool $callplugins This is used to skip the plugin code
* when upgrading an old assignment to a new one (the plugins get called manually)
* @return mixed false if an error occurs or the int id of the new instance
*/
    public function add_instance(stdClass $formdata, $callplugins) {
        global $DB;

        $err = '';

        // add the database record
        $update = new stdClass();
        $update->name = $formdata->name;
        $update->timemodified = time();
        $update->timecreated = time();
        $update->course = $formdata->course;
        $update->courseid = $formdata->course;
        $update->intro = $formdata->intro;
        $update->introformat = $formdata->introformat;
        $update->alwaysshowdescription = $formdata->alwaysshowdescription;
        $update->submissiondrafts = $formdata->submissiondrafts;
        $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
        $update->sendnotifications = $formdata->sendnotifications;
        $update->sendlatenotifications = $formdata->sendlatenotifications;
        $update->duedate = $formdata->duedate;
        $update->cutoffdate = $formdata->cutoffdate;
        $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
        $update->grade = $formdata->grade;
        $update->completionsubmit = !empty($formdata->completionsubmit);
        $update->teamsubmission = $formdata->teamsubmission;
        $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
        $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
        $update->blindmarking = $formdata->blindmarking;

        $returnid = $DB->insert_record('assign', $update);
        $this->instance = $DB->get_record('assign', array('id'=>$returnid), '*', MUST_EXIST);
        // cache the course record
        $this->course = $DB->get_record('course', array('id'=>$formdata->course), '*', MUST_EXIST);

        if ($callplugins) {
            // call save_settings hook for submission plugins
            foreach ($this->submissionplugins as $plugin) {
                if (!$this->update_plugin_instance($plugin, $formdata)) {
                    print_error($plugin->get_error());
                    return false;
                }
            }
            foreach ($this->feedbackplugins as $plugin) {
                if (!$this->update_plugin_instance($plugin, $formdata)) {
                    print_error($plugin->get_error());
                    return false;
                }
            }

            // in the case of upgrades the coursemodule has not been set so we need to wait before calling these two
            // TODO: add event to the calendar
            $this->update_calendar($formdata->coursemodule);
            // TODO: add the item in the gradebook
            $this->update_gradebook(false, $formdata->coursemodule);

        }

        $update = new stdClass();
        $update->id = $this->get_instance()->id;
        $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
        $DB->update_record('assign', $update);

        return $returnid;
    }

    /**
* Delete all grades from the gradebook for this assignment
*
* @return bool
*/
    private function delete_grades() {
        global $CFG;

        return grade_update('mod/assign', $this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, 0, NULL, array('deleted'=>1)) == GRADE_UPDATE_OK;
    }

    /**
* Delete this instance from the database
*
* @return bool false if an error occurs
*/
    public function delete_instance() {
        global $DB;
        $result = true;

        foreach ($this->submissionplugins as $plugin) {
            if (!$plugin->delete_instance()) {
                print_error($plugin->get_error());
                $result = false;
            }
        }
        foreach ($this->feedbackplugins as $plugin) {
            if (!$plugin->delete_instance()) {
                print_error($plugin->get_error());
                $result = false;
            }
        }

        // delete files associated with this assignment
        $fs = get_file_storage();
        if (! $fs->delete_area_files($this->context->id) ) {
            $result = false;
        }

        // delete_records will throw an exception if it fails - so no need for error checking here

        $DB->delete_records('assign_submission', array('assignment'=>$this->get_instance()->id));
        $DB->delete_records('assign_grades', array('assignment'=>$this->get_instance()->id));
        $DB->delete_records('assign_plugin_config', array('assignment'=>$this->get_instance()->id));

        // delete items from the gradebook
        if (! $this->delete_grades()) {
            $result = false;
        }

        // delete the instance
        $DB->delete_records('assign', array('id'=>$this->get_instance()->id));

        return $result;
    }

    /**
* Actual implementation of the reset course functionality, delete all the
* assignment submissions for course $data->courseid.
*
* @param $data the data submitted from the reset course.
* @return array status array
*/
    public function reset_userdata($data) {
        global $CFG,$DB;

        $componentstr = get_string('modulenameplural', 'assign');
        $status = array();

        $fs = get_file_storage();
        if (!empty($data->reset_assign_submissions)) {
            // Delete files associated with this assignment.
            foreach ($this->submissionplugins as $plugin) {
                $fileareas = array();
                $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
                $fileareas = $plugin->get_file_areas();
                foreach ($fileareas as $filearea) {
                    $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
                }

                if (!$plugin->delete_instance()) {
                    $status[] = array('component'=>$componentstr,
                                      'item'=>get_string('deleteallsubmissions','assign'),
                                      'error'=>$plugin->get_error());
                }
            }

            foreach ($this->feedbackplugins as $plugin) {
                $fileareas = array();
                $plugincomponent = $plugin->get_subtype() . '_' . $plugin->get_type();
                $fileareas = $plugin->get_file_areas();
                foreach ($fileareas as $filearea) {
                    $fs->delete_area_files($this->context->id, $plugincomponent, $filearea);
                }

                if (!$plugin->delete_instance()) {
                    $status[] = array('component'=>$componentstr,
                                      'item'=>get_string('deleteallsubmissions','assign'),
                                      'error'=>$plugin->get_error());
                }
            }

            $assignssql = "SELECT a.id
FROM {assign} a
WHERE a.course=:course";
            $params = array ("course" => $data->courseid);

            $DB->delete_records_select('assign_submission', "assignment IN ($assignssql)", $params);
            $status[] = array('component'=>$componentstr,
                              'item'=>get_string('deleteallsubmissions','assign'),
                              'error'=>false);

            if (empty($data->reset_gradebook_grades)) {
                // Remove all grades from gradebook.
                require_once($CFG->dirroot.'/mod/assign/lib.php');
                assign_reset_gradebook($data->courseid);
            }
        }
        // Updating dates - shift may be negative too.
        if ($data->timeshift) {
            shift_course_mod_dates('assign',
                                    array('duedate', 'allowsubmissionsfromdate','cutoffdate'),
                                    $data->timeshift,
                                    $data->courseid);
            $status[] = array('component'=>$componentstr,
                              'item'=>get_string('datechanged'),
                              'error'=>false);
        }

        return $status;
    }

    /**
* Update the settings for a single plugin
*
* @param assign_plugin $plugin The plugin to update
* @param stdClass $formdata The form data
* @return bool false if an error occurs
*/
    private function update_plugin_instance(assign_plugin $plugin, stdClass $formdata) {
        if ($plugin->is_visible()) {
            $enabledname = $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled';
            if ($formdata->$enabledname) {
                $plugin->enable();
                if (!$plugin->save_settings($formdata)) {
                    print_error($plugin->get_error());
                    return false;
                }
            } else {
                $plugin->disable();
            }
        }
        return true;
    }

    /**
* Update the gradebook information for this assignment
*
* @param bool $reset If true, will reset all grades in the gradbook for this assignment
* @param int $coursemoduleid This is required because it might not exist in the database yet
* @return bool
*/
    public function update_gradebook($reset, $coursemoduleid) {
         global $CFG;
        /** Include lib.php */
        require_once($CFG->dirroot.'/mod/assign/lib.php');
        $assign = clone $this->get_instance();
        $assign->cmidnumber = $coursemoduleid;
        $param = null;
        if ($reset) {
            $param = 'reset';
        }

        return assign_grade_item_update($assign, $param);
    }

    /** Load and cache the admin config for this module
*
* @return stdClass the plugin config
*/
    public function get_admin_config() {
        if ($this->adminconfig) {
            return $this->adminconfig;
        }
        $this->adminconfig = get_config('assign');
        return $this->adminconfig;
    }


    /**
* Update the calendar entries for this assignment
*
* @param int $coursemoduleid - Required to pass this in because it might not exist in the database yet
* @return bool
*/
    public function update_calendar($coursemoduleid) {
        global $DB, $CFG;
        require_once($CFG->dirroot.'/calendar/lib.php');

        // special case for add_instance as the coursemodule has not been set yet.

        if ($this->get_instance()->duedate) {
            $event = new stdClass();

            if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id))) {

                $event->name = $this->get_instance()->name;

                $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
                $event->timestart = $this->get_instance()->duedate;

                $calendarevent = calendar_event::load($event->id);
                $calendarevent->update($event);
            } else {
                $event = new stdClass();
                $event->name = $this->get_instance()->name;
                $event->description = format_module_intro('assign', $this->get_instance(), $coursemoduleid);
                $event->courseid = $this->get_instance()->course;
                $event->groupid = 0;
                $event->userid = 0;
                $event->modulename = 'assign';
                $event->instance = $this->get_instance()->id;
                $event->eventtype = 'due';
                $event->timestart = $this->get_instance()->duedate;
                $event->timeduration = 0;

                calendar_event::create($event);
            }
        } else {
            $DB->delete_records('event', array('modulename'=>'assign', 'instance'=>$this->get_instance()->id));
        }
    }


    /**
* Update this instance in the database
*
* @param stdClass $formdata - the data submitted from the form
* @return bool false if an error occurs
*/
    public function update_instance($formdata) {
        global $DB;

        $update = new stdClass();
        $update->id = $formdata->instance;
        $update->name = $formdata->name;
        $update->timemodified = time();
        $update->course = $formdata->course;
        $update->intro = $formdata->intro;
        $update->introformat = $formdata->introformat;
        $update->alwaysshowdescription = $formdata->alwaysshowdescription;
        $update->submissiondrafts = $formdata->submissiondrafts;
        $update->requiresubmissionstatement = $formdata->requiresubmissionstatement;
        $update->sendnotifications = $formdata->sendnotifications;
        $update->sendlatenotifications = $formdata->sendlatenotifications;
        $update->duedate = $formdata->duedate;
        $update->cutoffdate = $formdata->cutoffdate;
        $update->allowsubmissionsfromdate = $formdata->allowsubmissionsfromdate;
        $update->grade = $formdata->grade;
        $update->completionsubmit = !empty($formdata->completionsubmit);
        $update->teamsubmission = $formdata->teamsubmission;
        $update->requireallteammemberssubmit = $formdata->requireallteammemberssubmit;
        $update->teamsubmissiongroupingid = $formdata->teamsubmissiongroupingid;
        $update->blindmarking = $formdata->blindmarking;


        $result = $DB->update_record('assign', $update);
        $this->instance = $DB->get_record('assign', array('id'=>$update->id), '*', MUST_EXIST);

        // load the assignment so the plugins have access to it

        // call save_settings hook for submission plugins
        foreach ($this->submissionplugins as $plugin) {
            if (!$this->update_plugin_instance($plugin, $formdata)) {
                print_error($plugin->get_error());
                return false;
            }
        }
        foreach ($this->feedbackplugins as $plugin) {
            if (!$this->update_plugin_instance($plugin, $formdata)) {
                print_error($plugin->get_error());
                return false;
            }
        }


        // update the database record


        // update all the calendar events
        $this->update_calendar($this->get_course_module()->id);

        $this->update_gradebook(false, $this->get_course_module()->id);

        $update = new stdClass();
        $update->id = $this->get_instance()->id;
        $update->nosubmissions = (!$this->is_any_submission_plugin_enabled()) ? 1: 0;
        $DB->update_record('assign', $update);





        return $result;
    }

    /**
* add elements in grading plugin form
*
* @param mixed $grade stdClass|null
* @param MoodleQuickForm $mform
* @param stdClass $data
* @return void
*/
    private function add_plugin_grade_elements($grade, MoodleQuickForm $mform, stdClass $data) {
        foreach ($this->feedbackplugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $mform->addElement('header', 'header_' . $plugin->get_type(), $plugin->get_name());
                if (!$plugin->get_form_elements($grade, $mform, $data)) {
                    $mform->removeElement('header_' . $plugin->get_type());
                }
            }
        }
    }



    /**
* Add one plugins settings to edit plugin form
*
* @param assign_plugin $plugin The plugin to add the settings from
* @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
* @return void
*/
    private function add_plugin_settings(assign_plugin $plugin, MoodleQuickForm $mform) {
        global $CFG;
        if ($plugin->is_visible()) {
            // enabled
            //tied disableIf rule to this select element
            $mform->addElement('selectyesno', $plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $plugin->get_name());
            $mform->addHelpButton($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', 'enabled', $plugin->get_subtype() . '_' . $plugin->get_type());


            $default = get_config($plugin->get_subtype() . '_' . $plugin->get_type(), 'default');
            if ($plugin->get_config('enabled') !== false) {
                $default = $plugin->is_enabled();
            }
            $mform->setDefault($plugin->get_subtype() . '_' . $plugin->get_type() . '_enabled', $default);

            $plugin->get_settings($mform);

        }

    }


    /**
* Add settings to edit plugin form
*
* @param MoodleQuickForm $mform The form to add the configuration settings to. This form is modified directly (not returned)
* @return void
*/
    public function add_all_plugin_settings(MoodleQuickForm $mform) {
        $mform->addElement('header', 'general', get_string('submissionsettings', 'assign'));

        foreach ($this->submissionplugins as $plugin) {
            $this->add_plugin_settings($plugin, $mform);

        }
        $mform->addElement('header', 'general', get_string('feedbacksettings', 'assign'));
        foreach ($this->feedbackplugins as $plugin) {
            $this->add_plugin_settings($plugin, $mform);
        }
    }

    /**
* Allow each plugin an opportunity to update the defaultvalues
* passed in to the settings form (needed to set up draft areas for
* editor and filemanager elements)
* @param array $defaultvalues
*/
    public function plugin_data_preprocessing(&$defaultvalues) {
        foreach ($this->submissionplugins as $plugin) {
            if ($plugin->is_visible()) {
                $plugin->data_preprocessing($defaultvalues);
            }
        }
        foreach ($this->feedbackplugins as $plugin) {
            if ($plugin->is_visible()) {
                $plugin->data_preprocessing($defaultvalues);
            }
        }
    }

    /**
* Get the name of the current module.
*
* @return string the module name (Assignment)
*/
    protected function get_module_name() {
        if (isset(self::$modulename)) {
            return self::$modulename;
        }
        self::$modulename = get_string('modulename', 'assign');
        return self::$modulename;
    }

    /**
* Get the plural name of the current module.
*
* @return string the module name plural (Assignments)
*/
    protected function get_module_name_plural() {
        if (isset(self::$modulenameplural)) {
            return self::$modulenameplural;
        }
        self::$modulenameplural = get_string('modulenameplural', 'assign');
        return self::$modulenameplural;
    }

    /**
* Has this assignment been constructed from an instance?
*
* @return bool
*/
    public function has_instance() {
        return $this->instance || $this->get_course_module();
    }

    /**
* Get the settings for the current instance of this assignment
*
* @return stdClass The settings
*/
    public function get_instance() {
        global $DB;
        if ($this->instance) {
            return $this->instance;
        }
        if ($this->get_course_module()) {
            $this->instance = $DB->get_record('assign', array('id' => $this->get_course_module()->instance), '*', MUST_EXIST);
        }
        if (!$this->instance) {
            throw new coding_exception('Improper use of the assignment class. Cannot load the assignment record.');
        }
        return $this->instance;
    }

    /**
* Get the context of the current course
* @return mixed context|null The course context
*/
    public function get_course_context() {
        if (!$this->context && !$this->course) {
            throw new coding_exception('Improper use of the assignment class. Cannot load the course context.');
        }
        if ($this->context) {
            return $this->context->get_course_context();
        } else {
            return context_course::instance($this->course->id);
        }
    }


    /**
* Get the current course module
*
* @return mixed stdClass|null The course module
*/
    public function get_course_module() {
        if ($this->coursemodule) {
            return $this->coursemodule;
        }
        if (!$this->context) {
            return null;
        }

        if ($this->context->contextlevel == CONTEXT_MODULE) {
            $this->coursemodule = get_coursemodule_from_id('assign', $this->context->instanceid, 0, false, MUST_EXIST);
            return $this->coursemodule;
        }
        return null;
    }

    /**
* Get context module
*
* @return context
*/
    public function get_context() {
        return $this->context;
    }

    /**
* Get the current course
* @return mixed stdClass|null The course
*/
    public function get_course() {
        global $DB;
        if ($this->course) {
            return $this->course;
        }

        if (!$this->context) {
            return null;
        }
        $this->course = $DB->get_record('course', array('id' => $this->get_course_context()->instanceid), '*', MUST_EXIST);
        return $this->course;
    }

    /**
* Return a grade in user-friendly form, whether it's a scale or not
*
* @param mixed $grade int|null
* @param boolean $editing Are we allowing changes to this grade?
* @param int $userid The user id the grade belongs to
* @param int $modified Timestamp from when the grade was last modified
* @return string User-friendly representation of grade
*/
    public function display_grade($grade, $editing, $userid=0, $modified=0) {
        global $DB;

        static $scalegrades = array();

        if ($this->get_instance()->grade >= 0) {
            // Normal number
            if ($editing && $this->get_instance()->grade > 0) {
                if ($grade < 0) {
                    $displaygrade = '';
                } else {
                    $displaygrade = format_float($grade);
                }
                $o = '<input type="text" name="quickgrade_' . $userid . '" value="' . $displaygrade . '" size="6" maxlength="10" class="quickgrade"/>';
                $o .= '&nbsp;/&nbsp;' . format_float($this->get_instance()->grade,2);
                $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
                return $o;
            } else {
                if ($grade == -1 || $grade === null) {
                    return '-';
                } else {
                    return format_float(($grade),2) .'&nbsp;/&nbsp;'. format_float($this->get_instance()->grade,2);
                }
            }

        } else {
            // Scale
            if (empty($this->cache['scale'])) {
                if ($scale = $DB->get_record('scale', array('id'=>-($this->get_instance()->grade)))) {
                    $this->cache['scale'] = make_menu_from_list($scale->scale);
                } else {
                    return '-';
                }
            }
            if ($editing) {
                $o = '<select name="quickgrade_' . $userid . '" class="quickgrade">';
                $o .= '<option value="-1">' . get_string('nograde') . '</option>';
                foreach ($this->cache['scale'] as $optionid => $option) {
                    $selected = '';
                    if ($grade == $optionid) {
                        $selected = 'selected="selected"';
                    }
                    $o .= '<option value="' . $optionid . '" ' . $selected . '>' . $option . '</option>';
                }
                $o .= '</select>';
                $o .= '<input type="hidden" name="grademodified_' . $userid . '" value="' . $modified . '"/>';
                return $o;
            } else {
                $scaleid = (int)$grade;
                if (isset($this->cache['scale'][$scaleid])) {
                    return $this->cache['scale'][$scaleid];
                }
                return '-';
            }
        }
    }

    /**
* Load a list of users enrolled in the current course with the specified permission and group (0 for no group)
*
* @param int $currentgroup
* @param bool $idsonly
* @return array List of user records
*/
    public function list_participants($currentgroup, $idsonly) {
        if ($idsonly) {
            return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup, 'u.id');
        } else {
            return get_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
        }
    }

    /**
* Load a count of valid teams for this assignment
*
* @return int number of valid teams
*/
    public function count_teams() {

        $groups = groups_get_all_groups($this->get_course()->id, 0, $this->get_instance()->teamsubmissiongroupingid, 'g.id');
        $count = count($groups);

        // See if there are any users in the default group.
        $defaultusers = $this->get_submission_group_members(0, true);
        if (count($defaultusers) > 0) {
            $count += 1;
        }
        return $count;
    }

    /**
* Load a count of users enrolled in the current course with the specified permission and group (0 for no group)
*
* @param int $currentgroup
* @return int number of matching users
*/
    public function count_participants($currentgroup) {
        return count_enrolled_users($this->context, "mod/assign:submit", $currentgroup);
    }

    /**
* Load a count of users submissions in the current module that require grading
* This means the submission modification time is more recent than the
* grading modification time.
*
* @return int number of matching submissions
*/
    public function count_submissions_need_grading() {
        global $DB;

        $params = array($this->get_course_module()->instance);

        return $DB->count_records_sql("SELECT COUNT('x')
FROM {assign_submission} s
LEFT JOIN {assign_grades} g ON s.assignment = g.assignment AND s.userid = g.userid
WHERE s.assignment = ?
AND s.timemodified IS NOT NULL
AND (s.timemodified > g.timemodified OR g.timemodified IS NULL)",
                                       $params);
    }

    /**
* Load a count of grades
*
* @return int number of grades
*/
    public function count_grades() {
        global $DB;

        if (!$this->has_instance()) {
            return 0;
        }

        $sql = 'SELECT COUNT(id) FROM {assign_grades} WHERE assignment = ?';
        $params = array($this->get_course_module()->instance);

        return $DB->count_records_sql($sql, $params);
    }

    /**
* Load a count of submissions
*
* @return int number of submissions
*/
    public function count_submissions() {
        global $DB;

        if (!$this->has_instance()) {
            return 0;
        }

        $sql = 'SELECT COUNT(id) FROM {assign_submission} WHERE assignment = ?';
        $params = array($this->get_course_module()->instance);

        if ($this->get_instance()->teamsubmission) {
            // only look at team submissions
            $sql .= ' AND userid = ?';
            $params[] = 0;
        }
        return $DB->count_records_sql($sql, $params);
    }

    /**
* Load a count of submissions with a specified status
*
* @param string $status The submission status - should match one of the constants
* @return int number of matching submissions
*/
    public function count_submissions_with_status($status) {
        global $DB;
        $sql = 'SELECT COUNT(id) FROM {assign_submission} WHERE assignment = ? AND status = ?';
        $params = array($this->get_course_module()->instance, $status);

        if ($this->get_instance()->teamsubmission) {
            // only look at team submissions
            $sql .= ' AND userid = ?';
            $params[] = 0;
        }
        return $DB->count_records_sql($sql, $params);
    }

    /**
* Utility function to get the userid for every row in the grading table
* so the order can be frozen while we iterate it
*
* @return array An array of userids
*/
    private function get_grading_userid_list() {
        $filter = get_user_preferences('assign_filter', '');
        $table = new assign_grading_table($this, 0, $filter, 0, false);

        $useridlist = $table->get_column_data('userid');

        return $useridlist;
    }


    /**
* Utility function get the userid based on the row number of the grading table.
* This takes into account any active filters on the table.
*
* @param int $num The row number of the user
* @param bool $last This is set to true if this is the last user in the table
* @return mixed The user id of the matching user or false if there was an error
*/
    private function get_userid_for_row($num, $last) {
        if (!array_key_exists('userid_for_row', $this->cache)) {
            $this->cache['userid_for_row'] = array();
        }
        if (array_key_exists($num, $this->cache['userid_for_row'])) {
            list($userid, $last) = $this->cache['userid_for_row'][$num];
            return $userid;
        }

        $filter = get_user_preferences('assign_filter', '');
        $table = new assign_grading_table($this, 0, $filter, 0, false);

        $userid = $table->get_cell_data($num, 'userid', $last);

        $this->cache['userid_for_row'][$num] = array($userid, $last);
        return $userid;
    }

    /**
* Generate zip file from array of given files
*
* @param array $filesforzipping - array of files to pass into archive_to_pathname - this array is indexed by the final file name and each element in the array is an instance of a stored_file object
* @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
*/
     private function pack_files($filesforzipping) {
         global $CFG;
         //create path for new zip file.
         $tempzip = tempnam($CFG->tempdir.'/', 'assignment_');
         //zip files
         $zipper = new zip_packer();
         if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
             return $tempzip;
         }
         return false;
    }

    /**
* Finds all assignment notifications that have yet to be mailed out, and mails them.
*
* Cron function to be run periodically according to the moodle cron
*
* @return bool
*/
    static function cron() {
        global $DB;

        // only ever send a max of one days worth of updates
        $yesterday = time() - (24 * 3600);
        $timenow = time();

        // Collect all submissions from the past 24 hours that require mailing.
        $sql = "SELECT s.*, a.course, a.name, a.blindmarking, a.revealidentities,
g.*, g.id as gradeid, g.timemodified as lastmodified
FROM {assign} a
JOIN {assign_grades} g ON g.assignment = a.id
LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = g.userid
WHERE g.timemodified >= :yesterday AND
g.timemodified <= :today AND
g.mailed = 0";
        $params = array('yesterday' => $yesterday, 'today' => $timenow);
        $submissions = $DB->get_records_sql($sql, $params);

        if (empty($submissions)) {
            mtrace('done.');
            return true;
        }

        mtrace('Processing ' . count($submissions) . ' assignment submissions ...');

        // Preload courses we are going to need those.
        $courseids = array();
        foreach ($submissions as $submission) {
            $courseids[] = $submission->course;
        }
        // Filter out duplicates
        $courseids = array_unique($courseids);
        $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
        list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
        $sql = "SELECT c.*, {$ctxselect}
FROM {course} c
LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
WHERE c.id {$courseidsql}";
        $params['contextlevel'] = CONTEXT_COURSE;
        $courses = $DB->get_records_sql($sql, $params);
        // Clean up... this could go on for a while.
        unset($courseids);
        unset($ctxselect);
        unset($courseidsql);
        unset($params);

        // Simple array we'll use for caching modules.
        $modcache = array();

        // Message students about new feedback
        foreach ($submissions as $submission) {

            mtrace("Processing assignment submission $submission->id ...");

            // do not cache user lookups - could be too many
            if (!$user = $DB->get_record("user", array("id"=>$submission->userid))) {
                mtrace("Could not find user $submission->userid");
                continue;
            }

            // use a cache to prevent the same DB queries happening over and over
            if (!array_key_exists($submission->course, $courses)) {
                mtrace("Could not find course $submission->course");
                continue;
            }
            $course = $courses[$submission->course];
            if (isset($course->ctxid)) {
                // Context has not yet been preloaded. Do so now.
                context_helper::preload_from_record($course);
            }

            // Override the language and timezone of the "current" user, so that
            // mail is customised for the receiver.
            cron_setup_user($user, $course);

            // context lookups are already cached
            $coursecontext = context_course::instance($course->id);
            if (!is_enrolled($coursecontext, $user->id)) {
                $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
                mtrace(fullname($user)." not an active participant in " . $courseshortname);
                continue;
            }

            if (!$grader = $DB->get_record("user", array("id"=>$submission->grader))) {
                mtrace("Could not find grader $submission->grader");
                continue;
            }

            if (!array_key_exists($submission->assignment, $modcache)) {
                if (! $mod = get_coursemodule_from_instance("assign", $submission->assignment, $course->id)) {
                    mtrace("Could not find course module for assignment id $submission->assignment");
                    continue;
                }
                $modcache[$submission->assignment] = $mod;
            } else {
                $mod = $modcache[$submission->assignment];
            }
            // context lookups are already cached
            $contextmodule = context_module::instance($mod->id);

            if (!$mod->visible) {
                // Hold mail notification for hidden assignments until later
                continue;
            }

            // need to send this to the student
            $messagetype = 'feedbackavailable';
            $eventtype = 'assign_notification';
            $updatetime = $submission->lastmodified;
            $modulename = get_string('modulename', 'assign');

            $uniqueid = 0;
            if ($submission->blindmarking && !$submission->revealidentities) {
                $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
            }
            self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime,
                                               $mod, $contextmodule, $course, $modulename, $submission->name,
                                               $submission->blindmarking && !$submission->revealidentities,
                                               $uniqueid);

            $grade = new stdClass();
            $grade->id = $submission->gradeid;
            $grade->mailed = 1;
            $DB->update_record('assign_grades', $grade);

            mtrace('Done');
        }
        mtrace('Done processing ' . count($submissions) . ' assignment submissions');

        cron_setup_user();

        // Free up memory just to be sure
        unset($courses);
        unset($modcache);

        return true;
    }

    /**
* Update a grade in the grade table for the assignment and in the gradebook
*
* @param stdClass $grade a grade record keyed on id
* @return bool true for success
*/
    public function update_grade($grade) {
        global $DB;

        $grade->timemodified = time();

        if ($grade->grade && $grade->grade != -1) {
            if ($this->get_instance()->grade > 0) {
                if (!is_numeric($grade->grade)) {
                    return false;
                } else if ($grade->grade > $this->get_instance()->grade) {
                    return false;
                } else if ($grade->grade < 0) {
                    return false;
                }
            } else {
                // this is a scale
                if ($scale = $DB->get_record('scale', array('id' => -($this->get_instance()->grade)))) {
                    $scaleoptions = make_menu_from_list($scale->scale);
                    if (!array_key_exists((int) $grade->grade, $scaleoptions)) {
                        return false;
                    }
                }
            }
        }

        $result = $DB->update_record('assign_grades', $grade);
        if ($result) {
            $this->gradebook_item_update(null, $grade);
        }
        return $result;
    }

    /**
* View the grant extension date page
*
* Uses url parameters 'userid'
* or from parameter 'selectedusers'
* @param moodleform $mform - Used for validation of the submitted data
* @return string
*/
    private function view_grant_extension($mform) {
        global $DB, $CFG;
        require_once($CFG->dirroot . '/mod/assign/extensionform.php');

        $o = '';
        $batchusers = optional_param('selectedusers', '', PARAM_TEXT);
        $data = new stdClass();
        $data->extensionduedate = null;
        $userid = 0;
        if (!$batchusers) {
            $userid = required_param('userid', PARAM_INT);

            $grade = $this->get_user_grade($userid, false);

            $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);

            if ($grade) {
                $data->extensionduedate = $grade->extensionduedate;
            }
            $data->userid = $userid;
        } else {
            $data->batchusers = $batchusers;
        }
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(),
                                                      $this->show_intro(),
                                                      $this->get_course_module()->id,
                                                      get_string('grantextension', 'assign')));

        if (!$mform) {
            $mform = new mod_assign_extension_form(null, array($this->get_course_module()->id,
                                                               $userid,
                                                               $batchusers,
                                                               $this->get_instance(),
                                                               $data));
        }
        $o .= $this->get_renderer()->render(new assign_form('extensionform', $mform));
        $o .= $this->view_footer();
        return $o;
    }

    /**
* Get a list of the users in the same group as this user
*
* @param int $groupid The id of the group whose members we want or 0 for the default group
* @param bool $onlyids Whether to retrieve only the user id's
* @return array The users (possibly id's only)
*/
    public function get_submission_group_members($groupid, $onlyids) {
        $members = array();
        if ($groupid != 0) {
            if ($onlyids) {
                $allusers = groups_get_members($groupid, 'u.id');
            } else {
                $allusers = groups_get_members($groupid);
            }
            foreach ($allusers as $user) {
                if ($this->get_submission_group($user->id)) {
                    $members[] = $user;
                }
            }
        } else {
            $allusers = $this->list_participants(null, $onlyids);
            foreach ($allusers as $user) {
                if ($this->get_submission_group($user->id) == null) {
                    $members[] = $user;
                }
            }
        }
        return $members;
    }

    /**
* Get a list of the users in the same group as this user that have not submitted the assignment
*
* @param int $groupid The id of the group whose members we want or 0 for the default group
* @param bool $onlyids Whether to retrieve only the user id's
* @return array The users (possibly id's only)
*/
    public function get_submission_group_members_who_have_not_submitted($groupid, $onlyids) {
        if (!$this->get_instance()->teamsubmission || !$this->get_instance()->requireallteammemberssubmit) {
            return array();
        }
        $members = $this->get_submission_group_members($groupid, $onlyids);

        foreach ($members as $id => $member) {
            $submission = $this->get_user_submission($member->id, false);
            if ($submission && $submission->status != ASSIGN_SUBMISSION_STATUS_DRAFT) {
                unset($members[$id]);
            } else {
                if ($this->is_blind_marking()) {
                    $members[$id]->alias = get_string('hiddenuser', 'assign') . $this->get_uniqueid_for_user($id);
                }
            }
        }
        return $members;
    }

    /**
* Load the group submission object for a particular user, optionally creating it if required
*
* This will create the user submission and the group submission if required
*
* @param int $userid The id of the user whose submission we want
* @param int $groupid The id of the group for this user - may be 0 in which case it is determined from the userid
* @param bool $create If set to true a new submission object will be created in the database
* @return stdClass The submission
*/
    public function get_group_submission($userid, $groupid, $create) {
        global $DB;

        if ($groupid == 0) {
            $group = $this->get_submission_group($userid);
            if ($group) {
                $groupid = $group->id;
            }
        }

        if ($create) {
            // Make sure there is a submission for this user.
            $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>0, 'userid'=>$userid);
            $submission = $DB->get_record('assign_submission', $params);

            if (!$submission) {
                $submission = new stdClass();
                $submission->assignment = $this->get_instance()->id;
                $submission->userid = $userid;
                $submission->groupid = 0;
                $submission->timecreated = time();
                $submission->timemodified = $submission->timecreated;

                if ($this->get_instance()->submissiondrafts) {
                    $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
                } else {
                    $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
                }
                $DB->insert_record('assign_submission', $submission);
            }
        }
        // Now get the group submission.
        $params = array('assignment'=>$this->get_instance()->id, 'groupid'=>$groupid, 'userid'=>0);
        $submission = $DB->get_record('assign_submission', $params);

        if ($submission) {
            return $submission;
        }
        if ($create) {
            $submission = new stdClass();
            $submission->assignment = $this->get_instance()->id;
            $submission->userid = 0;
            $submission->groupid = $groupid;
            $submission->timecreated = time();
            $submission->timemodified = $submission->timecreated;

            if ($this->get_instance()->submissiondrafts) {
                $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
            } else {
                $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
            }
            $sid = $DB->insert_record('assign_submission', $submission);
            $submission->id = $sid;
            return $submission;
        }
        return false;
    }

    /**
* View a page rendered by a plugin
*
* Uses url parameters 'pluginaction', 'pluginsubtype', 'plugin', and 'id'
*
* @return string
*/
    private function view_plugin_page() {
        global $USER;

        $o = '';

        $pluginsubtype = required_param('pluginsubtype', PARAM_ALPHA);
        $plugintype = required_param('plugin', PARAM_TEXT);
        $pluginaction = required_param('pluginaction', PARAM_ALPHA);

        $plugin = $this->get_plugin_by_type($pluginsubtype, $plugintype);
        if (!$plugin) {
            print_error('invalidformdata', '');
            return;
        }

        $o .= $plugin->view_page($pluginaction);

        return $o;
    }


    /**
* This is used for team assignments to get the group for the specified user.
* If the user is a member of multiple or no groups this will return false
*
* @param int $userid The id of the user whose submission we want
* @return mixed The group or false
*/
    public function get_submission_group($userid) {
        $groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_instance()->teamsubmissiongroupingid);
        if (count($groups) != 1) {
            return false;
        }
        return array_pop($groups);
    }


    /**
* display the submission that is used by a plugin
* Uses url parameters 'sid', 'gid' and 'plugin'
* @param string $pluginsubtype
* @return string
*/
    private function view_plugin_content($pluginsubtype) {
        global $USER;

        $o = '';

        $submissionid = optional_param('sid', 0, PARAM_INT);
        $gradeid = optional_param('gid', 0, PARAM_INT);
        $plugintype = required_param('plugin', PARAM_TEXT);
        $item = null;
        if ($pluginsubtype == 'assignsubmission') {
            $plugin = $this->get_submission_plugin_by_type($plugintype);
            if ($submissionid <= 0) {
                throw new coding_exception('Submission id should not be 0');
            }
            $item = $this->get_submission($submissionid);

            // permissions
            if ($item->userid != $USER->id) {
                require_capability('mod/assign:grade', $this->context);
            }
            $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                              $this->get_context(),
                                                              $this->show_intro(),
                                                              $this->get_course_module()->id,
                                                              $plugin->get_name()));
            $o .= $this->get_renderer()->render(new assign_submission_plugin_submission($plugin,
                                                              $item,
                                                              assign_submission_plugin_submission::FULL,
                                                              $this->get_course_module()->id,
                                                              $this->get_return_action(),
                                                              $this->get_return_params()));

            $this->add_to_log('view submission', get_string('viewsubmissionforuser', 'assign', $item->userid));
        } else {
            $plugin = $this->get_feedback_plugin_by_type($plugintype);
            if ($gradeid <= 0) {
                throw new coding_exception('Grade id should not be 0');
            }
            $item = $this->get_grade($gradeid);
            // permissions
            if ($item->userid != $USER->id) {
                require_capability('mod/assign:grade', $this->context);
            }
            $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                              $this->get_context(),
                                                              $this->show_intro(),
                                                              $this->get_course_module()->id,
                                                              $plugin->get_name()));
            $o .= $this->get_renderer()->render(new assign_feedback_plugin_feedback($plugin,
                                                              $item,
                                                              assign_feedback_plugin_feedback::FULL,
                                                              $this->get_course_module()->id,
                                                              $this->get_return_action(),
                                                              $this->get_return_params()));
            $this->add_to_log('view feedback', get_string('viewfeedbackforuser', 'assign', $item->userid));
        }


        $o .= $this->view_return_links();

        $o .= $this->view_footer();
        return $o;
    }

    /**
* render the content in editor that is often used by plugin
*
* @param string $filearea
* @param int $submissionid
* @param string $plugintype
* @param string $editor
* @param string $component
* @return string
*/
    public function render_editor_content($filearea, $submissionid, $plugintype, $editor, $component) {
        global $CFG;

        $result = '';

        $plugin = $this->get_submission_plugin_by_type($plugintype);

        $text = $plugin->get_editor_text($editor, $submissionid);
        $format = $plugin->get_editor_format($editor, $submissionid);

        $finaltext = file_rewrite_pluginfile_urls($text, 'pluginfile.php', $this->get_context()->id, $component, $filearea, $submissionid);
        $result .= format_text($finaltext, $format, array('overflowdiv' => true, 'context' => $this->get_context()));



        if ($CFG->enableportfolios) {
            require_once($CFG->libdir . '/portfoliolib.php');

            $button = new portfolio_add_button();
            $button->set_callback_options('assign_portfolio_caller', array('cmid' => $this->get_course_module()->id, 'sid' => $submissionid, 'plugin' => $plugintype, 'editor' => $editor, 'area'=>$filearea), '/mod/assign/portfolio_callback.php');
            $fs = get_file_storage();

            if ($files = $fs->get_area_files($this->context->id, $component,$filearea, $submissionid, "timemodified", false)) {
                $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
            } else {
                $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
            }
            $result .= $button->to_html();
        }
        return $result;
    }

    /**
* Display a grading error
*
* @param string $message - The description of the result
* @return string
*/
    private function view_quickgrading_result($message) {
        $o = '';
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(),
                                                      $this->show_intro(),
                                                      $this->get_course_module()->id,
                                                      get_string('quickgradingresult', 'assign')));
        $o .= $this->get_renderer()->render(new assign_quickgrading_result($message, $this->get_course_module()->id));
        $o .= $this->view_footer();
        return $o;
    }

    /**
* Display the page footer
*
* @return string
*/
    private function view_footer() {
        return $this->get_renderer()->render_footer();
    }

    /**
* Does this user have grade permission for this assignment
*
* @return bool
*/
    private function can_grade() {
        // Permissions check
        if (!has_capability('mod/assign:grade', $this->context)) {
            return false;
        }

        return true;
    }

    /**
* Download a zip file of all assignment submissions
*
* @return void
*/
    private function download_submissions() {
        global $CFG,$DB;

        // More efficient to load this here.
        require_once($CFG->libdir.'/filelib.php');

        // Load all users with submit.
        $students = get_enrolled_users($this->context, "mod/assign:submit");

        // Build a list of files to zip.
        $filesforzipping = array();
        $fs = get_file_storage();

        $groupmode = groups_get_activity_groupmode($this->get_course_module());
        // All users.
        $groupid = 0;
        $groupname = '';
        if ($groupmode) {
            $groupid = groups_get_activity_group($this->get_course_module(), true);
            $groupname = groups_get_group_name($groupid).'-';
        }

        // Construct the zip file name.
        $filename = clean_filename($this->get_course()->shortname.'-'.
                                   $this->get_instance()->name.'-'.
                                   $groupname.$this->get_course_module()->id.".zip");

        // Get all the files for each student.
        foreach ($students as $student) {
            $userid = $student->id;

            if ((groups_is_member($groupid, $userid) or !$groupmode or !$groupid)) {
                // Get the plugins to add their own files to the zip.

                $submissiongroup = false;
                $groupname = '';
                if ($this->get_instance()->teamsubmission) {
                    $submission = $this->get_group_submission($userid, 0, false);
                    $submissiongroup = $this->get_submission_group($userid);
                    if ($submissiongroup) {
                        $groupname = $submissiongroup->name . '-';
                    } else {
                        $groupname = get_string('defaultteam', 'assign') . '-';
                    }
                } else {
                    $submission = $this->get_user_submission($userid, false);
                }

                if ($this->is_blind_marking()) {
                    $prefix = clean_filename(str_replace('_', ' ', $groupname . get_string('participant', 'assign')) .
                                             "_" . $this->get_uniqueid_for_user($userid) . "_");
                } else {
                    $prefix = clean_filename(str_replace('_', ' ', $groupname . fullname($student)) .
                                             "_" . $this->get_uniqueid_for_user($userid) . "_");
                }

                if ($submission) {
                    foreach ($this->submissionplugins as $plugin) {
                        if ($plugin->is_enabled() && $plugin->is_visible()) {
                            $pluginfiles = $plugin->get_files($submission);
                            foreach ($pluginfiles as $zipfilename => $file) {
                                $subtype = $plugin->get_subtype();
                                $type = $plugin->get_type();
                                $prefixedfilename = $prefix . $subtype . '_' . $type . '_' . $zipfilename;
                                $filesforzipping[$prefixedfilename] = $file;
                            }
                        }
                    }
                }
            }
        }
        if ($zipfile = $this->pack_files($filesforzipping)) {
            $this->add_to_log('download all submissions', get_string('downloadall', 'assign'));
            // Send file and delete after sending.
            send_temp_file($zipfile, $filename);
        }
    }

    /**
* Util function to add a message to the log
*
* @param string $action The current action
* @param string $info A detailed description of the change. But no more than 255 characters.
* @param string $url The url to the assign module instance.
* @return void
*/
    public function add_to_log($action = '', $info = '', $url='') {
        global $USER;

        $fullurl = 'view.php?id=' . $this->get_course_module()->id;
        if ($url != '') {
            $fullurl .= '&' . $url;
        }

        add_to_log($this->get_course()->id, 'assign', $action, $fullurl, $info, $this->get_course_module()->id, $USER->id);
    }

    /**
* Lazy load the page renderer and expose the renderer to plugins
*
* @return assign_renderer
*/
    public function get_renderer() {
        global $PAGE;
        if ($this->output) {
            return $this->output;
        }
        $this->output = $PAGE->get_renderer('mod_assign');
        return $this->output;
    }

    /**
* Load the submission object for a particular user, optionally creating it if required
*
* For team assignments there are 2 submissions - the student submission and the team submission
* All files are associated with the team submission but the status of the students contribution is
* recorded separately.
*
* @param int $userid The id of the user whose submission we want or 0 in which case USER->id is used
* @param bool $create optional Defaults to false. If set to true a new submission object will be created in the database
* @return stdClass The submission
*/
    public function get_user_submission($userid, $create) {
        global $DB, $USER;

        if (!$userid) {
            $userid = $USER->id;
        }
        // If the userid is not null then use userid.
        $params = array('assignment'=>$this->get_instance()->id, 'userid'=>$userid, 'groupid'=>0);
        $submission = $DB->get_record('assign_submission', $params);

        if ($submission) {
            return $submission;
        }
        if ($create) {
            $submission = new stdClass();
            $submission->assignment = $this->get_instance()->id;
            $submission->userid = $userid;
            $submission->timecreated = time();
            $submission->timemodified = $submission->timecreated;

            if ($this->get_instance()->submissiondrafts) {
                $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
            } else {
                $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
            }
            $sid = $DB->insert_record('assign_submission', $submission);
            $submission->id = $sid;
            return $submission;
        }
        return false;
    }

    /**
* Load the submission object from it's id
*
* @param int $submissionid The id of the submission we want
* @return stdClass The submission
*/
    private function get_submission($submissionid) {
        global $DB;

        return $DB->get_record('assign_submission', array('assignment'=>$this->get_instance()->id, 'id'=>$submissionid), '*', MUST_EXIST);
    }

    /**
* This will retrieve a grade object from the db, optionally creating it if required
*
* @param int $userid The user we are grading
* @param bool $create If true the grade will be created if it does not exist
* @return stdClass The grade record
*/
    public function get_user_grade($userid, $create) {
        global $DB, $USER;

        if (!$userid) {
            $userid = $USER->id;
        }

        // if the userid is not null then use userid
        $grade = $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'userid'=>$userid));

        if ($grade) {
            return $grade;
        }
        if ($create) {
            $grade = new stdClass();
            $grade->assignment = $this->get_instance()->id;
            $grade->userid = $userid;
            $grade->timecreated = time();
            $grade->timemodified = $grade->timecreated;
            $grade->locked = 0;
            $grade->grade = -1;
            $grade->grader = $USER->id;
            $grade->extensionduedate = 0;
            $gid = $DB->insert_record('assign_grades', $grade);
            $grade->id = $gid;
            return $grade;
        }
        return false;
    }

    /**
* This will retrieve a grade object from the db
*
* @param int $gradeid The id of the grade
* @return stdClass The grade record
*/
    private function get_grade($gradeid) {
        global $DB;

        return $DB->get_record('assign_grades', array('assignment'=>$this->get_instance()->id, 'id'=>$gradeid), '*', MUST_EXIST);
    }

    /**
* Print the grading page for a single user submission
*
* @param moodleform $mform
* @param int $offset
* @return string
*/
    private function view_single_grade_page($mform, $offset=0) {
        global $DB, $CFG;

        $o = '';

        // Include grade form
        require_once($CFG->dirroot . '/mod/assign/gradeform.php');

        // Need submit permission to submit an assignment
        require_capability('mod/assign:grade', $this->context);

        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(), false, $this->get_course_module()->id,get_string('grading', 'assign')));

        $rownum = required_param('rownum', PARAM_INT) + $offset;
        $useridlist = optional_param('useridlist', '', PARAM_TEXT);
        if ($useridlist) {
            $useridlist = explode(',', $useridlist);
        } else {
            $useridlist = $this->get_grading_userid_list();
        }
        $last = false;
        $userid = $useridlist[$rownum];
        if ($rownum == count($useridlist) - 1) {
            $last = true;
        }
        if (!$userid) {
            throw new coding_exception('Row is out of bounds for the current grading table: ' . $rownum);
        }
        $user = $DB->get_record('user', array('id' => $userid));
        if ($user) {
            $o .= $this->get_renderer()->render(new assign_user_summary($user,
                                                                $this->get_course()->id,
                                                                has_capability('moodle/site:viewfullnames',
                                                                $this->get_course_context()),
                                                                $this->is_blind_marking(),
                                                                $this->get_uniqueid_for_user($user->id)));
        }
        $submission = $this->get_user_submission($userid, false);
        $submissiongroup = null;
        $submissiongroupmemberswhohavenotsubmitted = array();
        $teamsubmission = null;
        $notsubmitted = array();
        if ($this->get_instance()->teamsubmission) {
            $teamsubmission = $this->get_group_submission($userid, 0, false);
            $submissiongroup = $this->get_submission_group($userid);
            $groupid = 0;
            if ($submissiongroup) {
                $groupid = $submissiongroup->id;
            }
            $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);

        }

        // get the current grade
        $grade = $this->get_user_grade($userid, false);
        if ($this->can_view_submission($userid)) {
            $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($userid);
            $extensionduedate = null;
            if ($grade) {
                $extensionduedate = $grade->extensionduedate;
            }
            $showedit = $this->submissions_open($userid) && ($this->is_any_submission_plugin_enabled());

            if ($teamsubmission) {
                $showsubmit = $showedit && $teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
            } else {
                $showsubmit = $showedit && $submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT);
            }
            $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());

            $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
                                                              $this->get_instance()->alwaysshowdescription,
                                                              $submission,
                                                              $this->get_instance()->teamsubmission,
                                                              $teamsubmission,
                                                              $submissiongroup,
                                                              $notsubmitted,
                                                              $this->is_any_submission_plugin_enabled(),
                                                              $gradelocked,
                                                              $this->is_graded($userid),
                                                              $this->get_instance()->duedate,
                                                              $this->get_instance()->cutoffdate,
                                                              $this->get_submission_plugins(),
                                                              $this->get_return_action(),
                                                              $this->get_return_params(),
                                                              $this->get_course_module()->id,
                                                              $this->get_course()->id,
                                                              assign_submission_status::GRADER_VIEW,
                                                              $showedit,
                                                              $showsubmit,
                                                              $viewfullnames,
                                                              $extensionduedate,
                                                              $this->get_context(),
                                                              $this->is_blind_marking(),
                                                              ''));
        }
        if ($grade) {
            $data = new stdClass();
            if ($grade->grade !== NULL && $grade->grade >= 0) {
                $data->grade = format_float($grade->grade,2);
            }
        } else {
            $data = new stdClass();
            $data->grade = '';
        }

        // now show the grading form
        if (!$mform) {
            $pagination = array( 'rownum'=>$rownum, 'useridlist'=>$useridlist, 'last'=>$last);
            $formparams = array($this, $data, $pagination);
            $mform = new mod_assign_grade_form(null,
                                               $formparams,
                                               'post',
                                               '',
                                               array('class'=>'gradeform'));
        }
        $o .= $this->get_renderer()->render(new assign_form('gradingform',$mform));

        $msg = get_string('viewgradingformforstudent', 'assign', array('id'=>$user->id, 'fullname'=>fullname($user)));
        $this->add_to_log('view grading form', $msg);

        $o .= $this->view_footer();
        return $o;
    }

    /**
* Show a confirmation page to make sure they want to release student identities
*
* @return string
*/
    private function view_reveal_identities_confirm() {
        global $CFG, $USER;

        require_capability('mod/assign:revealidentities', $this->get_context());

        $o = '';
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(), false, $this->get_course_module()->id));

        $confirmurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
                                                                    'action'=>'revealidentitiesconfirm',
                                                                    'sesskey'=>sesskey()));

        $cancelurl = new moodle_url('/mod/assign/view.php', array('id'=>$this->get_course_module()->id,
                                                                    'action'=>'grading'));

        $o .= $this->get_renderer()->confirm(get_string('revealidentitiesconfirm', 'assign'), $confirmurl, $cancelurl);
        $o .= $this->view_footer();
        $this->add_to_log('view', get_string('viewrevealidentitiesconfirm', 'assign'));
        return $o;
    }




    /**
* View a link to go back to the previous page. Uses url parameters returnaction and returnparams.
*
* @return string
*/
    private function view_return_links() {

        $returnaction = optional_param('returnaction','', PARAM_ALPHA);
        $returnparams = optional_param('returnparams','', PARAM_TEXT);

        $params = array();
        parse_str($returnparams, $params);
        $params = array_merge( array('id' => $this->get_course_module()->id, 'action' => $returnaction), $params);

        return $this->get_renderer()->single_button(new moodle_url('/mod/assign/view.php', $params), get_string('back'), 'get');

    }

    /**
* View the grading table of all submissions for this assignment
*
* @return string
*/
    private function view_grading_table() {
        global $USER, $CFG;
        // Include grading options form
        require_once($CFG->dirroot . '/mod/assign/gradingoptionsform.php');
        require_once($CFG->dirroot . '/mod/assign/quickgradingform.php');
        require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
        $o = '';

        $links = array();
        if (has_capability('gradereport/grader:view', $this->get_course_context()) &&
                has_capability('moodle/grade:viewall', $this->get_course_context())) {
            $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
            $links[$gradebookurl] = get_string('viewgradebook', 'assign');
        }
        if ($this->is_any_submission_plugin_enabled()) {
            $downloadurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=downloadall';
            $links[$downloadurl] = get_string('downloadall', 'assign');
        }
        if ($this->is_blind_marking() && has_capability('mod/assign:revealidentities', $this->get_context())) {
            $revealidentitiesurl = '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=revealidentities';
            $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
        }
        foreach ($this->get_feedback_plugins() as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                foreach ($plugin->get_grading_actions() as $action => $description) {
                    $url = '/mod/assign/view.php' .
                           '?id=' . $this->get_course_module()->id .
                           '&plugin=' . $plugin->get_type() .
                           '&pluginsubtype=assignfeedback' .
                           '&action=viewpluginpage&pluginaction=' . $action;
                    $links[$url] = $description;
                }
            }
        }

        $gradingactions = new url_select($links);

        $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');

        $perpage = get_user_preferences('assign_perpage', 10);
        $filter = get_user_preferences('assign_filter', '');
        $controller = $gradingmanager->get_active_controller();
        $showquickgrading = empty($controller);
        if (optional_param('action', '', PARAM_ALPHA) == 'saveoptions') {
            $quickgrading = optional_param('quickgrading', false, PARAM_BOOL);
            set_user_preference('assign_quickgrading', $quickgrading);
        }
        $quickgrading = get_user_preferences('assign_quickgrading', false);

        // print options for changing the filter and changing the number of results per page
        $gradingoptionsform = new mod_assign_grading_options_form(null,
                                                                  array('cm'=>$this->get_course_module()->id,
                                                                        'contextid'=>$this->context->id,
                                                                        'userid'=>$USER->id,
                                                                        'submissionsenabled'=>$this->is_any_submission_plugin_enabled(),
                                                                        'showquickgrading'=>$showquickgrading,
                                                                        'quickgrading'=>$quickgrading),
                                                                  'post', '',
                                                                  array('class'=>'gradingoptionsform'));

        $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null,
                                                                  array('cm'=>$this->get_course_module()->id,
                                                                        'submissiondrafts'=>$this->get_instance()->submissiondrafts,
                                                                        'duedate'=>$this->get_instance()->duedate,
                                                                        'feedbackplugins'=>$this->get_feedback_plugins()),
                                                                  'post', '',
                                                                  array('class'=>'gradingbatchoperationsform'));

        $gradingoptionsdata = new stdClass();
        $gradingoptionsdata->perpage = $perpage;
        $gradingoptionsdata->filter = $filter;
        $gradingoptionsform->set_data($gradingoptionsdata);

        $actionformtext = $this->get_renderer()->render($gradingactions);
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext));
        $o .= groups_print_activity_menu($this->get_course_module(), $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id.'&action=grading', true);

        // plagiarism update status apearring in the grading book
        if (!empty($CFG->enableplagiarism)) {
            /** Include plagiarismlib.php */
            require_once($CFG->libdir . '/plagiarismlib.php');
            $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
        }

        // load and print the table of submissions
        if ($showquickgrading && $quickgrading) {
            $table = $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, true));
            $quickgradingform = new mod_assign_quick_grading_form(null,
                                                                  array('cm'=>$this->get_course_module()->id,
                                                                        'gradingtable'=>$table));
            $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
        } else {
            $o .= $this->get_renderer()->render(new assign_grading_table($this, $perpage, $filter, 0, false));
        }

        $currentgroup = groups_get_activity_group($this->get_course_module(), true);
        $users = array_keys($this->list_participants($currentgroup, true));
        if (count($users) != 0) {
            // if no enrolled user in a course then don't display the batch operations feature
            $o .= $this->get_renderer()->render(new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform));
        }
        $o .= $this->get_renderer()->render(new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options'));
        return $o;
    }

    /**
* View entire grading page.
*
* @return string
*/
    private function view_grading_page() {
        global $CFG;

        $o = '';
        // Need submit permission to submit an assignment
        require_capability('mod/assign:grade', $this->context);
        require_once($CFG->dirroot . '/mod/assign/gradeform.php');

        // only load this if it is

        $o .= $this->view_grading_table();

        $o .= $this->view_footer();
        $this->add_to_log('view submission grading table', get_string('viewsubmissiongradingtable', 'assign'));
        return $o;
    }

    /**
* Capture the output of the plagiarism plugins disclosures and return it as a string
*
* @return void
*/
    private function plagiarism_print_disclosure() {
        global $CFG;
        $o = '';

        if (!empty($CFG->enableplagiarism)) {
            /** Include plagiarismlib.php */
            require_once($CFG->libdir . '/plagiarismlib.php');

            $o .= plagiarism_print_disclosure($this->get_course_module()->id);
        }

        return $o;
    }

    /**
* message for students when assignment submissions have been closed
*
* @return string
*/
    private function view_student_error_message() {
        global $CFG;

        $o = '';
        // Need submit permission to submit an assignment
        require_capability('mod/assign:submit', $this->context);

        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(),
                                                      $this->show_intro(),
                                                      $this->get_course_module()->id,
                                                      get_string('editsubmission', 'assign')));

        $o .= $this->get_renderer()->notification(get_string('submissionsclosed', 'assign'));

        $o .= $this->view_footer();

        return $o;

    }

    /**
* View edit submissions page.
*
* @param moodleform $mform
* @return void
*/
    private function view_edit_submission_page($mform) {
        global $CFG;

        $o = '';
        // Include submission form
        require_once($CFG->dirroot . '/mod/assign/submission_form.php');
        // Need submit permission to submit an assignment
        require_capability('mod/assign:submit', $this->context);

        if (!$this->submissions_open()) {
            return $this->view_student_error_message();
        }
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(),
                                                      $this->show_intro(),
                                                      $this->get_course_module()->id,
                                                      get_string('editsubmission', 'assign')));
        $o .= $this->plagiarism_print_disclosure();
        $data = new stdClass();

        if (!$mform) {
            $mform = new mod_assign_submission_form(null, array($this, $data));
        }

        $o .= $this->get_renderer()->render(new assign_form('editsubmissionform',$mform));

        $o .= $this->view_footer();
        $this->add_to_log('view submit assignment form', get_string('viewownsubmissionform', 'assign'));

        return $o;
    }

    /**
* See if this assignment has a grade yet
*
* @param int $userid
* @return bool
*/
    private function is_graded($userid) {
        $grade = $this->get_user_grade($userid, false);
        if ($grade) {
            return ($grade->grade !== NULL && $grade->grade >= 0);
        }
        return false;
    }


    /**
* Perform an access check to see if the current $USER can view this users submission
*
* @param int $userid
* @return bool
*/
    public function can_view_submission($userid) {
        global $USER;

        if (!is_enrolled($this->get_course_context(), $userid)) {
            return false;
        }
        if ($userid == $USER->id && !has_capability('mod/assign:submit', $this->context)) {
            return false;
        }
        if ($userid != $USER->id && !has_capability('mod/assign:grade', $this->context)) {
            return false;
        }
        return true;
    }

    /**
* Allows the plugin to show a batch grading operation page.
*
* @return none
*/
    private function view_plugin_grading_batch_operation($mform) {
        require_capability('mod/assign:grade', $this->context);
        $prefix = 'plugingradingbatchoperation_';

        if ($data = $mform->get_data()) {
            $tail = substr($data->operation, strlen($prefix));
            list($plugintype, $action) = explode('_', $tail, 2);

            $plugin = $this->get_feedback_plugin_by_type($plugintype);
            if ($plugin) {
                $users = $data->selectedusers;
                $userlist = explode(',', $users);
                echo $plugin->grading_batch_operation($action, $userlist);
                return;
            }
        }
        print_error('invalidformdata', '');
    }

    /**
* Ask the user to confirm they want to perform this batch operation
* @param moodleform $mform Set to a grading batch operations form
* @return string - the page to view after processing these actions
*/
    private function process_grading_batch_operation(& $mform) {
        global $CFG;
        require_once($CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php');
        require_sesskey();

        $mform = new mod_assign_grading_batch_operations_form(null,
                                                              array('cm'=>$this->get_course_module()->id,
                                                                    'submissiondrafts'=>$this->get_instance()->submissiondrafts,
                                                                    'duedate'=>$this->get_instance()->duedate,
                                                                    'feedbackplugins'=>$this->get_feedback_plugins()),
                                                              'post',
                                                              '',
                                                              array('class'=>'gradingbatchoperationsform'));

        if ($data = $mform->get_data()) {
            // get the list of users
            $users = $data->selectedusers;
            $userlist = explode(',', $users);

            $prefix = 'plugingradingbatchoperation_';

            if ($data->operation == 'grantextension') {
                // Reset the form so the grant extension page will create the extension form.
                $mform = null;
                return 'grantextension';
            } else if (strpos($data->operation, $prefix) === 0) {
                $tail = substr($data->operation, strlen($prefix));
                list($plugintype, $action) = explode('_', $tail, 2);

                $plugin = $this->get_feedback_plugin_by_type($plugintype);
                if ($plugin) {
                    return 'plugingradingbatchoperation';
                }
            }

            foreach ($userlist as $userid) {
                if ($data->operation == 'lock') {
                    $this->process_lock($userid);
                } else if ($data->operation == 'unlock') {
                    $this->process_unlock($userid);
                } else if ($data->operation == 'reverttodraft') {
                    $this->process_revert_to_draft($userid);
                }
            }
        }

        return 'grading';
    }

    /**
* Ask the user to confirm they want to submit their work for grading
* @param $mform moodleform - null unless form validation has failed
* @return string
*/
    private function check_submit_for_grading($mform) {
        global $USER, $CFG;

        require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');

        // Check that all of the submission plugins are ready for this submission
        $notifications = array();
        $submission = $this->get_user_submission($USER->id, false);
        $plugins = $this->get_submission_plugins();
        foreach ($plugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $check = $plugin->precheck_submission($submission);
                if ($check !== true) {
                    $notifications[] = $check;
                }
            }
        }

        $data = new stdClass();
        $adminconfig = $this->get_admin_config();
        $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
                                       $this->get_instance()->requiresubmissionstatement) &&
                                       !empty($adminconfig->submissionstatement);

        $submissionstatement = '';
        if (!empty($adminconfig->submissionstatement)) {
            $submissionstatement = $adminconfig->submissionstatement;
        }

        if ($mform == null) {
            $mform = new mod_assign_confirm_submission_form(null, array($requiresubmissionstatement,
                                                                        $submissionstatement,
                                                                        $this->get_course_module()->id,
                                                                        $data));
        }
        $o = '';
        $o .= $this->get_renderer()->header();
        $o .= $this->get_renderer()->render(new assign_submit_for_grading_page($notifications, $this->get_course_module()->id, $mform));
        $o .= $this->view_footer();

        $this->add_to_log('view confirm submit assignment form', get_string('viewownsubmissionform', 'assign'));

        return $o;
    }

    /**
* Print 2 tables of information with no action links -
* the submission summary and the grading summary
*
* @param stdClass $user the user to print the report for
* @param bool $showlinks - Return plain text or links to the profile
* @return string - the html summary
*/
    public function view_student_summary($user, $showlinks) {
        global $CFG, $DB, $PAGE;

        $grade = $this->get_user_grade($user->id, false);
        $submission = $this->get_user_submission($user->id, false);
        $o = '';

        $teamsubmission = null;
        $submissiongroup = null;
        $notsubmitted = array();
        if ($this->get_instance()->teamsubmission) {
            $teamsubmission = $this->get_group_submission($user->id, 0, false);
            $submissiongroup = $this->get_submission_group($user->id);
            $groupid = 0;
            if ($submissiongroup) {
                $groupid = $submissiongroup->id;
            }
            $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
        }

        if ($this->can_view_submission($user->id)) {
            $showedit = has_capability('mod/assign:submit', $this->context) &&
                         $this->submissions_open($user->id) && ($this->is_any_submission_plugin_enabled()) && $showlinks;
            $gradelocked = ($grade && $grade->locked) || $this->grading_disabled($user->id);
            // Grading criteria preview.
            $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
            $gradingcontrollerpreview = '';
            if ($gradingmethod = $gradingmanager->get_active_method()) {
                $controller = $gradingmanager->get_controller($gradingmethod);
                if ($controller->is_form_defined()) {
                    $gradingcontrollerpreview = $controller->render_preview($PAGE);
                }
            }

            $showsubmit = ($submission || $teamsubmission) && $showlinks;
            if ($teamsubmission && ($teamsubmission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
                $showsubmit = false;
            }
            if ($submission && ($submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED)) {
                $showsubmit = false;
            }
            $extensionduedate = null;
            if ($grade) {
                $extensionduedate = $grade->extensionduedate;
            }
            $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_course_context());
            $o .= $this->get_renderer()->render(new assign_submission_status($this->get_instance()->allowsubmissionsfromdate,
                                                              $this->get_instance()->alwaysshowdescription,
                                                              $submission,
                                                              $this->get_instance()->teamsubmission,
                                                              $teamsubmission,
                                                              $submissiongroup,
                                                              $notsubmitted,
                                                              $this->is_any_submission_plugin_enabled(),
                                                              $gradelocked,
                                                              $this->is_graded($user->id),
                                                              $this->get_instance()->duedate,
                                                              $this->get_instance()->cutoffdate,
                                                              $this->get_submission_plugins(),
                                                              $this->get_return_action(),
                                                              $this->get_return_params(),
                                                              $this->get_course_module()->id,
                                                              $this->get_course()->id,
                                                              assign_submission_status::STUDENT_VIEW,
                                                              $showedit,
                                                              $showsubmit,
                                                              $viewfullnames,
                                                              $extensionduedate,
                                                              $this->get_context(),
                                                              $this->is_blind_marking(),
                                                              $gradingcontrollerpreview));

            require_once($CFG->libdir.'/gradelib.php');
            require_once($CFG->dirroot.'/grade/grading/lib.php');

            $gradinginfo = grade_get_grades($this->get_course()->id,
                                        'mod',
                                        'assign',
                                        $this->get_instance()->id,
                                        $user->id);

            $gradingitem = $gradinginfo->items[0];
            $gradebookgrade = $gradingitem->grades[$user->id];

            // check to see if all feedback plugins are empty
            $emptyplugins = true;
            if ($grade) {
                foreach ($this->get_feedback_plugins() as $plugin) {
                    if ($plugin->is_visible() && $plugin->is_enabled()) {
                        if (!$plugin->is_empty($grade)) {
                            $emptyplugins = false;
                        }
                    }
                }
            }


            if (!($gradebookgrade->hidden) && ($gradebookgrade->grade !== null || !$emptyplugins)) {

                $gradefordisplay = '';
                $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');

                if ($controller = $gradingmanager->get_active_controller()) {
                    $controller->set_grade_range(make_grades_menu($this->get_instance()->grade));
                    $gradefordisplay = $controller->render_grade($PAGE,
                                                                 $grade->id,
                                                                 $gradingitem,
                                                                 $gradebookgrade->str_long_grade,
                                                                 has_capability('mod/assign:grade', $this->get_context()));
                } else {
                    $gradefordisplay = $this->display_grade($gradebookgrade->grade, false);
                }

                $gradeddate = $gradebookgrade->dategraded;
                $grader = $DB->get_record('user', array('id'=>$gradebookgrade->usermodified));

                $feedbackstatus = new assign_feedback_status($gradefordisplay,
                                                      $gradeddate,
                                                      $grader,
                                                      $this->get_feedback_plugins(),
                                                      $grade,
                                                      $this->get_course_module()->id,
                                                      $this->get_return_action(),
                                                      $this->get_return_params());

                $o .= $this->get_renderer()->render($feedbackstatus);
            }

        }
        return $o;
    }

    /**
* View submissions page (contains details of current submission).
*
* @return string
*/
    private function view_submission_page() {
        global $CFG, $DB, $USER, $PAGE;

        $o = '';
        $o .= $this->get_renderer()->render(new assign_header($this->get_instance(),
                                                      $this->get_context(),
                                                      $this->show_intro(),
                                                      $this->get_course_module()->id));

        if ($this->can_grade()) {
            if ($this->get_instance()->teamsubmission) {
                $summary = new assign_grading_summary($this->count_teams(),
                                                      $this->get_instance()->submissiondrafts,
                                                      $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
                                                      $this->is_any_submission_plugin_enabled(),
                                                      $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
                                                      $this->get_instance()->cutoffdate,
                                                      $this->get_instance()->duedate,
                                                      $this->get_course_module()->id,
                                                      $this->count_submissions_need_grading(),
                                                      $this->get_instance()->teamsubmission);
                $o .= $this->get_renderer()->render($summary);
            } else {
                $summary = new assign_grading_summary($this->count_participants(0),
                                                      $this->get_instance()->submissiondrafts,
                                                      $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_DRAFT),
                                                      $this->is_any_submission_plugin_enabled(),
                                                      $this->count_submissions_with_status(ASSIGN_SUBMISSION_STATUS_SUBMITTED),
                                                      $this->get_instance()->cutoffdate,
                                                      $this->get_instance()->duedate,
                                                      $this->get_course_module()->id,
                                                      $this->count_submissions_need_grading(),
                                                      $this->get_instance()->teamsubmission);
                $o .= $this->get_renderer()->render($summary);
            }
        }
        $grade = $this->get_user_grade($USER->id, false);
        $submission = $this->get_user_submission($USER->id, false);

        if ($this->can_view_submission($USER->id)) {
            $o .= $this->view_student_summary($USER, true);
        }


        $o .= $this->view_footer();
        $this->add_to_log('view', get_string('viewownsubmissionstatus', 'assign'));
        return $o;
    }

    /**
* convert the final raw grade(s) in the grading table for the gradebook
*
* @param stdClass $grade
* @return array
*/
    private function convert_grade_for_gradebook(stdClass $grade) {
        $gradebookgrade = array();
        // trying to match those array keys in grade update function in gradelib.php
        // with keys in th database table assign_grades
        // starting around line 262
        if ($grade->grade >= 0) {
            $gradebookgrade['rawgrade'] = $grade->grade;
        }
        $gradebookgrade['userid'] = $grade->userid;
        $gradebookgrade['usermodified'] = $grade->grader;
        $gradebookgrade['datesubmitted'] = NULL;
        $gradebookgrade['dategraded'] = $grade->timemodified;
        if (isset($grade->feedbackformat)) {
            $gradebookgrade['feedbackformat'] = $grade->feedbackformat;
        }
        if (isset($grade->feedbacktext)) {
            $gradebookgrade['feedback'] = $grade->feedbacktext;
        }

        return $gradebookgrade;
    }

    /**
* convert submission details for the gradebook
*
* @param stdClass $submission
* @return array
*/
    private function convert_submission_for_gradebook(stdClass $submission) {
        $gradebookgrade = array();


        $gradebookgrade['userid'] = $submission->userid;
        $gradebookgrade['usermodified'] = $submission->userid;
        $gradebookgrade['datesubmitted'] = $submission->timemodified;

        return $gradebookgrade;
    }

    /**
* update grades in the gradebook
*
* @param mixed $submission stdClass|null
* @param mixed $grade stdClass|null
* @return bool
*/
    private function gradebook_item_update($submission=NULL, $grade=NULL) {

        // Do not push grade to gradebook if blind marking is active as the gradebook would reveal the students.
        if ($this->is_blind_marking()) {
            return false;
        }
        if ($submission != NULL) {
            if ($submission->userid == 0) {
                // This is a group submission update.
                $team = groups_get_members($submission->groupid, 'u.id');

                foreach ($team as $member) {
                    $submission->groupid = 0;
                    $submission->userid = $member->id;
                    $this->gradebook_item_update($submission, null);
                }
                return;
            }

            $gradebookgrade = $this->convert_submission_for_gradebook($submission);

        } else {
            $gradebookgrade = $this->convert_grade_for_gradebook($grade);
        }
        // Grading is disabled, return.
        if ($this->grading_disabled($gradebookgrade['userid'])) {
            return false;
        }
        $assign = clone $this->get_instance();
        $assign->cmidnumber = $this->get_course_module()->id;

        return assign_grade_item_update($assign, $gradebookgrade);
    }

    /**
* update team submission
*
* @param stdClass $submission
* @param int $userid
* @param bool $updatetime
* @return bool
*/
    private function update_team_submission(stdClass $submission, $userid, $updatetime) {
        global $DB;

        if ($updatetime) {
            $submission->timemodified = time();
        }

        // First update the submission for the current user.
        $mysubmission = $this->get_user_submission($userid, true);
        $mysubmission->status = $submission->status;

        $this->update_submission($mysubmission, 0, $updatetime, false);

        // Now check the team settings to see if this assignment qualifies as submitted or draft.
        $team = $this->get_submission_group_members($submission->groupid, true);

        $allsubmitted = true;
        $anysubmitted = false;
        foreach ($team as $member) {
            $membersubmission = $this->get_user_submission($member->id, false);

            if (!$membersubmission || $membersubmission->status != ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
                $allsubmitted = false;
                if ($anysubmitted) {
                    break;
                }
            } else {
                $anysubmitted = true;
            }
        }
        if ($this->get_instance()->requireallteammemberssubmit) {
            if ($allsubmitted) {
                $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
            } else {
                $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
            }
            $result= $DB->update_record('assign_submission', $submission);
        } else {
            if ($anysubmitted) {
                $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
            } else {
                $submission->status = ASSIGN_SUBMISSION_STATUS_DRAFT;
            }
            $result= $DB->update_record('assign_submission', $submission);
        }

        $this->gradebook_item_update($submission);
        return $result;
    }


    /**
* update grades in the gradebook based on submission time
*
* @param stdClass $submission
* @param int $userid
* @param bool $updatetime
* @param bool $teamsubmission
* @return bool
*/
    private function update_submission(stdClass $submission, $userid, $updatetime, $teamsubmission) {
        global $DB;

        if ($teamsubmission) {
            return $this->update_team_submission($submission, $userid, $updatetime);
        }

        if ($updatetime) {
            $submission->timemodified = time();
        }
        $result= $DB->update_record('assign_submission', $submission);
        if ($result) {
            $this->gradebook_item_update($submission);
        }
        return $result;
    }

    /**
* Is this assignment open for submissions?
*
* Check the due date,
* prevent late submissions,
* has this person already submitted,
* is the assignment locked?
*
* @param int $userid - Optional userid so we can see if a different user can submit
* @return bool
*/
    private function submissions_open($userid = 0) {
        global $USER;

        if (!$userid) {
            $userid = $USER->id;
        }

        $time = time();
        $dateopen = true;
        $finaldate = false;
        if ($this->get_instance()->cutoffdate) {
            $finaldate = $this->get_instance()->cutoffdate;
        }
        // User extensions.
        if ($finaldate) {
            $grade = $this->get_user_grade($userid, false);
            if ($grade && $grade->extensionduedate) {
                // Extension can be before cut off date.
                if ($grade->extensionduedate > $finaldate) {
                    $finaldate = $grade->extensionduedate;
                }
            }
        }

        if ($finaldate) {
            $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time && $time <= $finaldate);
        } else {
            $dateopen = ($this->get_instance()->allowsubmissionsfromdate <= $time);
        }

        if (!$dateopen) {
            return false;
        }

        // Now check if this user has already submitted etc.
        if (!is_enrolled($this->get_course_context(), $userid)) {
            return false;
        }
        $submission = false;
        if ($this->get_instance()->teamsubmission) {
            $submission = $this->get_group_submission($userid, 0, false);
        } else {
            $submission = $this->get_user_submission($userid, false);
        }
        if ($submission) {

            if ($this->get_instance()->submissiondrafts && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
                // drafts are tracked and the student has submitted the assignment
                return false;
            }
        }
        if ($grade = $this->get_user_grade($userid, false)) {
            if ($grade->locked) {
                return false;
            }
        }

        if ($this->grading_disabled($userid)) {
            return false;
        }

        return true;
    }

    /**
* render the files in file area
* @param string $component
* @param string $area
* @param int $submissionid
* @return string
*/
    public function render_area_files($component, $area, $submissionid) {
        global $USER;

        $fs = get_file_storage();
        $browser = get_file_browser();
        $files = $fs->get_area_files($this->get_context()->id, $component, $area , $submissionid , "timemodified", false);
        return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);

    }

    /**
* Returns a list of teachers that should be grading given submission
*
* @param int $userid
* @return array
*/
    private function get_graders($userid) {
        //potential graders
        $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");

        $graders = array();
        if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) { // Separate groups are being used
            if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) { // Try to find all groups
                foreach ($groups as $group) {
                    foreach ($potentialgraders as $grader) {
                        if ($grader->id == $userid) {
                            continue; // do not send self
                        }
                        if (groups_is_member($group->id, $grader->id)) {
                            $graders[$grader->id] = $grader;
                        }
                    }
                }
            } else {
                // user not in group, try to find graders without group
                foreach ($potentialgraders as $grader) {
                    if ($grader->id == $userid) {
                        continue; // do not send self
                    }
                    if (!groups_has_membership($this->get_course_module(), $grader->id)) {
                        $graders[$grader->id] = $grader;
                    }
                }
            }
        } else {
            foreach ($potentialgraders as $grader) {
                if ($grader->id == $userid) {
                    continue; // do not send self
                }
                // must be enrolled
                if (is_enrolled($this->get_course_context(), $grader->id)) {
                    $graders[$grader->id] = $grader;
                }
            }
        }
        return $graders;
    }

    /**
* Format a notification for plain text
*
* @param string $messagetype
* @param stdClass $info
* @param stdClass $course
* @param stdClass $context
* @param string $modulename
* @param string $assignmentname
*/
    private static function format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname) {
        $posttext = format_string($course->shortname, true, array('context' => $context->get_course_context())).' -> '.
                     $modulename.' -> '.
                     format_string($assignmentname, true, array('context' => $context))."\n";
        $posttext .= '---------------------------------------------------------------------'."\n";
        $posttext .= get_string($messagetype . 'text', "assign", $info)."\n";
        $posttext .= "\n---------------------------------------------------------------------\n";
        return $posttext;
    }

    /**
* Format a notification for HTML
*
* @param string $messagetype
* @param stdClass $info
* @param stdClass $course
* @param stdClass $context
* @param string $modulename
* @param stdClass $coursemodule
* @param string $assignmentname
* @param stdClass $info
*/
    private static function format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) {
        global $CFG;
        $posthtml = '<p><font face="sans-serif">'.
                     '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.format_string($course->shortname, true, array('context' => $context->get_course_context())).'</a> ->'.
                     '<a href="'.$CFG->wwwroot.'/mod/assign/index.php?id='.$course->id.'">'.$modulename.'</a> ->'.
                     '<a href="'.$CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id.'">'.format_string($assignmentname, true, array('context' => $context)).'</a></font></p>';
        $posthtml .= '<hr /><font face="sans-serif">';
        $posthtml .= '<p>'.get_string($messagetype . 'html', 'assign', $info).'</p>';
        $posthtml .= '</font><hr />';
        return $posthtml;
    }

    /**
* Message someone about something (static so it can be called from cron)
*
* @param stdClass $userfrom
* @param stdClass $userto
* @param string $messagetype
* @param string $eventtype
* @param int $updatetime
* @param stdClass $coursemodule
* @param stdClass $context
* @param stdClass $course
* @param string $modulename
* @param string $assignmentname
* @return void
*/
    public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
                                                        $updatetime, $coursemodule, $context, $course,
                                                        $modulename, $assignmentname, $blindmarking,
                                                        $uniqueidforuser) {
        global $CFG;

        $info = new stdClass();
        if ($blindmarking) {
            $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
        } else {
            $info->username = fullname($userfrom, true);
        }
        $info->assignment = format_string($assignmentname,true, array('context'=>$context));
        $info->url = $CFG->wwwroot.'/mod/assign/view.php?id='.$coursemodule->id;
        $info->timeupdated = strftime('%c',$updatetime);

        $postsubject = get_string($messagetype . 'small', 'assign', $info);
        $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
        $posthtml = ($userto->mailformat == 1) ? self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname) : '';

        $eventdata = new stdClass();
        $eventdata->modulename = 'assign';
        $eventdata->userfrom = $userfrom;
        $eventdata->userto = $userto;
        $eventdata->subject = $postsubject;
        $eventdata->fullmessage = $posttext;
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml = $posthtml;
        $eventdata->smallmessage = $postsubject;

        $eventdata->name = $eventtype;
        $eventdata->component = 'mod_assign';
        $eventdata->notification = 1;
        $eventdata->contexturl = $info->url;
        $eventdata->contexturlname = $info->assignment;

        message_send($eventdata);
    }

    /**
* Message someone about something
*
* @param stdClass $userfrom
* @param stdClass $userto
* @param string $messagetype
* @param string $eventtype
* @param int $updatetime
* @return void
*/
    public function send_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime) {
        self::send_assignment_notification($userfrom, $userto, $messagetype, $eventtype,
                                           $updatetime, $this->get_course_module(), $this->get_context(),
                                           $this->get_course(), $this->get_module_name(),
                                           $this->get_instance()->name, $this->is_blind_marking(),
                                           $this->get_uniqueid_for_user($userfrom->id));
    }

    /**
* Notify student upon successful submission
*
* @param stdClass $submission
* @return void
*/
    private function notify_student_submission_receipt(stdClass $submission) {
        global $DB, $USER;

        $adminconfig = $this->get_admin_config();
        if (empty($adminconfig->submissionreceipts)) {
            // No need to do anything
            return;
        }
        if ($submission->userid) {
            $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
        } else {
            $user = $USER;
        }
        $this->send_notification($user, $user, 'submissionreceipt', 'assign_notification', $submission->timemodified);
    }

    /**
* Send notifications to graders upon student submissions
*
* @param stdClass $submission
* @return void
*/
    private function notify_graders(stdClass $submission) {
        global $DB, $USER;

        $late = $this->get_instance()->duedate && ($this->get_instance()->duedate < time());

        if (!$this->get_instance()->sendnotifications && !($late && $this->get_instance()->sendlatenotifications)) { // No need to do anything
            return;
        }

        if ($submission->userid) {
            $user = $DB->get_record('user', array('id'=>$submission->userid), '*', MUST_EXIST);
        } else {
            $user = $USER;
        }
        if ($teachers = $this->get_graders($user->id)) {
            foreach ($teachers as $teacher) {
                $this->send_notification($user, $teacher, 'gradersubmissionupdated', 'assign_notification', $submission->timemodified);
            }
        }
    }

    /**
* assignment submission is processed before grading
*
* @param $mform If validation failed when submitting this form - this is the moodleform - it can be null
* @return bool Return false if the validation fails. This affects which page is displayed next.
*/
    private function process_submit_for_grading($mform) {
        global $USER, $CFG;

        // Need submit permission to submit an assignment
        require_capability('mod/assign:submit', $this->context);
        require_once($CFG->dirroot . '/mod/assign/submissionconfirmform.php');
        require_sesskey();

        $data = new stdClass();
        $adminconfig = $this->get_admin_config();
        $requiresubmissionstatement = (!empty($adminconfig->requiresubmissionstatement) ||
                                       $this->get_i