Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 895d364bcf
Fetching contributors…

Cannot retrieve contributors at this time

file 3839 lines (3244 sloc) 162.665 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
<?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/>.

/**
* Defines various restore steps that will be used by common tasks in restore
*
* @package core_backup
* @subpackage moodle2
* @category backup
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

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

/**
* delete old directories and conditionally create backup_temp_ids table
*/
class restore_create_and_clean_temp_stuff extends restore_execution_step {

    protected function define_execution() {
        $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
        // If the table already exists, it's because restore_prechecks have been executed in the same
        // request (without problems) and it already contains a bunch of preloaded information (users...)
        // that we aren't going to execute again
        if ($exists) { // Inform plan about preloaded information
            $this->task->set_preloaded_information();
        }
        // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
        $itemid = $this->task->get_old_contextid();
        $newitemid = context_course::instance($this->get_courseid())->id;
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
        // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
        $itemid = $this->task->get_old_system_contextid();
        $newitemid = context_system::instance()->id;
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
        // Create the old-course-id to new-course-id mapping, we need that available since the beginning
        $itemid = $this->task->get_old_courseid();
        $newitemid = $this->get_courseid();
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);

    }
}

/**
* delete the temp dir used by backup/restore (conditionally),
* delete old directories and drop temp ids table
*/
class restore_drop_and_clean_temp_stuff extends restore_execution_step {

    protected function define_execution() {
        global $CFG;
        restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
        backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
        if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
            backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
        }
    }
}

/**
* Restore calculated grade items, grade categories etc
*/
class restore_gradebook_structure_step extends restore_structure_step {

    /**
* To conditionally decide if this step must be executed
* Note the "settings" conditions are evaluated in the
* corresponding task. Here we check for other conditions
* not being restore settings (files, site settings...)
*/
     protected function execute_condition() {
        global $CFG, $DB;

        // No gradebook info found, don't execute
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            return false;
        }

        // Some module present in backup file isn't available to restore
        // in this site, don't execute
        if ($this->task->is_missing_modules()) {
            return false;
        }

        // Some activity has been excluded to be restored, don't execute
        if ($this->task->is_excluding_activities()) {
            return false;
        }

        // There should only be one grade category (the 1 associated with the course itself)
        // If other categories already exist we're restoring into an existing course.
        // Restoring categories into a course with an existing category structure is unlikely to go well
        $category = new stdclass();
        $category->courseid = $this->get_courseid();
        $catcount = $DB->count_records('grade_categories', (array)$category);
        if ($catcount>1) {
            return false;
        }

        // Arrived here, execute the step
        return true;
     }

    protected function define_structure() {
        $paths = array();
        $userinfo = $this->task->get_setting_value('users');

        $paths[] = new restore_path_element('gradebook', '/gradebook');
        $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
        $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
        if ($userinfo) {
            $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
        }
        $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
        $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');

        return $paths;
    }

    protected function process_gradebook($data) {
    }

    protected function process_grade_item($data) {
        global $DB;

        $data = (object)$data;

        $oldid = $data->id;
        $data->course = $this->get_courseid();

        $data->courseid = $this->get_courseid();

        if ($data->itemtype=='manual') {
            // manual grade items store category id in categoryid
            $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
        } else if ($data->itemtype=='course') {
            // course grade item stores their category id in iteminstance
            $coursecat = grade_category::fetch_course_category($this->get_courseid());
            $data->iteminstance = $coursecat->id;
        } else if ($data->itemtype=='category') {
            // category grade items store their category id in iteminstance
            $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
        } else {
            throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
        }

        $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
        $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);

        $data->locktime = $this->apply_date_offset($data->locktime);
        $data->timecreated = $this->apply_date_offset($data->timecreated);
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        $coursecategory = $newitemid = null;
        //course grade item should already exist so updating instead of inserting
        if($data->itemtype=='course') {
            //get the ID of the already created grade item
            $gi = new stdclass();
            $gi->courseid = $this->get_courseid();
            $gi->itemtype = $data->itemtype;

            //need to get the id of the grade_category that was automatically created for the course
            $category = new stdclass();
            $category->courseid = $this->get_courseid();
            $category->parent = null;
            //course category fullname starts out as ? but may be edited
            //$category->fullname = '?';
            $coursecategory = $DB->get_record('grade_categories', (array)$category);
            $gi->iteminstance = $coursecategory->id;

            $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
            if (!empty($existinggradeitem)) {
                $data->id = $newitemid = $existinggradeitem->id;
                $DB->update_record('grade_items', $data);
            }
        }

        if (empty($newitemid)) {
            //in case we found the course category but still need to insert the course grade item
            if ($data->itemtype=='course' && !empty($coursecategory)) {
                $data->iteminstance = $coursecategory->id;
            }

            $newitemid = $DB->insert_record('grade_items', $data);
        }
        $this->set_mapping('grade_item', $oldid, $newitemid);
    }

    protected function process_grade_grade($data) {
        global $DB;

        $data = (object)$data;
        $olduserid = $data->userid;

        $data->itemid = $this->get_new_parentid('grade_item');

        $data->userid = $this->get_mappingid('user', $data->userid, null);
        if (!empty($data->userid)) {
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
            $data->locktime = $this->apply_date_offset($data->locktime);
            // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
            $data->overridden = $this->apply_date_offset($data->overridden);
            $data->timecreated = $this->apply_date_offset($data->timecreated);
            $data->timemodified = $this->apply_date_offset($data->timemodified);

            $newitemid = $DB->insert_record('grade_grades', $data);
        } else {
            debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
        }
    }

    protected function process_grade_category($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        $data->course = $this->get_courseid();
        $data->courseid = $data->course;

        $data->timecreated = $this->apply_date_offset($data->timecreated);
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        $newitemid = null;
        //no parent means a course level grade category. That may have been created when the course was created
        if(empty($data->parent)) {
            //parent was being saved as 0 when it should be null
            $data->parent = null;

            //get the already created course level grade category
            $category = new stdclass();
            $category->courseid = $this->get_courseid();
            $category->parent = null;

            $coursecategory = $DB->get_record('grade_categories', (array)$category);
            if (!empty($coursecategory)) {
                $data->id = $newitemid = $coursecategory->id;
                $DB->update_record('grade_categories', $data);
            }
        }

        //need to insert a course category
        if (empty($newitemid)) {
            $newitemid = $DB->insert_record('grade_categories', $data);
        }
        $this->set_mapping('grade_category', $oldid, $newitemid);
    }
    protected function process_grade_letter($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        $data->contextid = context_course::instance($this->get_courseid())->id;

        $newitemid = $DB->insert_record('grade_letters', $data);
        $this->set_mapping('grade_letter', $oldid, $newitemid);
    }
    protected function process_grade_setting($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        $data->courseid = $this->get_courseid();

        $newitemid = $DB->insert_record('grade_settings', $data);
        //$this->set_mapping('grade_setting', $oldid, $newitemid);
    }

    /**
* put all activity grade items in the correct grade category and mark all for recalculation
*/
    protected function after_execute() {
        global $DB;

        $conditions = array(
            'backupid' => $this->get_restoreid(),
            'itemname' => 'grade_item'//,
            //'itemid' => $itemid
        );
        $rs = $DB->get_recordset('backup_ids_temp', $conditions);

        // We need this for calculation magic later on.
        $mappings = array();

        if (!empty($rs)) {
            foreach($rs as $grade_item_backup) {

                // Store the oldid with the new id.
                $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;

                $updateobj = new stdclass();
                $updateobj->id = $grade_item_backup->newitemid;

                //if this is an activity grade item that needs to be put back in its correct category
                if (!empty($grade_item_backup->parentitemid)) {
                    $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
                    if (!is_null($oldcategoryid)) {
                        $updateobj->categoryid = $oldcategoryid;
                        $DB->update_record('grade_items', $updateobj);
                    }
                } else {
                    //mark course and category items as needing to be recalculated
                    $updateobj->needsupdate=1;
                    $DB->update_record('grade_items', $updateobj);
                }
            }
        }
        $rs->close();

        // We need to update the calculations for calculated grade items that may reference old
        // grade item ids using ##gi\d+##.
        // $mappings can be empty, use 0 if so (won't match ever)
        list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
        $sql = "SELECT gi.id, gi.calculation
FROM {grade_items} gi
WHERE gi.id {$sql} AND
calculation IS NOT NULL";
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $gradeitem) {
            // Collect all of the used grade item id references
            if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
                // This calculation doesn't reference any other grade items... EASY!
                continue;
            }
            // For this next bit we are going to do the replacement of id's in two steps:
            // 1. We will replace all old id references with a special mapping reference.
            // 2. We will replace all mapping references with id's
            // Why do we do this?
            // Because there potentially there will be an overlap of ids within the query and we
            // we substitute the wrong id.. safest way around this is the two step system
            $calculationmap = array();
            $mapcount = 0;
            foreach ($matches[1] as $match) {
                // Check that the old id is known to us, if not it was broken to begin with and will
                // continue to be broken.
                if (!array_key_exists($match, $mappings)) {
                    continue;
                }
                // Our special mapping key
                $mapping = '##MAPPING'.$mapcount.'##';
                // The old id that exists within the calculation now
                $oldid = '##gi'.$match.'##';
                // The new id that we want to replace the old one with.
                $newid = '##gi'.$mappings[$match].'##';
                // Replace in the special mapping key
                $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
                // And record the mapping
                $calculationmap[$mapping] = $newid;
                $mapcount++;
            }
            // Iterate all special mappings for this calculation and replace in the new id's
            foreach ($calculationmap as $mapping => $newid) {
                $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
            }
            // Update the calculation now that its being remapped
            $DB->update_record('grade_items', $gradeitem);
        }
        $rs->close();

        // Need to correct the grade category path and parent
        $conditions = array(
            'courseid' => $this->get_courseid()
        );

        $rs = $DB->get_recordset('grade_categories', $conditions);
        // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
        foreach ($rs as $gc) {
            if (!empty($gc->parent)) {
                $grade_category = new stdClass();
                $grade_category->id = $gc->id;
                $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
                $DB->update_record('grade_categories', $grade_category);
            }
        }
        $rs->close();

        // Now we can rebuild all the paths
        $rs = $DB->get_recordset('grade_categories', $conditions);
        foreach ($rs as $gc) {
            $grade_category = new stdClass();
            $grade_category->id = $gc->id;
            $grade_category->path = grade_category::build_path($gc);
            $grade_category->depth = substr_count($grade_category->path, '/') - 1;
            $DB->update_record('grade_categories', $grade_category);
        }
        $rs->close();

        // Restore marks items as needing update. Update everything now.
        grade_regrade_final_grades($this->get_courseid());
    }
}

/**
* decode all the interlinks present in restored content
* relying 100% in the restore_decode_processor that handles
* both the contents to modify and the rules to be applied
*/
class restore_decode_interlinks extends restore_execution_step {

    protected function define_execution() {
        // Get the decoder (from the plan)
        $decoder = $this->task->get_decoder();
        restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
        // And launch it, everything will be processed
        $decoder->execute();
    }
}

/**
* first, ensure that we have no gaps in section numbers
* and then, rebuid the course cache
*/
class restore_rebuild_course_cache extends restore_execution_step {

    protected function define_execution() {
        global $DB;

        // Although there is some sort of auto-recovery of missing sections
        // present in course/formats... here we check that all the sections
        // from 0 to MAX(section->section) exist, creating them if necessary
        $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
        // Iterate over all sections
        for ($i = 0; $i <= $maxsection; $i++) {
            // If the section $i doesn't exist, create it
            if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
                $sectionrec = array(
                    'course' => $this->get_courseid(),
                    'section' => $i);
                $DB->insert_record('course_sections', $sectionrec); // missing section created
            }
        }

        // Rebuild cache now that all sections are in place
        rebuild_course_cache($this->get_courseid());
    }
}

/**
* Review all the tasks having one after_restore method
* executing it to perform some final adjustments of information
* not available when the task was executed.
*/
class restore_execute_after_restore extends restore_execution_step {

    protected function define_execution() {

        // Simply call to the execute_after_restore() method of the task
        // that always is the restore_final_task
        $this->task->launch_execute_after_restore();
    }
}


/**
* Review all the (pending) block positions in backup_ids, matching by
* contextid, creating positions as needed. This is executed by the
* final task, once all the contexts have been created
*/
class restore_review_pending_block_positions extends restore_execution_step {

    protected function define_execution() {
        global $DB;

        // Get all the block_position objects pending to match
        $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
        $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
        // Process block positions, creating them or accumulating for final step
        foreach($rs as $posrec) {
            // Get the complete position object (stored as info)
            $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
            // If position is for one already mapped (known) contextid
            // process it now, creating the position, else nothing to
            // do, position finally discarded
            if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
                $position->contextid = $newctx->newitemid;
                // Create the block position
                $DB->insert_record('block_positions', $position);
            }
        }
        $rs->close();
    }
}

/**
* Process all the saved module availability records in backup_ids, matching
* course modules and grade item id once all them have been already restored.
* only if all matchings are satisfied the availability condition will be created.
* At the same time, it is required for the site to have that functionality enabled.
*/
class restore_process_course_modules_availability extends restore_execution_step {

    protected function define_execution() {
        global $CFG, $DB;

        // Site hasn't availability enabled
        if (empty($CFG->enableavailability)) {
            return;
        }

        // Get all the module_availability objects to process
        $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
        $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
        // Process availabilities, creating them if everything matches ok
        foreach($rs as $availrec) {
            $allmatchesok = true;
            // Get the complete availabilityobject
            $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
            // Map the sourcecmid if needed and possible
            if (!empty($availability->sourcecmid)) {
                $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
                if ($newcm) {
                    $availability->sourcecmid = $newcm->newitemid;
                } else {
                    $allmatchesok = false; // Failed matching, we won't create this availability rule
                }
            }
            // Map the gradeitemid if needed and possible
            if (!empty($availability->gradeitemid)) {
                $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
                if ($newgi) {
                    $availability->gradeitemid = $newgi->newitemid;
                } else {
                    $allmatchesok = false; // Failed matching, we won't create this availability rule
                }
            }
            if ($allmatchesok) { // Everything ok, create the availability rule
                $DB->insert_record('course_modules_availability', $availability);
            }
        }
        $rs->close();
    }
}


/*
* Execution step that, *conditionally* (if there isn't preloaded information)
* will load the inforef files for all the included course/section/activity tasks
* to backup_temp_ids. They will be stored with "xxxxref" as itemname
*/
class restore_load_included_inforef_records extends restore_execution_step {

    protected function define_execution() {

        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
            return;
        }

        // Get all the included tasks
        $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
        foreach ($tasks as $task) {
            // Load the inforef.xml file if exists
            $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
            if (file_exists($inforefpath)) {
                restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
            }
        }
    }
}

/*
* Execution step that will load all the needed files into backup_files_temp
* - info: contains the whole original object (times, names...)
* (all them being original ids as loaded from xml)
*/
class restore_load_included_files extends restore_structure_step {

    protected function define_structure() {

        $file = new restore_path_element('file', '/files/file');

        return array($file);
    }

    /**
* Process one <file> element from files.xml
*
* @param array $data the element data
*/
    public function process_file($data) {

        $data = (object)$data; // handy

        // load it if needed:
        // - it it is one of the annotated inforef files (course/section/activity/block)
        // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
        // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
        // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
        $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
        $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
                        $data->component == 'grouping' || $data->component == 'grade' ||
                        $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
        if ($isfileref || $iscomponent) {
            restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
        }
    }
}

/**
* Execution step that, *conditionally* (if there isn't preloaded information),
* will load all the needed roles to backup_temp_ids. They will be stored with
* "role" itemname. Also it will perform one automatic mapping to roles existing
* in the target site, based in permissions of the user performing the restore,
* archetypes and other bits. At the end, each original role will have its associated
* target role or 0 if it's going to be skipped. Note we wrap everything over one
* restore_dbops method, as far as the same stuff is going to be also executed
* by restore prechecks
*/
class restore_load_and_map_roles extends restore_execution_step {

    protected function define_execution() {
        if ($this->task->get_preloaded_information()) { // if info is already preloaded
            return;
        }

        $file = $this->get_basepath() . '/roles.xml';
        // Load needed toles to temp_ids
        restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);

        // Process roles, mapping/skipping. Any error throws exception
        // Note we pass controller's info because it can contain role mapping information
        // about manual mappings performed by UI
        restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings);
    }
}

/**
* Execution step that, *conditionally* (if there isn't preloaded information
* and users have been selected in settings, will load all the needed users
* to backup_temp_ids. They will be stored with "user" itemname and with
* their original contextid as paremitemid
*/
class restore_load_included_users extends restore_execution_step {

    protected function define_execution() {

        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
            return;
        }
        if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
            return;
        }
        $file = $this->get_basepath() . '/users.xml';
        restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
    }
}

/**
* Execution step that, *conditionally* (if there isn't preloaded information
* and users have been selected in settings, will process all the needed users
* in order to decide and perform any action with them (create / map / error)
* Note: Any error will cause exception, as far as this is the same processing
* than the one into restore prechecks (that should have stopped process earlier)
*/
class restore_process_included_users extends restore_execution_step {

    protected function define_execution() {

        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
            return;
        }
        if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
            return;
        }
        restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
    }
}

/**
* Execution step that will create all the needed users as calculated
* by @restore_process_included_users (those having newiteind = 0)
*/
class restore_create_included_users extends restore_execution_step {

    protected function define_execution() {

        restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid());
    }
}

/**
* Structure step that will create all the needed groups and groupings
* by loading them from the groups.xml file performing the required matches.
* Note group members only will be added if restoring user info
*/
class restore_groups_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array(); // Add paths here

        $paths[] = new restore_path_element('group', '/groups/group');
        if ($this->get_setting_value('users')) {
            $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
        }
        $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
        $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');

        return $paths;
    }

    // Processing functions go here
    public function process_group($data) {
        global $DB;

        $data = (object)$data; // handy
        $data->courseid = $this->get_courseid();

        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
        // another a group in the same course
        $context = context_course::instance($data->courseid);
        if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
            if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
                unset($data->idnumber);
            }
        } else {
            unset($data->idnumber);
        }

        $oldid = $data->id; // need this saved for later

        $restorefiles = false; // Only if we end creating the group

        // Search if the group already exists (by name & description) in the target course
        $description_clause = '';
        $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
        if (!empty($data->description)) {
            $description_clause = ' AND ' .
                                  $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
           $params['description'] = $data->description;
        }
        if (!$groupdb = $DB->get_record_sql("SELECT *
FROM {groups}
WHERE courseid = :courseid
AND name = :grname $description_clause", $params)) {
            // group doesn't exist, create
            $newitemid = $DB->insert_record('groups', $data);
            $restorefiles = true; // We'll restore the files
        } else {
            // group exists, use it
            $newitemid = $groupdb->id;
        }
        // Save the id mapping
        $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
    }

    public function process_member($data) {
        global $DB;

        $data = (object)$data; // handy

        // get parent group->id
        $data->groupid = $this->get_new_parentid('group');

        // map user newitemid and insert if not member already
        if ($data->userid = $this->get_mappingid('user', $data->userid)) {
            if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
                $DB->insert_record('groups_members', $data);
            }
        }
    }

    public function process_grouping($data) {
        global $DB;

        $data = (object)$data; // handy
        $data->courseid = $this->get_courseid();

        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
        // another a grouping in the same course
        $context = context_course::instance($data->courseid);
        if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
            if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
                unset($data->idnumber);
            }
        } else {
            unset($data->idnumber);
        }

        $oldid = $data->id; // need this saved for later
        $restorefiles = false; // Only if we end creating the grouping

        // Search if the grouping already exists (by name & description) in the target course
        $description_clause = '';
        $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
        if (!empty($data->description)) {
            $description_clause = ' AND ' .
                                  $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
           $params['description'] = $data->description;
        }
        if (!$groupingdb = $DB->get_record_sql("SELECT *
FROM {groupings}
WHERE courseid = :courseid
AND name = :grname $description_clause", $params)) {
            // grouping doesn't exist, create
            $newitemid = $DB->insert_record('groupings', $data);
            $restorefiles = true; // We'll restore the files
        } else {
            // grouping exists, use it
            $newitemid = $groupingdb->id;
        }
        // Save the id mapping
        $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
    }

    public function process_grouping_group($data) {
        global $DB;

        $data = (object)$data;

        $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
        $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings

        $params = array();
        $params['groupingid'] = $data->groupingid;
        $params['groupid'] = $data->groupid;

        if (!$DB->record_exists('groupings_groups', $params)) {
            $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
        }
    }

    protected function after_execute() {
        // Add group related files, matching with "group" mappings
        $this->add_related_files('group', 'icon', 'group');
        $this->add_related_files('group', 'description', 'group');
        // Add grouping related files, matching with "grouping" mappings
        $this->add_related_files('grouping', 'description', 'grouping');
    }

}

/**
* Structure step that will create all the needed scales
* by loading them from the scales.xml
*/
class restore_scales_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array(); // Add paths here
        $paths[] = new restore_path_element('scale', '/scales_definition/scale');
        return $paths;
    }

    protected function process_scale($data) {
        global $DB;

        $data = (object)$data;

        $restorefiles = false; // Only if we end creating the group

        $oldid = $data->id; // need this saved for later

        // Look for scale (by 'scale' both in standard (course=0) and current course
        // with priority to standard scales (ORDER clause)
        // scale is not course unique, use get_record_sql to suppress warning
        // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
        $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
        $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
        if (!$scadb = $DB->get_record_sql("SELECT *
FROM {scale}
WHERE courseid IN (0, :courseid)
AND $compare_scale_clause
ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
            // Remap the user if possible, defaut to user performing the restore if not
            $userid = $this->get_mappingid('user', $data->userid);
            $data->userid = $userid ? $userid : $this->task->get_userid();
            // Remap the course if course scale
            $data->courseid = $data->courseid ? $this->get_courseid() : 0;
            // If global scale (course=0), check the user has perms to create it
            // falling to course scale if not
            $systemctx = context_system::instance();
            if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
                $data->courseid = $this->get_courseid();
            }
            // scale doesn't exist, create
            $newitemid = $DB->insert_record('scale', $data);
            $restorefiles = true; // We'll restore the files
        } else {
            // scale exists, use it
            $newitemid = $scadb->id;
        }
        // Save the id mapping (with files support at system context)
        $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
    }

    protected function after_execute() {
        // Add scales related files, matching with "scale" mappings
        $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
    }
}


/**
* Structure step that will create all the needed outocomes
* by loading them from the outcomes.xml
*/
class restore_outcomes_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array(); // Add paths here
        $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
        return $paths;
    }

    protected function process_outcome($data) {
        global $DB;

        $data = (object)$data;

        $restorefiles = false; // Only if we end creating the group

        $oldid = $data->id; // need this saved for later

        // Look for outcome (by shortname both in standard (courseid=null) and current course
        // with priority to standard outcomes (ORDER clause)
        // outcome is not course unique, use get_record_sql to suppress warning
        $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
        if (!$outdb = $DB->get_record_sql('SELECT *
FROM {grade_outcomes}
WHERE shortname = :shortname
AND (courseid = :courseid OR courseid IS NULL)
ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
            // Remap the user
            $userid = $this->get_mappingid('user', $data->usermodified);
            $data->usermodified = $userid ? $userid : $this->task->get_userid();
            // Remap the scale
            $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
            // Remap the course if course outcome
            $data->courseid = $data->courseid ? $this->get_courseid() : null;
            // If global outcome (course=null), check the user has perms to create it
            // falling to course outcome if not
            $systemctx = context_system::instance();
            if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
                $data->courseid = $this->get_courseid();
            }
            // outcome doesn't exist, create
            $newitemid = $DB->insert_record('grade_outcomes', $data);
            $restorefiles = true; // We'll restore the files
        } else {
            // scale exists, use it
            $newitemid = $outdb->id;
        }
        // Set the corresponding grade_outcomes_courses record
        $outcourserec = new stdclass();
        $outcourserec->courseid = $this->get_courseid();
        $outcourserec->outcomeid = $newitemid;
        if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
            $DB->insert_record('grade_outcomes_courses', $outcourserec);
        }
        // Save the id mapping (with files support at system context)
        $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
    }

    protected function after_execute() {
        // Add outcomes related files, matching with "outcome" mappings
        $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
    }
}

/**
* Execution step that, *conditionally* (if there isn't preloaded information
* will load all the question categories and questions (header info only)
* to backup_temp_ids. They will be stored with "question_category" and
* "question" itemnames and with their original contextid and question category
* id as paremitemids
*/
class restore_load_categories_and_questions extends restore_execution_step {

    protected function define_execution() {

        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
            return;
        }
        $file = $this->get_basepath() . '/questions.xml';
        restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
    }
}

/**
* Execution step that, *conditionally* (if there isn't preloaded information)
* will process all the needed categories and questions
* in order to decide and perform any action with them (create / map / error)
* Note: Any error will cause exception, as far as this is the same processing
* than the one into restore prechecks (that should have stopped process earlier)
*/
class restore_process_categories_and_questions extends restore_execution_step {

    protected function define_execution() {

        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
            return;
        }
        restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
    }
}

/**
* Structure step that will read the section.xml creating/updating sections
* as needed, rebuilding course cache and other friends
*/
class restore_section_structure_step extends restore_structure_step {

    protected function define_structure() {
        global $CFG;

        $paths = array();

        $section = new restore_path_element('section', '/section');
        $paths[] = $section;
        if ($CFG->enableavailability) {
            $paths[] = new restore_path_element('availability', '/section/availability');
            $paths[] = new restore_path_element('availability_field', '/section/availability_field');
        }

        // Apply for 'format' plugins optional paths at section level
        $this->add_plugin_structure('format', $section);

        return $paths;
    }

    public function process_section($data) {
        global $CFG, $DB;
        $data = (object)$data;
        $oldid = $data->id; // We'll need this later

        $restorefiles = false;

        // Look for the section
        $section = new stdclass();
        $section->course = $this->get_courseid();
        $section->section = $data->number;
        // Section doesn't exist, create it with all the info from backup
        if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
            $section->name = $data->name;
            $section->summary = $data->summary;
            $section->summaryformat = $data->summaryformat;
            $section->sequence = '';
            $section->visible = $data->visible;
            if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
                $section->availablefrom = 0;
                $section->availableuntil = 0;
                $section->showavailability = 0;
            } else {
                $section->availablefrom = isset($data->availablefrom) ? $this->apply_date_offset($data->availablefrom) : 0;
                $section->availableuntil = isset($data->availableuntil) ? $this->apply_date_offset($data->availableuntil) : 0;
                $section->showavailability = isset($data->showavailability) ? $data->showavailability : 0;
            }
            if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
                $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
            }
            $newitemid = $DB->insert_record('course_sections', $section);
            $restorefiles = true;

        // Section exists, update non-empty information
        } else {
            $section->id = $secrec->id;
            if ((string)$secrec->name === '') {
                $section->name = $data->name;
            }
            if (empty($secrec->summary)) {
                $section->summary = $data->summary;
                $section->summaryformat = $data->summaryformat;
                $restorefiles = true;
            }
            if (empty($secrec->groupingid)) {
                if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
                    $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
                }
            }

            // Don't update available from, available until, or show availability
            // (I didn't see a useful way to define whether existing or new one should
            // take precedence).

            $DB->update_record('course_sections', $section);
            $newitemid = $secrec->id;
        }

        // Annotate the section mapping, with restorefiles option if needed
        $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);

        // set the new course_section id in the task
        $this->task->set_sectionid($newitemid);


        // Commented out. We never modify course->numsections as far as that is used
        // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
        // Note: We keep the code here, to know about and because of the possibility of making this
        // optional based on some setting/attribute in the future
        // If needed, adjust course->numsections
        //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
        // if ($numsections < $section->section) {
        // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
        // }
        //}
    }

    public function process_availability($data) {
        global $DB;
        $data = (object)$data;

        $data->coursesectionid = $this->task->get_sectionid();

        // NOTE: Other values in $data need updating, but these (cm,
        // grade items) have not yet been restored, so are done later.

        $newid = $DB->insert_record('course_sections_availability', $data);

        // We do not need to map between old and new id but storing a mapping
        // means it gets added to the backup_ids table to record which ones
        // need updating. The mapping is stored with $newid => $newid for
        // convenience.
        $this->set_mapping('course_sections_availability', $newid, $newid);
    }

    public function process_availability_field($data) {
        global $DB;
        $data = (object)$data;
        // Mark it is as passed by default
        $passed = true;
        $customfieldid = null;

        // If a customfield has been used in order to pass we must be able to match an existing
        // customfield by name (data->customfield) and type (data->customfieldtype)
        if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
            $passed = false;
        } else if (!is_null($data->customfield)) {
            $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
            $customfieldid = $DB->get_field('user_info_field', 'id', $params);
            $passed = ($customfieldid !== false);
        }

        if ($passed) {
            // Create the object to insert into the database
            $availfield = new stdClass();
            $availfield->coursesectionid = $this->task->get_sectionid();
            $availfield->userfield = $data->userfield;
            $availfield->customfieldid = $customfieldid;
            $availfield->operator = $data->operator;
            $availfield->value = $data->value;
            $DB->insert_record('course_sections_avail_fields', $availfield);
        }
    }

    protected function after_execute() {
        // Add section related files, with 'course_section' itemid to match
        $this->add_related_files('course', 'section', 'course_section');
    }

    public function after_restore() {
        global $DB;

        $sectionid = $this->get_task()->get_sectionid();

        // Get data object for current section availability (if any).
        $data = $DB->get_record('course_sections_availability',
                array('coursesectionid' => $sectionid), 'id, sourcecmid, gradeitemid', IGNORE_MISSING);

        // If it exists, update mappings.
        if ($data) {
            // Only update mappings for entries which are created by this restore.
            // Otherwise, when you restore to an existing course, it will mess up
            // existing section availability entries.
            if (!$this->get_mappingid('course_sections_availability', $data->id, false)) {
                return;
            }

            // Update source cmid / grade id to new value.
            $data->sourcecmid = $this->get_mappingid('course_module', $data->sourcecmid);
            if (!$data->sourcecmid) {
                $data->sourcecmid = null;
            }
            $data->gradeitemid = $this->get_mappingid('grade_item', $data->gradeitemid);
            if (!$data->gradeitemid) {
                $data->gradeitemid = null;
            }

            $DB->update_record('course_sections_availability', $data);
        }
    }
}


/**
* Structure step that will read the course.xml file, loading it and performing
* various actions depending of the site/restore settings. Note that target
* course always exist before arriving here so this step will be updating
* the course record (never inserting)
*/
class restore_course_structure_step extends restore_structure_step {
    /**
* @var bool this gets set to true by {@link process_course()} if we are
* restoring an old coures that used the legacy 'module security' feature.
* If so, we have to do more work in {@link after_execute()}.
*/
    protected $legacyrestrictmodules = false;

    /**
* @var array Used when {@link $legacyrestrictmodules} is true. This is an
* array with array keys the module names ('forum', 'quiz', etc.). These are
* the modules that are allowed according to the data in the backup file.
* In {@link after_execute()} we then have to prevent adding of all the other
* types of activity.
*/
    protected $legacyallowedmodules = array();

    protected function define_structure() {

        $course = new restore_path_element('course', '/course');
        $category = new restore_path_element('category', '/course/category');
        $tag = new restore_path_element('tag', '/course/tags/tag');
        $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');

        // Apply for 'format' plugins optional paths at course level
        $this->add_plugin_structure('format', $course);

        // Apply for 'theme' plugins optional paths at course level
        $this->add_plugin_structure('theme', $course);

        // Apply for 'report' plugins optional paths at course level
        $this->add_plugin_structure('report', $course);

        // Apply for 'course report' plugins optional paths at course level
        $this->add_plugin_structure('coursereport', $course);

        // Apply for plagiarism plugins optional paths at course level
        $this->add_plugin_structure('plagiarism', $course);

        return array($course, $category, $tag, $allowed_module);
    }

    /**
* Processing functions go here
*
* @global moodledatabase $DB
* @param stdClass $data
*/
    public function process_course($data) {
        global $CFG, $DB;

        $data = (object)$data;

        $fullname = $this->get_setting_value('course_fullname');
        $shortname = $this->get_setting_value('course_shortname');
        $startdate = $this->get_setting_value('course_startdate');

        // Calculate final course names, to avoid dupes
        list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);

        // Need to change some fields before updating the course record
        $data->id = $this->get_courseid();
        $data->fullname = $fullname;
        $data->shortname= $shortname;

        $context = context::instance_by_id($this->task->get_contextid());
        if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
            $data->idnumber = '';
        } else {
            unset($data->idnumber);
        }

        // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
        // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
        if (empty($data->hiddensections)) {
            $data->hiddensections = 0;
        }

        // Set legacyrestrictmodules to true if the course was resticting modules. If so
        // then we will need to process restricted modules after execution.
        $this->legacyrestrictmodules = !empty($data->restrictmodules);

        $data->startdate= $this->apply_date_offset($data->startdate);
        if ($data->defaultgroupingid) {
            $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
        }
        if (empty($CFG->enablecompletion)) {
            $data->enablecompletion = 0;
            $data->completionstartonenrol = 0;
            $data->completionnotify = 0;
        }
        $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
        if (!array_key_exists($data->lang, $languages)) {
            $data->lang = '';
        }

        $themes = get_list_of_themes(); // Get themes for quick search later
        if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
            $data->theme = '';
        }

        // Course record ready, update it
        $DB->update_record('course', $data);

        // Role name aliases
        restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
    }

    public function process_category($data) {
        // Nothing to do with the category. UI sets it before restore starts
    }

    public function process_tag($data) {
        global $CFG, $DB;

        $data = (object)$data;

        if (!empty($CFG->usetags)) { // if enabled in server
            // TODO: This is highly inneficient. Each time we add one tag
            // we fetch all the existing because tag_set() deletes them
            // so everything must be reinserted on each call
            $tags = array();
            $existingtags = tag_get_tags('course', $this->get_courseid());
            // Re-add all the existitng tags
            foreach ($existingtags as $existingtag) {
                $tags[] = $existingtag->rawname;
            }
            // Add the one being restored
            $tags[] = $data->rawname;
            // Send all the tags back to the course
            tag_set('course', $this->get_courseid(), $tags);
        }
    }

    public function process_allowed_module($data) {
        $data = (object)$data;

        // Backwards compatiblity support for the data that used to be in the
        // course_allowed_modules table.
        if ($this->legacyrestrictmodules) {
            $this->legacyallowedmodules[$data->modulename] = 1;
        }
    }

    protected function after_execute() {
        global $DB;

        // Add course related files, without itemid to match
        $this->add_related_files('course', 'summary', null);
        $this->add_related_files('course', 'legacy', null);

        // Deal with legacy allowed modules.
        if ($this->legacyrestrictmodules) {
            $context = context_course::instance($this->get_courseid());

            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
            foreach ($managerroleids as $roleid) {
                unset($roleids[$roleid]);
            }

            foreach (get_plugin_list('mod') as $modname => $notused) {
                if (isset($this->legacyallowedmodules[$modname])) {
                    // Module is allowed, no worries.
                    continue;
                }

                $capability = 'mod/' . $modname . ':addinstance';
                foreach ($roleids as $roleid) {
                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
                }
            }
        }
    }
}


/*
* Structure step that will read the roles.xml file (at course/activity/block levels)
* containig all the role_assignments and overrides for that context. If corresponding to
* one mapped role, they will be applied to target context. Will observe the role_assignments
* setting to decide if ras are restored.
* Note: only ras with component == null are restored as far as the any ra with component
* is handled by one enrolment plugin, hence it will createt the ras later
*/
class restore_ras_and_caps_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();

        // Observe the role_assignments setting
        if ($this->get_setting_value('role_assignments')) {
            $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
        }
        $paths[] = new restore_path_element('override', '/roles/role_overrides/override');

        return $paths;
    }

    /**
* Assign roles
*
* This has to be called after enrolments processing.
*
* @param mixed $data
* @return void
*/
    public function process_assignment($data) {
        global $DB;

        $data = (object)$data;

        // Check roleid, userid are one of the mapped ones
        if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
            return;
        }
        if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
            return;
        }
        if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
            // Only assign roles to not deleted users
            return;
        }
        if (!$contextid = $this->task->get_contextid()) {
            return;
        }

        if (empty($data->component)) {
            // assign standard manual roles
            // TODO: role_assign() needs one userid param to be able to specify our restore userid
            role_assign($newroleid, $newuserid, $contextid);

        } else if ((strpos($data->component, 'enrol_') === 0)) {
            // Deal with enrolment roles
            if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
                if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
                    //note: we have to verify component because it might have changed
                    if ($component === 'enrol_manual') {
                        // manual is a special case, we do not use components - this owudl happen when converting from other plugin
                        role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
                    } else {
                        role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
                    }
                }
            }
        }
    }

    public function process_override($data) {
        $data = (object)$data;

        // Check roleid is one of the mapped ones
        $newroleid = $this->get_mappingid('role', $data->roleid);
        // If newroleid and context are valid assign it via API (it handles dupes and so on)
        if ($newroleid && $this->task->get_contextid()) {
            // TODO: assign_capability() needs one userid param to be able to specify our restore userid
            // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
            assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
        }
    }
}

/**
* This structure steps restores the enrol plugins and their underlying
* enrolments, performing all the mappings and/or movements required
*/
class restore_enrolments_structure_step extends restore_structure_step {

    /**
* Conditionally decide if this step should be executed.
*
* This function checks the following parameter:
*
* 1. the course/enrolments.xml file exists
*
* @return bool true is safe to execute, false otherwise
*/
    protected function execute_condition() {

        // Check it is included in the backup
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            // Not found, can't restore enrolments info
            return false;
        }

        return true;
    }

    protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
        $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');

        return $paths;
    }

    /**
* Create enrolment instances.
*
* This has to be called after creation of roles
* and before adding of role assignments.
*
* @param mixed $data
* @return void
*/
    public function process_enrol($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id; // We'll need this later

        $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);

        if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
            // TODO: add complex restore support via custom class
            debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
            $this->set_mapping('enrol', $oldid, 0);
            return;
        }

        // Perform various checks to decide what to do with the enrol plugin
        if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
            // TODO: decide if we want to switch to manual enrol - we need UI for this
            debugging("Enrol plugin data can not be restored because it is not installed");
            $this->set_mapping('enrol', $oldid, 0);
            return;

        }
        if (!enrol_is_enabled($data->enrol)) {
            // TODO: decide if we want to switch to manual enrol - we need UI for this
            debugging("Enrol plugin data can not be restored because it is not enabled");
            $this->set_mapping('enrol', $oldid, 0);
            return;
        }

        // map standard fields - plugin has to process custom fields from own restore class
        $data->roleid = $this->get_mappingid('role', $data->roleid);
        //TODO: should we move the enrol start and end date here?

        // always add instance, if the course does not support multiple instances it just returns NULL
        $enrol = enrol_get_plugin($data->enrol);
        $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
        if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
            // ok
        } else {
            if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
                // most probably plugin that supports only one instance
                $newitemid = key($instances);
            } else {
                debugging('Can not create new enrol instance or reuse existing');
                $newitemid = 0;
            }
        }

        if ($restoretype === ENROL_RESTORE_NOUSERS) {
            // plugin requests to prevent restore of any users
            $newitemid = 0;
        }

        $this->set_mapping('enrol', $oldid, $newitemid);
    }

    /**
* Create user enrolments
*
* This has to be called after creation of enrolment instances
* and before adding of role assignments.
*
* @param mixed $data
* @return void
*/
    public function process_enrolment($data) {
        global $DB;

        $data = (object)$data;

        // Process only if parent instance have been mapped
        if ($enrolid = $this->get_new_parentid('enrol')) {
            if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
                // And only if user is a mapped one
                if ($userid = $this->get_mappingid('user', $data->userid)) {
                    $enrol = enrol_get_plugin($instance->enrol);
                    //TODO: do we need specify modifierid?
                    $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
                    //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
                }
            }
        }
    }
}


/**
* Make sure the user restoring the course can actually access it.
*/
class restore_fix_restorer_access_step extends restore_execution_step {
    protected function define_execution() {
        global $CFG, $DB;

        if (!$userid = $this->task->get_userid()) {
            return;
        }

        if (empty($CFG->restorernewroleid)) {
            // Bad luck, no fallback role for restorers specified
            return;
        }

        $courseid = $this->get_courseid();
        $context = context_course::instance($courseid);

        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
            // Current user may access the course (admin, category manager or restored teacher enrolment usually)
            return;
        }

        // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
        role_assign($CFG->restorernewroleid, $userid, $context);

        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
            // Extra role is enough, yay!
            return;
        }

        // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
        // hopefully admin selected suitable $CFG->restorernewroleid ...
        if (!enrol_is_enabled('manual')) {
            return;
        }
        if (!$enrol = enrol_get_plugin('manual')) {
            return;
        }
        if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
            $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
            $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
            $enrol->add_instance($course, $fields);
        }

        enrol_try_internal_enrol($courseid, $userid);
    }
}


/**
* This structure steps restores the filters and their configs
*/
class restore_filters_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
        $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');

        return $paths;
    }

    public function process_active($data) {

        $data = (object)$data;

        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
            return;
        }
        filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
    }

    public function process_config($data) {

        $data = (object)$data;

        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
            return;
        }
        filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
    }
}


/**
* This structure steps restores the comments
* Note: Cannot use the comments API because defaults to USER->id.
* That should change allowing to pass $userid
*/
class restore_comments_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('comment', '/comments/comment');

        return $paths;
    }

    public function process_comment($data) {
        global $DB;

        $data = (object)$data;

        // First of all, if the comment has some itemid, ask to the task what to map
        $mapping = false;
        if ($data->itemid) {
            $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
            $data->itemid = $this->get_mappingid($mapping, $data->itemid);
        }
        // Only restore the comment if has no mapping OR we have found the matching mapping
        if (!$mapping || $data->itemid) {
            // Only if user mapping and context
            $data->userid = $this->get_mappingid('user', $data->userid);
            if ($data->userid && $this->task->get_contextid()) {
                $data->contextid = $this->task->get_contextid();
                // Only if there is another comment with same context/user/timecreated
                $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
                if (!$DB->record_exists('comments', $params)) {
                    $DB->insert_record('comments', $data);
                }
            }
        }
    }
}

/**
* This structure steps restores the calendar events
*/
class restore_calendarevents_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('calendarevents', '/events/event');

        return $paths;
    }

    public function process_calendarevents($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;
        $restorefiles = true; // We'll restore the files
        // Find the userid and the groupid associated with the event. Return if not found.
        $data->userid = $this->get_mappingid('user', $data->userid);
        if ($data->userid === false) {
            return;
        }
        if (!empty($data->groupid)) {
            $data->groupid = $this->get_mappingid('group', $data->groupid);
            if ($data->groupid === false) {
                return;
            }
        }
        // Handle events with empty eventtype //MDL-32827
        if(empty($data->eventtype)) {
            if ($data->courseid == $SITE->id) { // Site event
                $data->eventtype = "site";
            } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
                // Course assingment event
                $data->eventtype = "due";
            } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
                $data->eventtype = "course";
            } else if ($data->groupid) { // Group event
                $data->eventtype = "group";
            } else if ($data->userid) { // User event
                $data->eventtype = "user";
            } else {
                return;
            }
        }

        $params = array(
                'name' => $data->name,
                'description' => $data->description,
                'format' => $data->format,
                'courseid' => $this->get_courseid(),
                'groupid' => $data->groupid,
                'userid' => $data->userid,
                'repeatid' => $data->repeatid,
                'modulename' => $data->modulename,
                'eventtype' => $data->eventtype,
                'timestart' => $this->apply_date_offset($data->timestart),
                'timeduration' => $data->timeduration,
                'visible' => $data->visible,
                'uuid' => $data->uuid,
                'sequence' => $data->sequence,
                'timemodified' => $this->apply_date_offset($data->timemodified));
        if ($this->name == 'activity_calendar') {
            $params['instance'] = $this->task->get_activityid();
        } else {
            $params['instance'] = 0;
        }
        $sql = 'SELECT id FROM {event} WHERE name = ? AND courseid = ? AND
repeatid = ? AND modulename = ? AND timestart = ? AND timeduration =?
AND ' . $DB->sql_compare_text('description', 255) . ' = ' . $DB->sql_compare_text('?', 255);
        $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
        $result = $DB->record_exists_sql($sql, $arg);
        if (empty($result)) {
            $newitemid = $DB->insert_record('event', $params);
            $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
        }

    }
    protected function after_execute() {
        // Add related files
        $this->add_related_files('calendar', 'event_description', 'event_description');
    }
}

class restore_course_completion_structure_step extends restore_structure_step {

    /**
* Conditionally decide if this step should be executed.
*
* This function checks parameters that are not immediate settings to ensure
* that the enviroment is suitable for the restore of course completion info.
*
* This function checks the following four parameters:
*
* 1. Course completion is enabled on the site
* 2. The backup includes course completion information
* 3. All modules are restorable
* 4. All modules are marked for restore.
*
* @return bool True is safe to execute, false otherwise
*/
    protected function execute_condition() {
        global $CFG;

        // First check course completion is enabled on this site
        if (empty($CFG->enablecompletion)) {
            // Disabled, don't restore course completion
            return false;
        }

        // Check it is included in the backup
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            // Not found, can't restore course completion
            return false;
        }

        // Check we are able to restore all backed up modules
        if ($this->task->is_missing_modules()) {
            return false;
        }

        // Finally check all modules within the backup are being restored.
        if ($this->task->is_excluding_activities()) {
            return false;
        }

        return true;
    }

    /**
* Define the course completion structure
*
* @return array Array of restore_path_element
*/
    protected function define_structure() {

        // To know if we are including user completion info
        $userinfo = $this->get_setting_value('userscompletion');

        $paths = array();
        $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
        $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');

        if ($userinfo) {
            $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
            $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
        }

        return $paths;

    }

    /**
* Process course completion criteria
*
* @global moodle_database $DB
* @param stdClass $data
*/
    public function process_course_completion_criteria($data) {
        global $DB;

        $data = (object)$data;
        $data->course = $this->get_courseid();

        // Apply the date offset to the time end field
        $data->timeend = $this->apply_date_offset($data->timeend);

        // Map the role from the criteria
        if (!empty($data->role)) {
            $data->role = $this->get_mappingid('role', $data->role);
        }

        $skipcriteria = false;

        // If the completion criteria is for a module we need to map the module instance
        // to the new module id.
        if (!empty($data->moduleinstance) && !empty($data->module)) {
            $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
            if (empty($data->moduleinstance)) {
                $skipcriteria = true;
            }
        } else {
            $data->module = null;
            $data->moduleinstance = null;
        }

        // We backup the course shortname rather than the ID so that we can match back to the course
        if (!empty($data->courseinstanceshortname)) {
            $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
            if (!$courseinstanceid) {
                $skipcriteria = true;
            }
        } else {
            $courseinstanceid = null;
        }
        $data->courseinstance = $courseinstanceid;

        if (!$skipcriteria) {
            $params = array(
                'course' => $data->course,
                'criteriatype' => $data->criteriatype,
                'enrolperiod' => $data->enrolperiod,
                'courseinstance' => $data->courseinstance,
                'module' => $data->module,
                'moduleinstance' => $data->moduleinstance,
                'timeend' => $data->timeend,
                'gradepass' => $data->gradepass,
                'role' => $data->role
            );
            $newid = $DB->insert_record('course_completion_criteria', $params);
            $this->set_mapping('course_completion_criteria', $data->id, $newid);
        }
    }

    /**
* Processes course compltion criteria complete records
*
* @global moodle_database $DB
* @param stdClass $data
*/
    public function process_course_completion_crit_compl($data) {
        global $DB;

        $data = (object)$data;

        // This may be empty if criteria could not be restored
        $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);

        $data->course = $this->get_courseid();
        $data->userid = $this->get_mappingid('user', $data->userid);

        if (!empty($data->criteriaid) && !empty($data->userid)) {
            $params = array(
                'userid' => $data->userid,
                'course' => $data->course,
                'criteriaid' => $data->criteriaid,
                'timecompleted' => $this->apply_date_offset($data->timecompleted)
            );
            if (isset($data->gradefinal)) {
                $params['gradefinal'] = $data->gradefinal;
            }
            if (isset($data->unenroled)) {
                $params['unenroled'] = $data->unenroled;
            }
            $DB->insert_record('course_completion_crit_compl', $params);
        }
    }

    /**
* Process course completions
*
* @global moodle_database $DB
* @param stdClass $data
*/
    public function process_course_completions($data) {
        global $DB;

        $data = (object)$data;

        $data->course = $this->get_courseid();
        $data->userid = $this->get_mappingid('user', $data->userid);

        if (!empty($data->userid)) {
            $params = array(
                'userid' => $data->userid,
                'course' => $data->course,
                'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
                'timestarted' => $this->apply_date_offset($data->timestarted),
                'timecompleted' => $this->apply_date_offset($data->timecompleted),
                'reaggregate' => $data->reaggregate
            );
            $DB->insert_record('course_completions', $params);
        }
    }

    /**
* Process course completion aggregate methods
*
* @global moodle_database $DB
* @param stdClass $data
*/
    public function process_course_completion_aggr_methd($data) {
        global $DB;

        $data = (object)$data;

        $data->course = $this->get_courseid();

        // Only create the course_completion_aggr_methd records if
        // the target course has not them defined. MDL-28180
        if (!$DB->record_exists('course_completion_aggr_methd', array(
                    'course' => $data->course,
                    'criteriatype' => $data->criteriatype))) {
            $params = array(
                'course' => $data->course,
                'criteriatype' => $data->criteriatype,
                'method' => $data->method,
                'value' => $data->value,
            );
            $DB->insert_record('course_completion_aggr_methd', $params);
        }
    }
}


/**
* This structure step restores course logs (cmid = 0), delegating
* the hard work to the corresponding {@link restore_logs_processor} passing the
* collection of {@link restore_log_rule} rules to be observed as they are defined
* by the task. Note this is only executed based in the 'logs' setting.
*
* NOTE: This is executed by final task, to have all the activities already restored
*
* NOTE: Not all course logs are being restored. For now only 'course' and 'user'
* records are. There are others like 'calendar' and 'upload' that will be handled
* later.
*
* NOTE: All the missing actions (not able to be restored) are sent to logs for
* debugging purposes
*/
class restore_course_logs_structure_step extends restore_structure_step {

    /**
* Conditionally decide if this step should be executed.
*
* This function checks the following parameter:
*
* 1. the course/logs.xml file exists
*
* @return bool true is safe to execute, false otherwise
*/
    protected function execute_condition() {

        // Check it is included in the backup
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            // Not found, can't restore course logs
            return false;
        }

        return true;
    }

    protected function define_structure() {

        $paths = array();

        // Simple, one plain level of information contains them
        $paths[] = new restore_path_element('log', '/logs/log');

        return $paths;
    }

    protected function process_log($data) {
        global $DB;

        $data = (object)($data);

        $data->time = $this->apply_date_offset($data->time);
        $data->userid = $this->get_mappingid('user', $data->userid);
        $data->course = $this->get_courseid();
        $data->cmid = 0;

        // For any reason user wasn't remapped ok, stop processing this
        if (empty($data->userid)) {
            return;
        }

        // Everything ready, let's delegate to the restore_logs_processor

        // Set some fixed values that will save tons of DB requests
        $values = array(
            'course' => $this->get_courseid());
        // Get instance and process log record
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);

        // If we have data, insert it, else something went wrong in the restore_logs_processor
        if ($data) {
            $DB->insert_record('log', $data);
        }
    }
}

/**
* This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
* sharing its same structure but modifying the way records are handled
*/
class restore_activity_logs_structure_step extends restore_course_logs_structure_step {

    protected function process_log($data) {
        global $DB;

        $data = (object)($data);

        $data->time = $this->apply_date_offset($data->time);
        $data->userid = $this->get_mappingid('user', $data->userid);
        $data->course = $this->get_courseid();
        $data->cmid = $this->task->get_moduleid();

        // For any reason user wasn't remapped ok, stop processing this
        if (empty($data->userid)) {
            return;
        }

        // Everything ready, let's delegate to the restore_logs_processor

        // Set some fixed values that will save tons of DB requests
        $values = array(
            'course' => $this->get_courseid(),
            'course_module' => $this->task->get_moduleid(),
            $this->task->get_modulename() => $this->task->get_activityid());
        // Get instance and process log record
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);

        // If we have data, insert it, else something went wrong in the restore_logs_processor
        if ($data) {
            $DB->insert_record('log', $data);
        }
    }
}


/**
* Defines the restore step for advanced grading methods attached to the activity module
*/
class restore_activity_grading_structure_step extends restore_structure_step {

    /**
* This step is executed only if the grading file is present
*/
     protected function execute_condition() {

        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            return false;
        }

        return true;
    }


    /**
* Declares paths in the grading.xml file we are interested in
*/
    protected function define_structure() {

        $paths = array();
        $userinfo = $this->get_setting_value('userinfo');

        $paths[] = new restore_path_element('grading_area', '/areas/area');

        $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
        $paths[] = $definition;
        $this->add_plugin_structure('gradingform', $definition);

        if ($userinfo) {
            $instance = new restore_path_element('grading_instance',
                '/areas/area/definitions/definition/instances/instance');
            $paths[] = $instance;
            $this->add_plugin_structure('gradingform', $instance);
        }

        return $paths;
    }

    /**
* Processes one grading area element
*
* @param array $data element data
*/
    protected function process_grading_area($data) {
        global $DB;

        $task = $this->get_task();
        $data = (object)$data;
        $oldid = $data->id;
        $data->component = 'mod_'.$task->get_modulename();
        $data->contextid = $task->get_contextid();

        $newid = $DB->insert_record('grading_areas', $data);
        $this->set_mapping('grading_area', $oldid, $newid);
    }

    /**
* Processes one grading definition element
*
* @param array $data element data
*/
    protected function process_grading_definition($data) {
        global $DB;

        $task = $this->get_task();
        $data = (object)$data;
        $oldid = $data->id;
        $data->areaid = $this->get_new_parentid('grading_area');
        $data->copiedfromid = null;
        $data->timecreated = time();
        $data->usercreated = $task->get_userid();
        $data->timemodified = $data->timecreated;
        $data->usermodified = $data->usercreated;

        $newid = $DB->insert_record('grading_definitions', $data);
        $this->set_mapping('grading_definition', $oldid, $newid, true);
    }

    /**
* Processes one grading form instance element
*
* @param array $data element data
*/
    protected function process_grading_instance($data) {
        global $DB;

        $data = (object)$data;

        // new form definition id
        $newformid = $this->get_new_parentid('grading_definition');

        // get the name of the area we are restoring to
        $sql = "SELECT ga.areaname
FROM {grading_definitions} gd
JOIN {grading_areas} ga ON gd.areaid = ga.id
WHERE gd.id = ?";
        $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);

        // get the mapped itemid - the activity module is expected to define the mappings
        // for each gradable area
        $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);

        $oldid = $data->id;
        $data->definitionid = $newformid;
        $data->raterid = $this->get_mappingid('user', $data->raterid);
        $data->itemid = $newitemid;

        $newid = $DB->insert_record('grading_instances', $data);
        $this->set_mapping('grading_instance', $oldid, $newid);
    }

    /**
* Final operations when the database records are inserted
*/
    protected function after_execute() {
        // Add files embedded into the definition description
        $this->add_related_files('grading', 'description', 'grading_definition');
    }
}


/**
* This structure step restores the grade items associated with one activity
* All the grade items are made child of the "course" grade item but the original
* categoryid is saved as parentitemid in the backup_ids table, so, when restoring
* the complete gradebook (categories and calculations), that information is
* available there
*/
class restore_activity_grades_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();
        $userinfo = $this->get_setting_value('userinfo');

        $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
        $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
        if ($userinfo) {
            $paths[] = new restore_path_element('grade_grade',
                           '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
        }
        return $paths;
    }

    protected function process_grade_item($data) {
        global $DB;

        $data = (object)($data);
        $oldid = $data->id; // We'll need these later
        $oldparentid = $data->categoryid;
        $courseid = $this->get_courseid();

        // make sure top course category exists, all grade items will be associated
        // to it. Later, if restoring the whole gradebook, categories will be introduced
        $coursecat = grade_category::fetch_course_category($courseid);
        $coursecatid = $coursecat->id; // Get the categoryid to be used

        $idnumber = null;
        if (!empty($data->idnumber)) {
            // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
            // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
            // so the best is to keep the ones already in the gradebook
            // Potential problem: duplicates if same items are restored more than once. :-(
            // This needs to be fixed in some way (outcomes & activities with multiple items)
            // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
            // In any case, verify always for uniqueness
            $sql = "SELECT cm.id
FROM {course_modules} cm
WHERE cm.course = :courseid AND
cm.idnumber = :idnumber AND
cm.id <> :cmid";
            $params = array(
                'courseid' => $courseid,
                'idnumber' => $data->idnumber,
                'cmid' => $this->task->get_moduleid()
            );
            if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
                $idnumber = $data->idnumber;
            }
        }

        unset($data->id);
        $data->categoryid = $coursecatid;
        $data->courseid = $this->get_courseid();
        $data->iteminstance = $this->task->get_activityid();
        $data->idnumber = $idnumber;
        $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
        $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
        $data->timecreated = $this->apply_date_offset($data->timecreated);
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        $gradeitem = new grade_item($data, false);
        $gradeitem->insert('restore');

        //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
        $gradeitem->sortorder = $data->sortorder;
        $gradeitem->update('restore');

        // Set mapping, saving the original category id into parentitemid
        // gradebook restore (final task) will need it to reorganise items
        $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
    }

    protected function process_grade_grade($data) {
        $data = (object)($data);
        $olduserid = $data->userid;
        unset($data->id);

        $data->itemid = $this->get_new_parentid('grade_item');

        $data->userid = $this->get_mappingid('user', $data->userid, null);
        if (!empty($data->userid)) {
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
            // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
            $data->overridden = $this->apply_date_offset($data->overridden);

            $grade = new grade_grade($data, false);
            $grade->insert('restore');
            // no need to save any grade_grade mapping
        } else {
            debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
        }
    }

    /**
* process activity grade_letters. Note that, while these are possible,
* because grade_letters are contextid based, in proctice, only course
* context letters can be defined. So we keep here this method knowing
* it won't be executed ever. gradebook restore will restore course letters.
*/
    protected function process_grade_letter($data) {
        global $DB;

        $data = (object)$data;

        $data->contextid = $this->task->get_contextid();
        $newitemid = $DB->insert_record('grade_letters', $data);
        // no need to save any grade_letter mapping
    }
}


/**
* This structure steps restores one instance + positions of one block
* Note: Positions corresponding to one existing context are restored
* here, but all the ones having unknown contexts are sent to backup_ids
* for a later chance to be restored at the end (final task)
*/
class restore_block_instance_structure_step extends restore_structure_step {

    protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
        $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');

        return $paths;
    }

    public function process_block($data) {
        global $DB, $CFG;

        $data = (object)$data; // Handy
        $oldcontextid = $data->contextid;
        $oldid = $data->id;
        $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();

        // Look for the parent contextid
        if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
            throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
        }

        // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
        // If there is already one block of that type in the parent context
        // and the block is not multiple, stop processing
        // Use blockslib loader / method executor
        if (!$bi = block_instance($data->blockname)) {
            return false;
        }

        if (!$bi->instance_allow_multiple()) {
            if ($DB->record_exists_sql("SELECT bi.id
FROM {block_instances} bi
JOIN {block} b ON b.name = bi.blockname
WHERE bi.parentcontextid = ?
AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
                return false;
            }
        }

        // If there is already one block of that type in the parent context
        // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
        // stop processing
        $params = array(
            'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
            'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
            'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
        if ($birecs = $DB->get_records('block_instances', $params)) {
            foreach($birecs as $birec) {
                if ($birec->configdata == $data->configdata) {
                    return false;
                }
            }
        }

        // Set task old contextid, blockid and blockname once we know them
        $this->task->set_old_contextid($oldcontextid);
        $this->task->set_old_blockid($oldid);
        $this->task->set_blockname($data->blockname);

        // Let's look for anything within configdata neededing processing
        // (nulls and uses of legacy file.php)
        if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
            $configdata = (array)unserialize(base64_decode($data->configdata));
            foreach ($configdata as $attribute => $value) {
                if (in_array($attribute, $attrstotransform)) {
                    $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
                }
            }
            $data->configdata = base64_encode(serialize((object)$configdata));
        }

        // Create the block instance
        $newitemid = $DB->insert_record('block_instances', $data);
        // Save the mapping (with restorefiles support)
        $this->set_mapping('block_instance', $oldid, $newitemid, true);
        // Create the block context
        $newcontextid = context_block::instance($newitemid)->id;
        // Save the block contexts mapping and sent it to task
        $this->set_mapping('context', $oldcontextid, $newcontextid);
        $this->task->set_contextid($newcontextid);
        $this->task->set_blockid($newitemid);

        // Restore block fileareas if declared
        $component = 'block_' . $this->task->get_blockname();
        foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
            $this->add_related_files($component, $filearea, null);
        }

        // Process block positions, creating them or accumulating for final step
        foreach($positions as $position) {
            $position = (object)$position;
            $position->blockinstanceid = $newitemid; // The instance is always the restored one
            // If position is for one already mapped (known) contextid
            // process it now, creating the position
            if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
                $position->contextid = $newpositionctxid;
                // Create the block position
                $DB->insert_record('block_positions', $position);

            // The position belongs to an unknown context, send it to backup_ids
            // to process them as part of the final steps of restore. We send the
            // whole $position object there, hence use the low level method.
            } else {
                restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
            }
        }
    }
}

/**
* Structure step to restore common course_module information
*
* This step will process the module.xml file for one activity, in order to restore
* the corresponding information to the course_modules table, skipping various bits
* of information based on CFG settings (groupings, completion...) in order to fullfill
* all the reqs to be able to create the context to be used by all the rest of steps
* in the activity restore task
*/
class restore_module_structure_step extends restore_structure_step {

    protected function define_structure() {
        global $CFG;

        $paths = array();

        $module = new restore_path_element('module', '/module');
        $paths[] = $module;
        if ($CFG->enableavailability) {
            $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
            $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
        }

        // Apply for 'format' plugins optional paths at module level
        $this->add_plugin_structure('format', $module);

        // Apply for 'plagiarism' plugins optional paths at module level
        $this->add_plugin_structure('plagiarism', $module);

        return $paths;
    }

    protected function process_module($data) {
        global $CFG, $DB;

        $data = (object)$data;
        $oldid = $data->id;
        $this->task->set_old_moduleversion($data->version);

        $data->course = $this->task->get_courseid();
        $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
        // Map section (first try by course_section mapping match. Useful in course and section restores)
        $data->section = $this->get_mappingid('course_section', $data->sectionid);
        if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
            $params = array(
                'course' => $this->get_courseid(),
                'section' => $data->sectionnumber);
            $data->section = $DB->get_field('course_sections', 'id', $params);
        }
        if (!$data->section) { // sectionnumber failed, try to get first section in course
            $params = array(
                'course' => $this->get_courseid());
            $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
        }
        if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
            $sectionrec = array(
                'course' => $this->get_courseid(),
                'section' => 0);
            $DB->insert_record('course_sections', $sectionrec); // section 0
            $sectionrec = array(
                'course' => $this->get_courseid(),
                'section' => 1);
            $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
        }
        $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
        if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
            $data->groupmembersonly = 0;
        }
        if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
            $data->idnumber = '';
        }
        if (empty($CFG->enablecompletion)) { // completion
            $data->completion = 0;
            $data->completiongradeitemnumber = null;
            $data->completionview = 0;
            $data->completionexpected = 0;
        } else {
            $data->completionexpected = $this->apply_date_offset($data->completionexpected);
        }
        if (empty($CFG->enableavailability)) {
            $data->availablefrom = 0;
            $data->availableuntil = 0;
            $data->showavailability = 0;
        } else {
            $data->availablefrom = $this->apply_date_offset($data->availablefrom);
            $data->availableuntil= $this->apply_date_offset($data->availableuntil);
        }
        // Backups that did not include showdescription, set it to default 0
        // (this is not totally necessary as it has a db default, but just to
        // be explicit).
        if (!isset($data->showdescription)) {
            $data->showdescription = 0;
        }
        $data->instance = 0; // Set to 0 for now, going to create it soon (next step)

        // course_module record ready, insert it
        $newitemid = $DB->insert_record('course_modules', $data);
        // save mapping
        $this->set_mapping('course_module', $oldid, $newitemid);
        // set the new course_module id in the task
        $this->task->set_moduleid($newitemid);
        // we can now create the context safely
        $ctxid = context_module::instance($newitemid)->id;
        // set the new context id in the task
        $this->task->set_contextid($ctxid);
        // update sequence field in course_section
        if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
            $sequence .= ',' . $newitemid;
        } else {
            $sequence = $newitemid;
        }
        $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
    }

    protected function process_availability($data) {
        $data = (object)$data;
        // Simply going to store the whole availability record now, we'll process
        // all them later in the final task (once all activities have been restored)
        // Let's call the low level one to be able to store the whole object
        $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
    }

    protected function process_availability_field($data) {
        global $DB;
        $data = (object)$data;
        // Mark it is as passed by default
        $passed = true;
        $customfieldid = null;

        // If a customfield has been used in order to pass we must be able to match an existing
        // customfield by name (data->customfield) and type (data->customfieldtype)
        if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
            $passed = false;
        } else if (!empty($data->customfield)) {
            $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
            $customfieldid = $DB->get_field('user_info_field', 'id', $params);
            $passed = ($customfieldid !== false);
        }

        if ($passed) {
            // Create the object to insert into the database
            $availfield = new stdClass();
            $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
            $availfield->userfield = $data->userfield;
            $availfield->customfieldid = $customfieldid;
            $availfield->operator = $data->operator;
            $availfield->value = $data->value;
            // Insert into the database
            $DB->insert_record('course_modules_avail_fields', $availfield);
        }
    }
}

/**
* Structure step that will process the user activity completion
* information if all these conditions are met:
* - Target site has completion enabled ($CFG->enablecompletion)
* - Activity includes completion info (file_exists)
*/
class restore_userscompletion_structure_step extends restore_structure_step {
    /**
* To conditionally decide if this step must be executed
* Note the "settings" conditions are evaluated in the
* corresponding task. Here we check for other conditions
* not being restore settings (files, site settings...)
*/
     protected function execute_condition() {
         global $CFG;

         // Completion disabled in this site, don't execute
         if (empty($CFG->enablecompletion)) {
             return false;
         }

         // No user completion info found, don't execute
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
         if (!file_exists($fullpath)) {
             return false;
         }

         // Arrived here, execute the step
         return true;
     }

     protected function define_structure() {

        $paths = array();

        $paths[] = new restore_path_element('completion', '/completions/completion');

        return $paths;
    }

    protected function process_completion($data) {
        global $DB;

        $data = (object)$data;

        $data->coursemoduleid = $this->task->get_moduleid();
        $data->userid = $this->get_mappingid('user', $data->userid);
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        // Find the existing record
        $existing = $DB->get_record('course_modules_completion', array(
                'coursemoduleid' => $data->coursemoduleid,
                'userid' => $data->userid), 'id, timemodified');
        // Check we didn't already insert one for this cmid and userid
        // (there aren't supposed to be duplicates in that field, but
        // it was possible until MDL-28021 was fixed).
        if ($existing) {
            // Update it to these new values, but only if the time is newer
            if ($existing->timemodified < $data->timemodified) {
                $data->id = $existing->id;
                $DB->update_record('course_modules_completion', $data);
            }
        } else {
            // Normal entry where it doesn't exist already
            $DB->insert_record('course_modules_completion', $data);
        }
    }
}

/**
* Abstract structure step, parent of all the activity structure steps. Used to suuport
* the main <activity ...> tag and process it. Also provides subplugin support for
* activities.
*/
abstract class restore_activity_structure_step extends restore_structure_step {

    protected function add_subplugin_structure($subplugintype, $element) {

        global $CFG;

        // Check the requested subplugintype is a valid one
        $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
        if (!file_exists($subpluginsfile)) {
             throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
        }
        include($subpluginsfile);
        if (!array_key_exists($subplugintype, $subplugins)) {
             throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
        }
        // Get all the restore path elements, looking across all the subplugin dirs
        $subpluginsdirs = get_plugin_list($subplugintype);
        foreach ($subpluginsdirs as $name => $subpluginsdir) {
            $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
            $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
            if (file_exists($restorefile)) {
                require_once($restorefile);
                $restoresubplugin = new $classname($subplugintype, $name, $this);
                // Add subplugin paths to the step
                $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
            }
        }
    }

    /**
* As far as activity restore steps are implementing restore_subplugin stuff, they need to
* have the parent task available for wrapping purposes (get course/context....)
* @return restore_task
*/
    public function get_task() {
        return $this->task;
    }

    /**
* Adds support for the 'activity' path that is common to all the activities
* and will be processed globally here
*/
    protected function prepare_activity_structure($paths) {

        $paths[] = new restore_path_element('activity', '/activity');

        return $paths;
    }

    /**
* Process the activity path, informing the task about various ids, needed later
*/
    protected function process_activity($data) {
        $data = (object)$data;
        $this->task->set_old_contextid($data->contextid); // Save old contextid in task
        $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
        $this->task->set_old_activityid($data->id); // Save old activityid in task
    }

    /**
* This must be invoked immediately after creating the "module" activity record (forum, choice...)
* and will adjust the new activity id (the instance) in various places
*/
    protected function apply_activity_instance($newitemid) {
        global $DB;

        $this->task->set_activityid($newitemid); // Save activity id in task
        // Apply the id to course_sections->instanceid
        $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
        // Do the mapping for modulename, preparing it for files by oldcontext
        $modulename = $this->task->get_modulename();
        $oldid = $this->task->get_old_activityid();
        $this->set_mapping($modulename, $oldid, $newitemid, true);
    }
}

/**
* Structure step in charge of creating/mapping all the qcats and qs
* by parsing the questions.xml file and checking it against the
* results calculated by {@link restore_process_categories_and_questions}
* and stored in backup_ids_temp
*/
class restore_create_categories_and_questions extends restore_structure_step {

    protected function define_structure() {

        $category = new restore_path_element('question_category', '/question_categories/question_category');
        $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
        $hint = new restore_path_element('question_hint',
                '/question_categories/question_category/questions/question/question_hints/question_hint');

        // Apply for 'qtype' plugins optional paths at question level
        $this->add_plugin_structure('qtype', $question);

        return array($category, $question, $hint);
    }

    protected function process_question_category($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        // Check we have one mapping for this category
        if (!$mapping = $this->get_mapping('question_category', $oldid)) {
            return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
        }

        // Check we have to create the category (newitemid = 0)
        if ($mapping->newitemid) {
            return; // newitemid != 0, this category is going to be mapped. Nothing to do
        }

        // Arrived here, newitemid = 0, we need to create the category
        // we'll do it at parentitemid context, but for CONTEXT_MODULE
        // categories, that will be created at CONTEXT_COURSE and moved
        // to module context later when the activity is created
        if ($mapping->info->contextlevel == CONTEXT_MODULE) {
            $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
        }
        $data->contextid = $mapping->parentitemid;

        // Let's create the question_category and save mapping
        $newitemid = $DB->insert_record('question_categories', $data);
        $this->set_mapping('question_category', $oldid, $newitemid);
        // Also annotate them as question_category_created, we need
        // that later when remapping parents
        $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
    }

    protected function process_question($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        // Check we have one mapping for this question
        if (!$questionmapping = $this->get_mapping('question', $oldid)) {
            return; // No mapping = this question doesn't need to be created/mapped
        }

        // Get the mapped category (cannot use get_new_parentid() because not
        // all the categories have been created, so it is not always available
        // Instead we get the mapping for the question->parentitemid because
        // we have loaded qcatids there for all parsed questions
        $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);

        // In the past, there were some very sloppy values of penalty. Fix them.
        if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
            $data->penalty = 0.3333333;
        }
        if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
            $data->penalty = 0.6666667;
        }
        if ($data->penalty >= 1) {
            $data->penalty = 1;
        }

        $data->timecreated = $this->apply_date_offset($data->timecreated);
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        $userid = $this->get_mappingid('user', $data->createdby);
        $data->createdby = $userid ? $userid : $this->task->get_userid();

        $userid = $this->get_mappingid('user', $data->modifiedby);
        $data->modifiedby = $userid ? $userid : $this->task->get_userid();

        // With newitemid = 0, let's create the question
        if (!$questionmapping->newitemid) {
            $newitemid = $DB->insert_record('question', $data);
            $this->set_mapping('question', $oldid, $newitemid);
            // Also annotate them as question_created, we need
            // that later when remapping parents (keeping the old categoryid as parentid)
            $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
        } else {
            // By performing this set_mapping() we make get_old/new_parentid() to work for all the
            // children elements of the 'question' one (so qtype plugins will know the question they belong to)
            $this->set_mapping('question', $oldid, $questionmapping->newitemid);
        }

        // Note, we don't restore any question files yet
        // as far as the CONTEXT_MODULE categories still
        // haven't their contexts to be restored to
        // The {@link restore_create_question_files}, executed in the final step
        // step will be in charge of restoring all the question files
    }

        protected function process_question_hint($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        // Detect if the question is created or mapped
        $oldquestionid = $this->get_old_parentid('question');
        $newquestionid = $this->get_new_parentid('question');
        $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;

        // If the question has been created by restore, we need to create its question_answers too
        if ($questioncreated) {
            // Adjust some columns
            $data->questionid = $newquestionid;
            // Insert record
            $newitemid = $DB->insert_record('question_hints', $data);

        // The question existed, we need to map the existing question_hints
        } else {
            // Look in question_hints by hint text matching
            $sql = 'SELECT id
FROM {question_hints}
WHERE questionid = ?
AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
            $params = array($newquestionid, $data->hint);
            $newitemid = $DB->get_field_sql($sql, $params);
            // If we haven't found the newitemid, something has gone really wrong, question in DB
            // is missing hints, exception
            if (!$newitemid) {
                $info = new stdClass();
                $info->filequestionid = $oldquestionid;
                $info->dbquestionid = $newquestionid;
                $info->hint = $data->hint;
                throw new restore_step_exception('error_question_hint_missing_in_db', $info);
            }
        }
        // Create mapping (I'm not sure if this is really needed?)
        $this->set_mapping('question_hint', $oldid, $newitemid);
    }

    protected function after_execute() {
        global $DB;

        // First of all, recode all the created question_categories->parent fields
        $qcats = $DB->get_records('backup_ids_temp', array(
                     'backupid' => $this->get_restoreid(),
                     'itemname' => 'question_category_created'));
        foreach ($qcats as $qcat) {
            $newparent = 0;
            $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
            // Get new parent (mapped or created, so we look in quesiton_category mappings)
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
                                 'backupid' => $this->get_restoreid(),
                                 'itemname' => 'question_category',
                                 'itemid' => $dbcat->parent))) {
                // contextids must match always, as far as we always include complete qbanks, just check it
                $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
                if ($dbcat->contextid == $newparentctxid) {
                    $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
                } else {
                    $newparent = 0; // No ctx match for both cats, no parent relationship
                }
            }
            // Here with $newparent empty, problem with contexts or remapping, set it to top cat
            if (!$newparent) {
                $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
            }
        }

        // Now, recode all the created question->parent fields
        $qs = $DB->get_records('backup_ids_temp', array(
                  'backupid' => $this->get_restoreid(),
                  'itemname' => 'question_created'));
        foreach ($qs as $q) {
            $newparent = 0;
            $dbq = $DB->get_record('question', array('id' => $q->newitemid));
            // Get new parent (mapped or created, so we look in question mappings)
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
                                 'backupid' => $this->get_restoreid(),
                                 'itemname' => 'question',
                                 'itemid' => $dbq->parent))) {
                $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
            }
        }

        // Note, we don't restore any question files yet
        // as far as the CONTEXT_MODULE categories still
        // haven't their contexts to be restored to
        // The {@link restore_create_question_files}, executed in the final step
        // step will be in charge of restoring all the question files
    }
}

/**
* Execution step that will move all the CONTEXT_MODULE question categories
* created at early stages of restore in course context (because modules weren't
* created yet) to their target module (matching by old-new-contextid mapping)
*/
class restore_move_module_questions_categories extends restore_execution_step {

    protected function define_execution() {
        global $DB;

        $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
        foreach ($contexts as $contextid => $contextlevel) {
            // Only if context mapping exists (i.e. the module has been restored)
            if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
                // Update all the qcats having their parentitemid set to the original contextid
                $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
FROM {backup_ids_temp}
WHERE backupid = ?
AND itemname = 'question_category'
AND parentitemid = ?", array($this->get_restoreid(), $contextid));
                foreach ($modulecats as $modulecat) {
                    $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
                    // And set new contextid also in question_category mapping (will be
                    // used by {@link restore_create_question_files} later
                    restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
                }
            }
        }
    }
}

/**
* Execution step that will create all the question/answers/qtype-specific files for the restored
* questions. It must be executed after {@link restore_move_module_questions_categories}
* because only then each question is in its final category and only then the
* context can be determined
*
* TODO: Improve this. Instead of looping over each question, it can be reduced to
* be done by contexts (this will save a huge ammount of queries)
*/
class restore_create_question_files extends restore_execution_step {

    protected function define_execution() {
        global $DB;

        // Let's process only created questions
        $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
FROM {backup_ids_temp} bi
JOIN {question} q ON q.id = bi.newitemid
WHERE bi.backupid = ?
AND bi.itemname = 'question_created'", array($this->get_restoreid()));
        foreach ($questionsrs as $question) {
            // Get question_category mapping, it contains the target context for the question
            if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
                // Something went really wrong, cannot find the question_category for the question
                debugging('Error fetching target context for question', DEBUG_DEVELOPER);
                continue;
            }
            // Calculate source and target contexts
            $oldctxid = $qcatmapping->info->contextid;
            $newctxid = $qcatmapping->parentitemid;

            // Add common question files (question and question_answer ones)
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
                                              $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
                                              $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
                                              $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
                                              $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
                                              $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
                                              $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
                                              $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
                                              $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
            // Add qtype dependent files
            $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
            foreach ($components as $component => $fileareas) {
                foreach ($fileareas as $filearea => $mapping) {
                    // Use itemid only if mapping is question_created
                    $itemid = ($mapping == 'question_created') ? $question->itemid : null;
                    restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
                                                      $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
                }
            }
        }
        $questionsrs->close();
    }
}


/**
* Try to restore aliases and references to external files.
*
* The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
* We expect that all regular (non-alias) files have already been restored. Make sure
* there is no restore step executed after this one that would call send_files_to_pool() again.
*
* You may notice we have hardcoded support for Server files, Legacy course files
* and user Private files here at the moment. This could be eventually replaced with a set of
* callbacks in the future if needed.
*
* @copyright 2012 David Mudrak <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_process_file_aliases_queue extends restore_execution_step {

    /** @var array internal cache for {@link choose_repository() */
    private $cachereposbyid = array();

    /** @var array internal cache for {@link choose_repository() */
    private $cachereposbytype = array();

    /**
* What to do when this step is executed.
*/
    protected function define_execution() {
        global $DB;

        $this->log('processing file aliases queue', backup::LOG_INFO);

        $fs = get_file_storage();

        // Load the queue.
        $rs = $DB->get_recordset('backup_ids_temp',
            array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
            '', 'info');

        // Iterate over aliases in the queue.
        foreach ($rs as $record) {
            $info = unserialize(base64_decode($record->info));

            // Try to pick a repository instance that should serve the alias.
            $repository = $this->choose_repository($info);

            if (is_null($repository)) {
                $this->notify_failure($info, 'unable to find a matching repository instance');
                continue;
            }

            if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
                // Aliases to Server files and Legacy course files may refer to a file
                // contained in the backup file or to some existing file (if we are on the
                // same site).
                try {
                    $reference = file_storage::unpack_reference($info->oldfile->reference);
                } catch (Exception $e) {
                    $this->notify_failure($info, 'invalid reference field format');
                    continue;
                }

                // Let's see if the referred source file was also included in the backup.
                $candidates = $DB->get_recordset('backup_files_temp', array(
                        'backupid' => $this->get_restoreid(),
                        'contextid' => $reference['contextid'],
                        'component' => $reference['component'],
                        'filearea' => $reference['filearea'],
                        'itemid' => $reference['itemid'],
                    ), '', 'info, newcontextid, newitemid');

                $source = null;

                foreach ($candidates as $candidate) {
                    $candidateinfo = unserialize(base64_decode($candidate->info));
                    if ($candidateinfo->filename === $reference['filename']
                            and $candidateinfo->filepath === $reference['filepath']
                            and !is_null($candidate->newcontextid)
                            and !is_null($candidate->newitemid) ) {
                        $source = $candidateinfo;
                        $source->contextid = $candidate->newcontextid;
                        $source->itemid = $candidate->newitemid;
                        break;
                    }
                }
                $candidates->close();

                if ($source) {
                    // We have an alias that refers to another file also included in
                    // the backup. Let us change the reference field so that it refers
                    // to the restored copy of the original file.
                    $reference = file_storage::pack_reference($source);

                    // Send the new alias to the filepool.
                    $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
                    $this->notify_success($info);
                    continue;

                } else {
                    // This is a reference to some moodle file that was not contained in the backup
                    // file. If we are restoring to the same site, keep the reference untouched
                    // and restore the alias as is if the referenced file exists.
                    if ($this->task->is_samesite()) {
                        if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
                                $reference['itemid'], $reference['filepath'], $reference['filename'])) {
                            $reference = file_storage::pack_reference($reference);
                            $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
                            $this->notify_success($info);
                            continue;
                        } else {
                            $this->notify_failure($info, 'referenced file not found');
                            continue;
                        }

                    // If we are at other site, we can't restore this alias.
                    } else {
                        $this->notify_failure($info, 'referenced file not included');
                        continue;
                    }
                }

            } else if ($info->oldfile->repositorytype === 'user') {
                if ($this->task->is_samesite()) {
                    // For aliases to user Private files at the same site, we have a chance to check
                    // if the referenced file still exists.
                    try {
                        $reference = file_storage::unpack_reference($info->oldfile->reference);
                    } catch (Exception $e) {
                        $this->notify_failure($info, 'invalid reference field format');
                        continue;
                    }
                    if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
                            $reference['itemid'], $reference['filepath'], $reference['filename'])) {
                        $reference = file_storage::pack_reference($reference);
                        $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
                        $this->notify_success($info);
                        continue;
                    } else {
                        $this->notify_failure($info, 'referenced file not found');
                        continue;
                    }

                // If we are at other site, we can't restore this alias.
                } else {
                    $this->notify_failure($info, 'restoring at another site');
                    continue;
                }

            } else {
                // This is a reference to some external file such as in boxnet or dropbox.
                // If we are restoring to the same site, keep the reference untouched and
                // restore the alias as is.
                if ($this->task->is_samesite()) {
                    $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
                    $this->notify_success($info);
                    continue;

                // If we are at other site, we can't restore this alias.
                } else {
                    $this->notify_failure($info, 'restoring at another site');
                    continue;
                }
            }
        }
        $rs->close();
    }

    /**
* Choose the repository instance that should handle the alias.
*
* At the same site, we can rely on repository instance id and we just
* check it still exists. On other site, try to find matching Server files or
* Legacy course files repository instance. Return null if no matching
* repository instance can be found.
*
* @param stdClass $info
* @return repository|null
*/
    private function choose_repository(stdClass $info) {
        global $DB, $CFG;
        require_once($CFG->dirroot.'/repository/lib.php');

        if ($this->task->is_samesite()) {
            // We can rely on repository instance id.

            if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
                return $this->cachereposbyid[$info->oldfile->repositoryid];
            }

            $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);

            try {
                $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
                return $this->cachereposbyid[$info->oldfile->repositoryid];
            } catch (Exception $e) {
                $this->cachereposbyid[$info->oldfile->repositoryid] = null;
                return null;
            }

        } else {
            // We can rely on repository type only.

            if (empty($info->oldfile->repositorytype)) {
                return null;
            }

            if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
                return $this->cachereposbytype[$info->oldfile->repositorytype];
            }

            $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);

            // Both Server files and Legacy course files repositories have a single
            // instance at the system context to use. Let us try to find it.
            if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
                $sql = "SELECT ri.id
FROM {repository} r
JOIN {repository_instances} ri ON ri.typeid = r.id
WHERE r.type = ? AND ri.contextid = ?";
                $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
                if (empty($ris)) {
                    return null;
                }
                $repoids = array_keys($ris);
                $repoid = reset($repoids);
                try {
                    $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
                    return $this->cachereposbytype[$info->oldfile->repositorytype];
                } catch (Exception $e) {
                    $this->cachereposbytype[$info->oldfile->repositorytype] = null;
                    return null;
                }
            }

            $this->cachereposbytype[$info->oldfile->repositorytype] = null;
            return null;
        }
    }

    /**
* Let the user know that the given alias was successfully restored
*
* @param stdClass $info
*/
    private function notify_success(stdClass $info) {
        $filedesc = $this->describe_alias($info);
        $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
    }

    /**
* Let the user know that the given alias can't be restored
*
* @param stdClass $info
* @param string $reason detailed reason to be logged
*/
    private function notify_failure(stdClass $info, $reason = '') {
        $filedesc = $this->describe_alias($info);
        if ($reason) {
            $reason = ' ('.$reason.')';
        }
        $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
        $this->add_result_item('file_aliases_restore_failures', $filedesc);
    }

    /**
* Return a human readable description of the alias file
*
* @param stdClass $info
* @return string
*/
    private function describe_alias(stdClass $info) {

        $filedesc = $this->expected_alias_location($info->newfile);

        if (!is_null($info->oldfile->source)) {
            $filedesc .= ' ('.$info->oldfile->source.')';
        }

        return $filedesc;
    }

    /**
* Return the expected location of a file
*
* Please note this may and may not work as a part of URL to pluginfile.php
* (depends on how the given component/filearea deals with the itemid).
*
* @param stdClass $filerecord
* @return string
*/
    private function expected_alias_location($filerecord) {

        $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
        if (!is_null($filerecord->itemid)) {
            $filedesc .= '/'.$filerecord->itemid;
        }
        $filedesc .= $filerecord->filepath.$filerecord->filename;

        return $filedesc;
    }

    /**
* Append a value to the given resultset
*
* @param string $name name of the result containing a list of values
* @param mixed $value value to add as another item in that result
*/
    private function add_result_item($name, $value) {

        $results = $this->task->get_results();

        if (isset($results[$name])) {
            if (!is_array($results[$name])) {
                throw new coding_exception('Unable to append a result item into a non-array structure.');
            }
            $current = $results[$name];
            $current[] = $value;
            $this->task->add_result(array($name => $current));

        } else {
            $this->task->add_result(array($name => array($value)));
        }
    }
}


/**
* Abstract structure step, to be used by all the activities using core questions stuff
* (like the quiz module), to support qtype plugins, states and sessions
*/
abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
    /** @var array question_attempt->id to qtype. */
    protected $qtypes = array();
    /** @var array question_attempt->id to questionid. */
    protected $newquestionids = array();

    /**
* Attach below $element (usually attempts) the needed restore_path_elements
* to restore question_usages and all they contain.
*
* If you use the $nameprefix parameter, then you will need to implement some
* extra methods in your class, like
*
* protected function process_{$nameprefix}_question_attempt($data) {
* $this->process_question_attempt($data);
* }
*
* You need three methods like this, for question_usage, question_attempt and
* question_attempt_step.
*
* @param restore_path_element $element the parent element that the usages are stored inside.
* @param array $paths the paths array that is being built.
* @param string $nameprefix should match the prefix passed to the corresponding
* backup_questions_activity_structure_step::add_question_usages call.
*/
    protected function add_question_usages($element, &$paths, $nameprefix = '') {
        // Check $element is restore_path_element
        if (! $element instanceof restore_path_element) {
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
        }

        // Check $paths is one array
        if (!is_array($paths)) {
            throw new restore_step_exception('paths_must_be_array', $paths);
        }
        $paths[] = new restore_path_element($nameprefix . 'question_usage',
                $element->get_path() . "/{$nameprefix}question_usage");
        $paths[] = new restore_path_element($nameprefix . 'question_attempt',
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
                true);
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
    }

    /**
* Process question_usages
*/
    protected function process_question_usage($data, $nameprefix = '') {
        global $DB;

        // Clear our caches.
        $this->qtypes = array();
        $this->newquestionids = array();

        $data = (object)$data;
        $oldid = $data->id;

        $oldcontextid = $this->get_task()->get_old_contextid();
        $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());

        // Everything ready, insert (no mapping needed)
        $newitemid = $DB->insert_record('question_usages', $data);

        $this->inform_new_usage_id($newitemid);

        $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
    }

    /**
* When process_question_usage creates the new usage, it calls this method
* to let the activity link to the new usage. For example, the quiz uses
* this method to set quiz_attempts.uniqueid to the new usage id.
* @param integer $newusageid
*/
    abstract protected function inform_new_usage_id($newusageid);

    /**
* Process question_attempts
*/
    protected function process_question_attempt($data, $nameprefix = '') {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;
        $question = $this->get_mapping('question', $data->questionid);

        $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
        $data->questionid = $question->newitemid;
        $data->timemodified = $this->apply_date_offset($data->timemodified);

        $newitemid = $DB->insert_record('question_attempts', $data);

        $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
        $this->qtypes[$newitemid] = $question->info->qtype;
        $this->newquestionids[$newitemid] = $data->questionid;
    }

    /**
* Process question_attempt_steps
*/
    protected function process_question_attempt_step($data, $nameprefix = '') {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;

        // Pull out the response data.
        $response = array();
        if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {