File: restorelib.php

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

    }

    //This function checks if moodle.xml seems to be a valid xml file
    //(exists, has an xml header and a course main tag
    function restore_check_moodle_file ($file) {
    
        $status = true;

        //Check if it exists
        if ($status = is_file($file)) {
            //Open it and read the first 200 bytes (chars)
            $handle = fopen ($file, "r");
            $first_chars = fread($handle,200);
            $status = fclose ($handle);
            //Chek if it has the requires strings
            if ($status) {
                $status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                if ($status !== false) {
                    $status = strpos($first_chars,"<MOODLE_BACKUP>");
                }
            }
        }   

        return $status;  
    }   

    //This function iterates over all modules in backup file, searching for a
    //MODNAME_refresh_events() to execute. Perhaps it should ve moved to central Moodle...
    function restore_refresh_events($restore) {
   
        global $CFG;
        $status = true;
        
        //Take all modules in backup
        $modules = $restore->mods;
        //Iterate
        foreach($modules as $name => $module) {
            //Only if the module is being restored
            if ($module->restore == 1) {
                //Include module library
                include_once("$CFG->dirroot/mod/$name/lib.php");
                //If module_refresh_events exists
                $function_name = $name."_refresh_events";
                if (function_exists($function_name)) {
                    $status = $function_name($restore->course_id);
                }
            }
        }
        return $status;
    }

    //This function makes all the necessary calls to xxxx_decode_content_links_caller()
    //function in each module, passing them the desired contents to be decoded
    //from backup format to destination site/course in order to mantain inter-activities
    //working in the backup/restore process
    function restore_decode_content_links($restore) {
        global $CFG;

        $status = true;

        if (!defined('RESTORE_SILENTLY')) {
            echo "<ul>";
        }
        foreach ($restore->mods as $name => $info) {
            //If the module is being restored
            if ($info->restore == 1) {
                //Check if the xxxx_decode_content_links_caller exists
	            include_once("$CFG->dirroot/mod/$name/restorelib.php");
                $function_name = $name."_decode_content_links_caller";
                if (function_exists($function_name)) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
                        echo '</li>';
                    }
                    $status = $function_name($restore);
                }
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</ul>";
        }
        
        // TODO: process all html text also in blocks too
        
        return $status;
    }
    
    //This function is called from all xxxx_decode_content_links_caller(),
    //its task is to ask all modules (maybe other linkable objects) to restore
    //links to them.
    function restore_decode_content_links_worker($content,$restore) {
        foreach($restore->mods as $name => $info) {
            $function_name = $name."_decode_content_links";
            if (function_exists($function_name)) {
                $content = $function_name($content,$restore);
            }
        }
        return $content;
    }

    //This function converts all the wiki texts in the restored course
    //to the Markdown format. Used only for backup files prior 2005041100.
    //It calls every module xxxx_convert_wiki2markdown function
    function restore_convert_wiki2markdown($restore) {

        $status = true;

        if (!defined('RESTORE_SILENTLY')) {
            echo "<ul>";
        }
        foreach ($restore->mods as $name => $info) {
            //If the module is being restored
            if ($info->restore == 1) {
                //Check if the xxxx_restore_wiki2markdown exists
                $function_name = $name."_restore_wiki2markdown";
                if (function_exists($function_name)) {
                    $status = $function_name($restore);
                    if (!defined('RESTORE_SILENTLY')) {
                        echo "<li>".get_string("modulenameplural",$name);
                        echo '</li>';
                    }
                }
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</ul>";
        }
        return $status;
    }

    //This function receives a wiki text in the restore process and
    //return it with every link to modules " modulename:moduleid"
    //converted if possible. See the space before modulename!!
    function restore_decode_wiki_content($content,$restore) {

        global $CFG;
        
        $result = $content;
        
        $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
        //We look for it
        preg_match_all($searchstring,$content,$foundset);
        //If found, then we are going to look for its new id (in backup tables)
        if ($foundset[0]) { 
            //print_object($foundset);                                     //Debug
            //Iterate over foundset[2]. They are the old_ids               
            foreach($foundset[2] as $old_id) {
                //We get the needed variables here (course id)
                $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id);
                //Personalize the searchstring
                $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
                //If it is a link to this course, update the link to its new location
                if($rec->new_id) {
                    //Now replace it
                    $result= preg_replace($searchstring,' $1:'.$rec->new_id.'($2)',$result);
                } else {
                    //It's a foreign link so redirect it to its original URL
                    $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
                }
            }
        }
        return $result;
    }


    //This function read the xml file and store it data from the info zone in an object
    function restore_read_xml_info ($xml_file) {

        //We call the main read_xml function, with todo = INFO
        $info = restore_read_xml ($xml_file,"INFO",false);

        return $info;
    }

    //This function read the xml file and store it data from the course header zone in an object  
    function restore_read_xml_course_header ($xml_file) {

        //We call the main read_xml function, with todo = COURSE_HEADER
        $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);

        return $info;
    }

    //This function read the xml file and store its data from the blocks in a object
    function restore_read_xml_blocks ($xml_file) {

        //We call the main read_xml function, with todo = BLOCKS
        $info = restore_read_xml ($xml_file,'BLOCKS',false);

        return $info;
    }

    //This function read the xml file and store its data from the sections in a object
    function restore_read_xml_sections ($xml_file) {

        //We call the main read_xml function, with todo = SECTIONS
        $info = restore_read_xml ($xml_file,"SECTIONS",false);

        return $info;
    }
    
    //This function read the xml file and store its data from the metacourse in a object
    function restore_read_xml_metacourse ($xml_file) {

        //We call the main read_xml function, with todo = METACOURSE
        $info = restore_read_xml ($xml_file,"METACOURSE",false);

        return $info;
    }

    //This function read the xml file and store its data from the gradebook in a object
    function restore_read_xml_gradebook ($restore, $xml_file) {

        //We call the main read_xml function, with todo = GRADEBOOK
        $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
    
        return $info;
    }

    //This function read the xml file and store its data from the users in 
    //backup_ids->info db (and user's id in $info)
    function restore_read_xml_users ($restore,$xml_file) {

        //We call the main read_xml function, with todo = USERS
        $info = restore_read_xml ($xml_file,"USERS",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the messages in
    //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
    function restore_read_xml_messages ($restore,$xml_file) {

        //We call the main read_xml function, with todo = MESSAGES
        $info = restore_read_xml ($xml_file,"MESSAGES",$restore);

        return $info;
    }


    //This function read the xml file and store its data from the questions in
    //backup_ids->info db (and category's id in $info)
    function restore_read_xml_questions ($restore,$xml_file) {

        //We call the main read_xml function, with todo = QUESTIONS
        $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the scales in
    //backup_ids->info db (and scale's id in $info)
    function restore_read_xml_scales ($restore,$xml_file) {

        //We call the main read_xml function, with todo = SCALES
        $info = restore_read_xml ($xml_file,"SCALES",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the groups in
    //backup_ids->info db (and group's id in $info)
    function restore_read_xml_groups ($restore,$xml_file) {

        //We call the main read_xml function, with todo = GROUPS
        $info = restore_read_xml ($xml_file,"GROUPS",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the events (course) in
    //backup_ids->info db (and event's id in $info)
    function restore_read_xml_events ($restore,$xml_file) {

        //We call the main read_xml function, with todo = EVENTS
        $info = restore_read_xml ($xml_file,"EVENTS",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the modules in
    //backup_ids->info
    function restore_read_xml_modules ($restore,$xml_file) {

        //We call the main read_xml function, with todo = MODULES
        $info = restore_read_xml ($xml_file,"MODULES",$restore);

        return $info;
    }

    //This function read the xml file and store its data from the logs in
    //backup_ids->info
    function restore_read_xml_logs ($restore,$xml_file) {

        //We call the main read_xml function, with todo = LOGS
        $info = restore_read_xml ($xml_file,"LOGS",$restore);

        return $info;
    }

    //This function prints the contents from the info parammeter passed
    function restore_print_info ($info) {

        global $CFG;

        $status = true;
        if ($info) {
            //This is tha align to every ingo table      
            $table->align = array ("right","left");
            //This is the nowrap clause 
            $table->wrap = array ("","nowrap");
            //The width
            $table->width = "70%";
            //Put interesting info in table
            //The backup original name
            $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
            $tab[0][1] = $info->backup_name;
            //The moodle version
            $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
            $tab[1][1] = $info->backup_moodle_release." (".$info->backup_moodle_version.")";
            //The backup version
            $tab[2][0] = "<b>".get_string("backupversion").":</b>";
            $tab[2][1] = $info->backup_backup_release." (".$info->backup_backup_version.")";
            //The backup date
            $tab[3][0] = "<b>".get_string("backupdate").":</b>";
            $tab[3][1] = userdate($info->backup_date);
            //Print title
            print_heading(get_string("backup").":");
            $table->data = $tab;
            //Print backup general info
            print_table($table);

            if ($info->backup_backup_version <= 2005070500 && !empty($CFG->unicodedb)) {
                 notify(get_string('backupnonisowarning'));  // Message informing that this backup may not work!
            }

            //Now backup contents in another table
            $tab = array();
            //First mods info
            $mods = $info->mods;
            $elem = 0;
            foreach ($mods as $key => $mod) {
                $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
                if ($mod->backup == "false") {
                    $tab[$elem][1] = get_string("notincluded");
                } else {
                    if ($mod->userinfo == "true") {
                        $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
                    } else {
                        $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
                    }
                    if (is_array($mod->instances) && count($mod->instances)) {
                        foreach ($mod->instances as $instance) {
                            if ($instance->backup) {
                                $elem++;
                                $tab[$elem][0] = $instance->name;
                                if ($instance->userinfo == 'true') {
                                    $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
                                } else {
                                    $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
                                }
                            }
                        }
                    }
                }
                $elem++;
            }
            //Metacourse info
            $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
            if ($info->backup_metacourse == "true") {
                $tab[$elem][1] = get_string("yes");
            } else {
                $tab[$elem][1] = get_string("no");
            }
            $elem++;
            //Users info
            $tab[$elem][0] = "<b>".get_string("users").":</b>";
            $tab[$elem][1] = get_string($info->backup_users);
            $elem++;
            //Logs info
            $tab[$elem][0] = "<b>".get_string("logs").":</b>";
            if ($info->backup_logs == "true") {
                $tab[$elem][1] = get_string("yes");
            } else {
                $tab[$elem][1] = get_string("no");
            }
            $elem++;
            //User Files info
            $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
            if ($info->backup_user_files == "true") {
                $tab[$elem][1] = get_string("yes");
            } else {
                $tab[$elem][1] = get_string("no");
            }
            $elem++;
            //Course Files info
            $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
            if ($info->backup_course_files == "true") {
                $tab[$elem][1] = get_string("yes");
            } else {
                $tab[$elem][1] = get_string("no");
            }
            $elem++;
            //Messages info (only showed if present)
            if ($info->backup_messages == 'true') {
                $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
                $tab[$elem][1] = get_string('yes');
                $elem++;
            } else {
                //Do nothing
            }
            $table->data = $tab;
            //Print title
            print_heading(get_string("backupdetails").":");
            //Print backup general info
            print_table($table);
        } else {
            $status = false;
        }

        return $status;
    }

    //This function prints the contents from the course_header parammeter passed
    function restore_print_course_header ($course_header) {

        $status = true;
        if ($course_header) {
            //This is tha align to every ingo table
            $table->align = array ("right","left");
            //The width
            $table->width = "70%";
            //Put interesting course header in table
            //The course name
            $tab[0][0] = "<b>".get_string("name").":</b>";
            $tab[0][1] = $course_header->course_fullname." (".$course_header->course_shortname.")";
            //The course summary
            $tab[1][0] = "<b>".get_string("summary").":</b>";
            $tab[1][1] = $course_header->course_summary;
            $table->data = $tab;
            //Print title
            print_heading(get_string("course").":");
            //Print backup course header info
            print_table($table);
        } else {
            $status = false; 
        }
        return $status;
    }

    //This function create a new course record.
    //When finished, course_header contains the id of the new course
    function restore_create_new_course($restore,&$course_header) {

        global $CFG;
 
        $status = true;

        $fullname = $course_header->course_fullname;
        $shortname = $course_header->course_shortname;
        $currentfullname = "";
        $currentshortname = "";
        $counter = 0;
        //Iteratere while the name exists
        do {
            if ($counter) {
                $suffixfull = " ".get_string("copyasnoun")." ".$counter;
                $suffixshort = "_".$counter;
            } else {
                $suffixfull = "";
                $suffixshort = "";
            }
            $currentfullname = $fullname.$suffixfull;
            // Limit the size of shortname - database column accepts <= 15 chars
            $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
            $coursefull  = get_record("course","fullname",addslashes($currentfullname));
            $courseshort = get_record("course","shortname",addslashes($currentshortname));
            $counter++;
        } while ($coursefull || $courseshort);

        //New name = currentname
        $course_header->course_fullname = $currentfullname;
        $course_header->course_shortname = $currentshortname;
        
        //Now calculate the category
        $category = get_record("course_categories","id",$course_header->category->id,
                                                   "name",addslashes($course_header->category->name));
        //If no exists, try by name only
        if (!$category) {
            $category = get_record("course_categories","name",addslashes($course_header->category->name));
        }
        //If no exists, get category id 1
        if (!$category) {
            $category = get_record("course_categories","id","1");
        }
        //If category 1 doesn'exists, lets create the course category (get it from backup file)
        if (!$category) {
            $ins_category->name = addslashes($course_header->category->name);
            $ins_category->parent = 0;
            $ins_category->sortorder = 0;
            $ins_category->coursecount = 0;
            $ins_category->visible = 0;            //To avoid interferences with the rest of the site
            $ins_category->timemodified = time();
            $newid = insert_record("course_categories",$ins_category);
            $category->id = $newid;
            $category->name = $course_header->category->name;
        }
        //If exists, put new category id
        if ($category) {
            $course_header->category->id = $category->id;
            $course_header->category->name = $category->name;
        //Error, cannot locate category
        } else {
            $course_header->category->id = 0;
            $course_header->category->name = get_string("unknowncategory");
            $status = false;
        }

        //Create the course_object
        if ($status) {
            $course->category = addslashes($course_header->category->id);
            $course->password = addslashes($course_header->course_password);
            $course->fullname = addslashes($course_header->course_fullname);
            $course->shortname = addslashes($course_header->course_shortname);
            $course->idnumber = addslashes($course_header->course_idnumber);
            $course->idnumber = ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
            $course->summary = restore_decode_absolute_links(addslashes($course_header->course_summary));
            $course->format = addslashes($course_header->course_format);
            $course->showgrades = addslashes($course_header->course_showgrades);
            $course->newsitems = addslashes($course_header->course_newsitems);
            $course->teacher = addslashes($course_header->course_teacher);
            $course->teachers = addslashes($course_header->course_teachers);
            $course->student = addslashes($course_header->course_student);
            $course->students = addslashes($course_header->course_students);
            $course->guest = addslashes($course_header->course_guest);
            $course->startdate = addslashes($course_header->course_startdate);
            $course->enrolperiod = addslashes($course_header->course_enrolperiod);
            $course->numsections = addslashes($course_header->course_numsections);
            //$course->showrecent = addslashes($course_header->course_showrecent);   INFO: This is out in 1.3
            $course->maxbytes = addslashes($course_header->course_maxbytes);
            $course->showreports = addslashes($course_header->course_showreports);
            if (isset($course_header->course_groupmode)) {
                $course->groupmode = addslashes($course_header->course_groupmode);
            }
            if (isset($course_header->course_groupmodeforce)) {
                $course->groupmodeforce = addslashes($course_header->course_groupmodeforce);
            }
            $course->lang = addslashes($course_header->course_lang);
            $course->theme = addslashes($course_header->course_theme);
            $course->cost = addslashes($course_header->course_cost);
            $course->currency = addslashes($course_header->course_currency);
            $course->marker = addslashes($course_header->course_marker);
            $course->visible = addslashes($course_header->course_visible);
            $course->hiddensections = addslashes($course_header->course_hiddensections);
            $course->timecreated = addslashes($course_header->course_timecreated);
            $course->timemodified = addslashes($course_header->course_timemodified);
            $course->metacourse = addslashes($course_header->course_metacourse);
            //Calculate sortorder field
            $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
                                       FROM ' . $CFG->prefix . 'course
                                       WHERE category=' . $course->category);
            if (!empty($sortmax->max)) {
                $course->sortorder = $sortmax->max + 1;
                unset($sortmax);
            } else {
                $course->sortorder = 100;
            }

            //Now, recode some languages (Moodle 1.5)
            if ($course->lang == 'ma_nt') {
                $course->lang = 'mi_nt';
            }

            //Disable course->metacourse if avoided in restore config
            if (!$restore->metacourse) {
                $course->metacourse = 0;
            }

            //Check if the theme exists in destination server
            $themes = get_list_of_themes();
            if (!in_array($course->theme, $themes)) {
                $course->theme = '';
            } 

            //Now insert the record
            $newid = insert_record("course",$course);
            if ($newid) {
                //save old and new course id
                backup_putid ($restore->backup_unique_code,"course",$course_header->course_id,$newid);
                //Replace old course_id in course_header
                $course_header->course_id = $newid;
            } else {
                $status = false;
            }
        }

        return $status;
    }

   /**
    * Returns the best question category (id) found to restore one
    * question category from a backup file. Works by stamp (since Moodle 1.1)
    * or by name (for older versions).
    *
    * @param object  $cat      the question_categories record to be searched
    * @param integer $courseid the course where we are restoring
    * @return integer the id of a existing question_category or 0 (not found)
    */
    function restore_get_best_question_category($cat, $courseid) {
        
        $found = 0;

        //Decide how to work (by stamp or name)
        if ($cat->stamp) {
            $searchfield = 'stamp';
            $searchvalue = $cat->stamp;
        } else {
            $searchfield = 'name';
            $searchvalue = $cat->name;
        }
        
        //First shot. Try to get the category from the course being restored
        if ($fcat = get_record('question_categories','course',$courseid,$searchfield,$searchvalue)) {
            $found = $fcat->id;
        //Second shot. Try to obtain any concordant category and check its publish status and editing rights
        } else if ($fcats = get_records('question_categories', $searchfield, $searchvalue, 'id', 'id, publish, course')) {
            foreach ($fcats as $fcat) {
                if ($fcat->publish == 1 && isteacheredit($fcat->course)) {
                    $found = $fcat->id;
                    break;
                }
            }
        }

        return $found;
    }

    //This function creates all the block stuff when restoring courses
    //It calls selectively to  restore_create_block_instances() for 1.5 
    //and above backups. Upwards compatible with old blocks.
    function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {

        $status = true;

        delete_records('block_instance', 'pageid', $restore->course_id, 'pagetype', PAGE_COURSE_VIEW);
        if (empty($backup_block_format)) {     // This is a backup from Moodle < 1.5
            if (empty($blockinfo)) {
                // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
                $newpage = page_create_object(PAGE_COURSE_VIEW, $restore->course_id);
                blocks_repopulate_page($newpage);
            } else {
                // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
                $blockrecords = get_records_select('block', '', '', 'name, id');
                $temp_blocks_l = array();
                $temp_blocks_r = array();
                @list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
                $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r));
                foreach($temp_blocks as $blockposition => $blocks) {
                    $blockweight = 0;
                    foreach($blocks as $blockname) { 
                        if(!isset($blockrecords[$blockname])) {
                            // We don't know anything about this block!
                            continue;
                        }
                        $blockinstance = new stdClass;
                        // Remove any - prefix before doing the name-to-id mapping
                        if(substr($blockname, 0, 1) == '-') {
                            $blockname = substr($blockname, 1);
                            $blockinstance->visible = 0;
                        } else {
                            $blockinstance->visible = 1;
                        }
                        $blockinstance->blockid  = $blockrecords[$blockname]->id;
                        $blockinstance->pageid   = $restore->course_id;
                        $blockinstance->pagetype = PAGE_COURSE_VIEW;
                        $blockinstance->position = $blockposition;
                        $blockinstance->weight   = $blockweight;
                        if(!$status = insert_record('block_instance', $blockinstance)) {
                            $status = false;
                        }
                        ++$blockweight;
                    }
                }
            }
        } else if($backup_block_format == 'instances') {
            $status = restore_create_block_instances($restore,$xml_file);
        }

        return $status;

    } 

    //This function creates all the block_instances from xml when restoring in a
    //new course
    function restore_create_block_instances($restore,$xml_file) {

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            $info = restore_read_xml_blocks($xml_file);
        }

        if(empty($info->instances)) {
            return $status;
        }

        // First of all, iterate over the blocks to see which distinct pages we have
        // in our hands and arrange the blocks accordingly.
        $pageinstances = array();
        foreach($info->instances as $instance) {

            //pagetype and pageid black magic, we have to handle the case of blocks for the
            //course, blocks from other pages in that course etc etc etc.

            if($instance->pagetype == PAGE_COURSE_VIEW) {
                // This one's easy...
                $instance->pageid  = $restore->course_id;
            }
            else {
                $parts = explode('-', $instance->pagetype);
                if($parts[0] == 'mod') {
                    if(!$restore->mods[$parts[1]]->restore) {
                        continue;
                    }
                    $getid = backup_getid($restore->backup_unique_code, $parts[1], $instance->pageid);
                    $instance->pageid = $getid->new_id;
                }
                else {
                    // Not invented here ;-)
                    continue;
                }
            }

            if(!isset($pageinstances[$instance->pagetype])) {
                $pageinstances[$instance->pagetype] = array();
            }
            if(!isset($pageinstances[$instance->pagetype][$instance->pageid])) {
                $pageinstances[$instance->pagetype][$instance->pageid] = array();
            }

            $pageinstances[$instance->pagetype][$instance->pageid][] = $instance;
        }

        $blocks = get_records_select('block', '', '', 'name, id, multiple');

        // For each type of page we have restored
        foreach($pageinstances as $thistypeinstances) {

            // For each page id of that type
            foreach($thistypeinstances as $thisidinstances) {

                $addedblocks = array();
                $maxweights  = array();

                // For each block instance in that page
                foreach($thisidinstances as $instance) {

                    if(!isset($blocks[$instance->name])) {
                        //We are trying to restore a block we don't have...
                        continue;
                    }
    
                    //If we have already added this block once and multiples aren't allowed, disregard it
                    if(!$blocks[$instance->name]->multiple && isset($addedblocks[$instance->name])) {
                        continue;
                    }

                    //If its the first block we add to a new position, start weight counter equal to 0.
                    if(empty($maxweights[$instance->position])) {
                        $maxweights[$instance->position] = 0;
                    }
    
                    //If the instance weight is greater than the weight counter (we skipped some earlier
                    //blocks most probably), bring it back in line.
                    if($instance->weight > $maxweights[$instance->position]) {
                        $instance->weight = $maxweights[$instance->position];
                    }

                    //Add this instance
                    $instance->blockid = $blocks[$instance->name]->id;
                    
                    if(!insert_record('block_instance', $instance)) {
                        $status = false;
                        break;
                    }
    
                    //Now we can increment the weight counter
                    ++$maxweights[$instance->position];
    
                    //Keep track of block types we have already added
                    $addedblocks[$instance->name] = true;

                }
            }
        }

        return $status;
    }

    //This function creates all the course_sections and course_modules from xml
    //when restoring in a new course or simply checks sections and create records
    //in backup_ids when restoring in a existing course
    function restore_create_sections($restore,$xml_file) {

        global $CFG,$db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            $info = restore_read_xml_sections($xml_file);
        }
        //Put the info in the DB, recoding ids and saving the in backup tables

        $sequence = "";

        if ($info) {
            //For each, section, save it to db
            foreach ($info->sections as $key => $sect) {
                $sequence = "";
                $section->course = $restore->course_id;
                $section->section = $sect->number;
                $section->summary = restore_decode_absolute_links(addslashes($sect->summary));
                $section->visible = $sect->visible;
                $section->sequence = "";
                //Now calculate the section's newid
                $newid = 0;
                if ($restore->restoreto == 2) {
                //Save it to db (only if restoring to new course)
                    $newid = insert_record("course_sections",$section);
                } else {
                    //Get section id when restoring in existing course
                    $rec = get_record("course_sections","course",$restore->course_id,
                                                        "section",$section->section);
                    //If that section doesn't exist, get section 0 (every mod will be
                    //asigned there
                    if(!$rec) {
                        $rec = get_record("course_sections","course",$restore->course_id,
                                                            "section","0");
                    }
                    //New check. If section 0 doesn't exist, insert it here !!
                    //Teorically this never should happen but, in practice, some users
                    //have reported this issue. 
                    if(!$rec) {
                        $zero_sec->course = $restore->course_id;
                        $zero_sec->section = 0;
                        $zero_sec->summary = "";
                        $zero_sec->sequence = "";
                        $newid = insert_record("course_sections",$zero_sec);
                        $rec->id = $newid;
                        $rec->sequence = "";
                    }
                    $newid = $rec->id;
                    $sequence = $rec->sequence;
                }
                if ($newid) {
                    //save old and new section id
                    backup_putid ($restore->backup_unique_code,"course_sections",$key,$newid);
                } else {
                    $status = false;
                }
                //If all is OK, go with associated mods
                if ($status) {
                    //If we have mods in the section
                    if (!empty($sect->mods)) {
                        //For each mod inside section
                        foreach ($sect->mods as $keym => $mod) {
                            //Check if we've to restore this module (and instance) 
                            if ($restore->mods[$mod->type]->restore) {
                                if (!is_array($restore->mods[$mod->type]->instances)  // we don't care about per instance
                                    || (array_key_exists($mod->instance,$restore->mods[$mod->type]->instances) 
                                        && !empty($restore->mods[$mod->type]->instances[$mod->instance]->restore))) {
                                    //Get the module id from modules
                                    $module = get_record("modules","name",$mod->type);
                                    if ($module) {
                                        $course_module->course = $restore->course_id;
                                        $course_module->module = $module->id;
                                        $course_module->section = $newid;
                                        $course_module->added = $mod->added;
                                        $course_module->score = $mod->score;
                                        $course_module->indent = $mod->indent;
                                        $course_module->visible = $mod->visible;
                                        if (isset($mod->groupmode)) {
                                            $course_module->groupmode = $mod->groupmode;
                                        }
                                        $course_module->instance = 0;
                                        //NOTE: The instance (new) is calculated and updated in db in the
                                        //      final step of the restore. We don't know it yet.
                                        //print_object($course_module);					//Debug
                                        //Save it to db
                                        $newidmod = insert_record("course_modules",$course_module); 
                                        if ($newidmod) {
                                            //save old and new module id
                                            //In the info field, we save the original instance of the module
                                            //to use it later
                                            backup_putid ($restore->backup_unique_code,"course_modules",
                                                          $keym,$newidmod,$mod->instance);
                                        } else {
                                            $status = false;
                                        }
                                        //Now, calculate the sequence field
                                        if ($status) {
                                            if ($sequence) {
                                                $sequence .= ",".$newidmod;
                                            } else {
                                                $sequence = $newidmod;
                                            }
                                        }
                                    } else {
                                        $status = false;
                                    }
                                }
                            }
                        }
                    }
                }
                //If all is OK, update sequence field in course_sections
                if ($status) {
                    if (isset($sequence)) {
                        $update_rec->id = $newid;
                        $update_rec->sequence = $sequence;
                        $status = update_record("course_sections",$update_rec);
                    }
                }
            }
        } else {
            $status = false;
        }
        return $status;
    }

    //This function creates all the metacourse data from xml, notifying 
    //about each incidence
    function restore_create_metacourse($restore,$xml_file) {

        global $CFG,$db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //Load data from XML to info
            $info = restore_read_xml_metacourse($xml_file);
        }

        //Process info about metacourse
        if ($status and $info) {
            //Process child records
            if (!empty($info->childs)) {
                foreach ($info->childs as $child) {
                    $dbcourse = false;
                    $dbmetacourse = false;
                    //Check if child course exists in destination server
                    //(by id in the same server or by idnumber and shortname in other server)
                    if ($restore->original_wwwroot == $CFG->wwwroot) {
                        //Same server, lets see by id
                        $dbcourse = get_record('course','id',$child->id);
                    } else {
                        //Different server, lets see by idnumber and shortname, and only ONE record
                        $dbcount = count_records('course','idnumber',$child->idnumber,'shortname',$child->shortname);
                        if ($dbcount == 1) {
                            $dbcourse = get_record('course','idnumber',$child->idnumber,'shortname',$child->shortname);
                        }
                    }
                    //If child course has been found, insert data
                    if ($dbcourse) {
                        $dbmetacourse->child_course = $dbcourse->id;
                        $dbmetacourse->parent_course = $restore->course_id;
                        $status = insert_record ('course_meta',$dbmetacourse);
                    } else {
                        //Child course not found, notice!
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id.'/'.$child->idnumber.'/'.$child->shortname.')</li></ul>';
                        }
                    }
                }
                //Now, recreate student enrolments...
                sync_metacourse($restore->course_id);
            }
            //Process parent records
            if (!empty($info->parents)) {
                foreach ($info->parents as $parent) {
                    $dbcourse = false;
                    $dbmetacourse = false;
                    //Check if parent course exists in destination server
                    //(by id in the same server or by idnumber and shortname in other server)
                    if ($restore->original_wwwroot == $CFG->wwwroot) {
                        //Same server, lets see by id
                        $dbcourse = get_record('course','id',$parent->id);
                    } else {
                        //Different server, lets see by idnumber and shortname, and only ONE record
                        $dbcount = count_records('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
                        if ($dbcount == 1) {
                            $dbcourse = get_record('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
                        }
                    }
                    //If parent course has been found, insert data if it is a metacourse
                    if ($dbcourse) {
                        if ($dbcourse->metacourse) {
                            $dbmetacourse->parent_course = $dbcourse->id;
                            $dbmetacourse->child_course = $restore->course_id;
                            $status = insert_record ('course_meta',$dbmetacourse);
                            //Now, recreate student enrolments in parent course
                            sync_metacourse($dbcourse->id);
                        } else {
                            //Parent course isn't metacourse, notice!
                            if (!defined('RESTORE_SILENTLY')) {
                                echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
                            }
                        }
                    } else {
                        //Parent course not found, notice!
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
                        }
                    }
                }
            }

        }
        return $status;
    }
    
    //This function creates all the gradebook data from xml, notifying 
    //about each incidence
    function restore_create_gradebook($restore,$xml_file) {

        global $CFG,$db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //info will contain the number of record to process
            $info = restore_read_xml_gradebook($restore, $xml_file);

        //If we have info, then process preferences, letters & categories
            if ($info > 0) {
                //Count how many we have
                $preferencescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_preferences');
                $letterscount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_letter');
                $categoriescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_category');

                if ($preferencescount || $letterscount || $categoriescount) {
                    //Start ul
                    if (!defined('RESTORE_SILENTLY')) {
                        echo '<ul>';
                    }
                    //Number of records to get in every chunk
                    $recordset_size = 2;
                    //Flag to mark if we must continue
                    $continue = true;

                    //If there aren't preferences, stop
                    if (!$preferencescount) {
                        $continue = false;
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('backupwithoutgradebook','grade').'</li>';
                        }
                    }

                    //If we are restoring to an existing course and it has advanced disabled, stop
                    if ($restore->restoreto != 2) {
                        //Fetch the 'use_advanced' preferences (id = 0)
                        if ($pref_rec = get_record('grade_preferences','courseid',$restore->course_id,'preference',0)) {
                            if ($pref_rec->value == 0) {
                                $continue = false;
                                if (!defined('RESTORE_SILENTLY')) {
                                    echo '<li>'.get_string('respectingcurrentdata','grade').'</li>';
                                }
                            }
                        }
                    }

                    //Process preferences
                    if ($preferencescount && $continue) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('preferences','grades').'</li>';
                        }
                        $counter = 0;
                        while ($counter < $preferencescount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'grade_preferences' AND backup_code = '$restore->backup_unique_code'",
                                                       "old_id",
                                                       "old_id, old_id",
                                                       $counter,
                                                       $recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,'grade_preferences',$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the GRADE_PREFERENCES record structure
                                        $dbrec->courseid   = $restore->course_id;
                                        $dbrec->preference = backup_todb($info['GRADE_PREFERENCE']['#']['PREFERENCE']['0']['#']);
                                        $dbrec->value      = backup_todb($info['GRADE_PREFERENCE']['#']['VALUE']['0']['#']);
   
                                        //Structure is equal to db, insert record
                                        //if the preference doesn't exist
                                        if (!$prerec = get_record('grade_preferences','courseid',$dbrec->courseid,'preference',$dbrec->preference)) {
                                            $status = insert_record('grade_preferences',$dbrec);
                                        }
                                    }
                                    //Increment counters
                                    $counter++;
                                    //Do some output
                                    if ($counter % 1 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($counter % 20 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }

                    //Process letters
                    //If destination course has letters, skip restoring letters
                    $hasletters = get_records('grade_letter', 'courseid', $restore->course_id);

                    if ($letterscount && $continue && !$hasletters) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('letters','grades').'</li>';
                        }
                        $counter = 0;
                        while ($counter < $letterscount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'grade_letter' AND backup_code = '$restore->backup_unique_code'",
                                                       "old_id",
                                                       "old_id, old_id",
                                                       $counter,
                                                       $recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,'grade_letter',$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the GRADE_LETTER record structure
                                        $dbrec->courseid   = $restore->course_id;
                                        $dbrec->letter     = backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
                                        $dbrec->grade_high = backup_todb($info['GRADE_LETTER']['#']['GRADE_HIGH']['0']['#']);
                                        $dbrec->grade_low  = backup_todb($info['GRADE_LETTER']['#']['GRADE_LOW']['0']['#']);

                                        //Structure is equal to db, insert record
                                        $status = insert_record('grade_letter',$dbrec);
                                    }
                                    //Increment counters
                                    $counter++;
                                    //Do some output
                                    if ($counter % 1 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($counter % 20 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }

                    //Process categories
                    if ($categoriescount && $continue) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('categories','grades').'</li>';
                        }
                        $counter = 0;
                        $countercat = 0;
                        while ($countercat < $categoriescount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'grade_category' AND backup_code = '$restore->backup_unique_code'",
                                                       "old_id",
                                                       "old_id, old_id",
                                                       $countercat,
                                                       $recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,'grade_category',$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the GRADE_CATEGORY record structure
                                        $dbrec->courseid     = $restore->course_id;
                                        $dbrec->name         = backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#']);
                                        $dbrec->drop_x_lowest= backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#']);
                                        $dbrec->bonus_points = backup_todb($info['GRADE_CATEGORY']['#']['BONUS_POINTS']['0']['#']);
                                        $dbrec->hidden       = backup_todb($info['GRADE_CATEGORY']['#']['HIDDEN']['0']['#']);
                                        $dbrec->weight       = backup_todb($info['GRADE_CATEGORY']['#']['WEIGHT']['0']['#']);

                                        //If the grade_category exists in the course (by name), don't insert anything
                                        $catex = get_record('grade_category','courseid',$dbrec->courseid,'name',$dbrec->name);

                                        if (!$catex) {
                                            //Structure is equal to db, insert record
                                            $categoryid = insert_record('grade_category',$dbrec);
                                        } else {
                                            //Simply remap category
                                            $categoryid = $catex->id;
                                        }

                                        //Now, restore grade_item
                                        $items = $info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'];

                                        //Iterate over items
                                        for($i = 0; $i < sizeof($items); $i++) {
                                            $ite_info = $items[$i];
                                            //traverse_xmlize($ite_info);                                                                 //Debug
                                            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                                            //$GLOBALS['traverse_array']="";                                                              //Debug

                                            //Now build the GRADE_ITEM record structure
                                            $item->courseid     = $restore->course_id;
                                            $item->category     = $categoryid;
                                            $item->module_name  = backup_todb($ite_info['#']['MODULE_NAME']['0']['#']);
                                            $item->cminstance   = backup_todb($ite_info['#']['CMINSTANCE']['0']['#']);
                                            $item->scale_grade  = backup_todb($ite_info['#']['SCALE_GRADE']['0']['#']);
                                            $item->extra_credit = backup_todb($ite_info['#']['EXTRA_CREDIT']['0']['#']);
                                            $item->sort_order   = backup_todb($ite_info['#']['SORT_ORDER']['0']['#']);

                                            //Check that the module has been included in the restore
                                            if ($restore->mods[$item->module_name]->restore) {
                                                //Get the id of the moduletype
                                                if ($module = get_record('modules','name',$item->module_name)) {
                                                    $item->modid = $module->id;
                                                    //Get the instance id
                                                    if ($instance = backup_getid($restore->backup_unique_code,$item->module_name,$item->cminstance)) {
                                                        $item->cminstance = $instance->new_id;
                                                        //Structure is equal to db, insert record
                                                        $itemid = insert_record('grade_item',$item);

                                                        //Now process grade_exceptions
                                                        if (!empty($ite_info['#']['GRADE_EXCEPTIONS'])) {
                                                            $exceptions = $ite_info['#']['GRADE_EXCEPTIONS']['0']['#']['GRADE_EXCEPTION'];
                                                        } else {
                                                            $exceptions = array();
                                                        }

                                                        //Iterate over exceptions
                                                        for($j = 0; $j < sizeof($exceptions); $j++) {
                                                            $exc_info = $exceptions[$j];
                                                            //traverse_xmlize($exc_info);                                                                 //Debug
                                                            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                                                            //$GLOBALS['traverse_array']="";                                                              //Debug

                                                            //Now build the GRADE_EXCEPTIONS record structure
                                                            $exception->courseid     = $restore->course_id;
                                                            $exception->grade_itemid = $itemid;
                                                            $exception->userid       = backup_todb($exc_info['#']['USERID']['0']['#']);

                                                            //We have to recode the useridto field
                                                            $user = backup_getid($restore->backup_unique_code,"user",$exception->userid);
                                                            if ($user) {
                                                                $exception->userid = $user->new_id;
                                                                //Structure is equal to db, insert record
                                                                $exceptionid = insert_record('grade_exceptions',$exception);
                                                                //Do some output
                                                                $counter++;
                                                                if ($counter % 20 == 0) {
                                                                    if (!defined('RESTORE_SILENTLY')) {
                                                                        echo ".";
                                                                        if ($counter % 400 == 0) {
                                                                            echo "<br />";
                                                                        }
                                                                    }
                                                                    backup_flush(300);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        //Re-sort all the grade_items because we can have duplicates
                                        if ($grade_items = get_records ('grade_item','courseid',$restore->course_id,'sort_order','id,sort_order')) {
                                            $order = 1;
                                            foreach ($grade_items as $grade_item) {
                                                $grade_item->sort_order = $order;
                                                set_field ('grade_item','sort_order',$grade_item->sort_order,'id',$grade_item->id);
                                                $order++;
                                            }
                                        }
                                    }
                                    //Increment counters
                                    $countercat++;
                                    //Do some output
                                    if ($countercat % 1 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($countercat % 20 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }
                    if (!defined('RESTORE_SILENTLY')) {
                    //End ul
                        echo '</ul>';
                    }
                }
            }
        }                
     
        return $status;
    }

    //This function creates all the user, user_students, user_teachers
    //user_course_creators and user_admins from xml
    function restore_create_users($restore,$xml_file) {

        global $CFG, $db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //info will contain the old_id of every user
            //in backup_ids->info will be the real info (serialized)
            $info = restore_read_xml_users($restore,$xml_file);
        }

        //Now, get evey user_id from $info and user data from $backup_ids
        //and create the necessary records (users, user_students, user_teachers
        //user_course_creators and user_admins
        if (!empty($info->users)) {
            //For each user, take its info from backup_ids
            foreach ($info->users as $userid) {
                $rec = backup_getid($restore->backup_unique_code,"user",$userid); 
                $user = $rec->info;

                //Now, recode some languages (Moodle 1.5)
                if ($user->lang == 'ma_nt') {
                    $user->lang = 'mi_nt';
                }

                //Check if it's admin and coursecreator
                $is_admin =         !empty($user->roles['admin']);
                $is_coursecreator = !empty($user->roles['coursecreator']);

                //Check if it's teacher and student
                $is_teacher = !empty($user->roles['teacher']);
                $is_student = !empty($user->roles['student']);

                //Check if it's needed
                $is_needed = !empty($user->roles['needed']);

                //Calculate if it is a course user
                //Has role teacher or student or needed
                $is_course_user = ($is_teacher or $is_student or $is_needed);

                //To store new ids created
                $newid=null;
                //check if it exists (by username) and get its id
                $user_exists = true;
                $user_data = get_record("user","username",addslashes($user->username));
                if (!$user_data) {
                    $user_exists = false;
                } else {
                    $newid = $user_data->id;
                }
                //Flags to see if we have to create the user, roles and preferences
                $create_user = true;
                $create_roles = true;
                $create_preferences = true;

                //If we are restoring course users and it isn't a course user
                if ($restore->users == 1 and !$is_course_user) {
                    //If only restoring course_users and user isn't a course_user, inform to $backup_ids
                    $status = backup_putid($restore->backup_unique_code,"user",$userid,null,'notincourse');
                    $create_user = false;
                    $create_roles = false;
                    $create_preferences = false;
                }

                if ($user_exists and $create_user) {
                    //If user exists mark its newid in backup_ids (the same than old)
                    $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,'exists');
                    $create_user = false;
                }

                //Here, if create_user, do it
                if ($create_user) {
                    //Unset the id because it's going to be inserted with a new one
                    unset ($user->id);
                    //We addslashes to necessary fields
                    $user->username = addslashes($user->username);
                    $user->firstname = addslashes($user->firstname);
                    $user->lastname = addslashes($user->lastname);
                    $user->email = addslashes($user->email);
                    $user->institution = addslashes($user->institution);
                    $user->department = addslashes($user->department);
                    $user->address = addslashes($user->address);
                    $user->city = addslashes($user->city);
                    $user->url = addslashes($user->url);
                    $user->description = restore_decode_absolute_links(addslashes($user->description));

                    //We need to analyse the AUTH field to recode it:
                    //   - if the field isn't set, we are in a pre 1.4 backup and we'll 
                    //     use $CFG->auth
                    //   - if the destination site has any kind of INTERNAL authentication, 
                    //     then apply it to the new user.
                    //   - if the destination site has any kind of EXTERNAL authentication, 
                    //     then leave the original authentication of the user.

                    if ((! isset($user->auth)) || is_internal_auth($CFG->auth)) {
                        $user->auth = $CFG->auth;
                    }

                    //We need to process the POLICYAGREED field to recalculate it:
                    //    - if the destination site is different (by wwwroot) reset it.
                    //    - if the destination site is the same (by wwwroot), leave it unmodified

                    if ($restore->original_wwwroot != $CFG->wwwroot) {
                        $user->policyagreed = 0;
                    } else {
                        //Nothing to do, we are in the same server
                    }

                    //Check if the theme exists in destination server
                    $themes = get_list_of_themes();
                    if (!in_array($user->theme, $themes)) {
                        $user->theme = '';
                    }

                    //We are going to create the user
                    //The structure is exactly as we need
                    $newid = insert_record ("user",$user);
                    //Put the new id
                    $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new");
                }

                //Here, if create_roles, do it as necessary
                if ($create_roles) {
                    //Get the newid and current info from backup_ids
                    $data = backup_getid($restore->backup_unique_code,"user",$userid);
                    $newid = $data->new_id;
                    $currinfo = $data->info.",";

                    //Now, depending of the role, create records in user_studentes and user_teacher 
                    //and/or mark it in backup_ids
                    
                    if ($is_admin) {
                        //If the record (user_admins) doesn't exists
                        if (!record_exists("user_admins","userid",$newid)) {
                            //Only put status in backup_ids
                            $currinfo = $currinfo."admin,";
                            $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                        }
                    } 
                    if ($is_coursecreator) {
                        //If the record (user_coursecreators) doesn't exists
                        if (!record_exists("user_coursecreators","userid",$newid)) {
                            //Only put status in backup_ids
                            $currinfo = $currinfo."coursecreator,";
                            $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                        }
                    } 
                    if ($is_needed) {
                        //Only put status in backup_ids
                        $currinfo = $currinfo."needed,";
                        $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                    }
                    if ($is_teacher) {
                        //If the record (teacher) doesn't exists
                        if (!record_exists("user_teachers","userid",$newid,"course", $restore->course_id)) {
                            //Put status in backup_ids 
                            $currinfo = $currinfo."teacher,";
                            $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                            //Set course and user
                            $user->roles['teacher']->course = $restore->course_id;
                            $user->roles['teacher']->userid = $newid;

                            //Need to analyse the enrol field
                            //    - if it isn't set, set it to $CFG->enrol
                            //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                            //    - if we are in the same server (by wwwroot), maintain it unmodified.
                            if (empty($user->roles['teacher']->enrol)) {
                                $user->roles['teacher']->enrol = $CFG->enrol;
                            } else if ($restore->original_wwwroot != $CFG->wwwroot) {
                                $user->roles['teacher']->enrol = $CFG->enrol;
                            } else {
                                //Nothing to do. Leave it unmodified
                            }    

                            //Insert data in user_teachers
                            //The structure is exactly as we need
                            $status = insert_record("user_teachers",$user->roles['teacher']);
                        }
                    } 
                    if ($is_student) {
                        //If the record (student) doesn't exists
                        if (!record_exists("user_students","userid",$newid,"course", $restore->course_id)) {
                            //Put status in backup_ids
                            $currinfo = $currinfo."student,";
                            $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                            //Set course and user
                            $user->roles['student']->course = $restore->course_id;
                            $user->roles['student']->userid = $newid;

                            //Need to analyse the enrol field
                            //    - if it isn't set, set it to $CFG->enrol
                            //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                            //    - if we are in the same server (by wwwroot), maintain it unmodified.
                            if (empty($user->roles['student']->enrol)) {
                                $user->roles['student']->enrol = $CFG->enrol;
                            } else if ($restore->original_wwwroot != $CFG->wwwroot) {
                                $user->roles['student']->enrol = $CFG->enrol;
                            } else {
                                //Nothing to do. Leave it unmodified
                            }    

                            //Insert data in user_students
                            //The structure is exactly as we need
                            $status = insert_record("user_students",$user->roles['student']);
                        }
                    }
                    if (!$is_course_user) {
                        //If the record (user) doesn't exists
                        if (!record_exists("user","id",$newid)) {
                            //Put status in backup_ids
                            $currinfo = $currinfo."user,";
                            $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
                        }
                    }
                }

                //Here, if create_preferences, do it as necessary
                if ($create_preferences) {
                    //echo "Checking for preferences of user ".$user->username."<br />";         //Debug
                    //Get user new id from backup_ids
                    $data = backup_getid($restore->backup_unique_code,"user",$userid);
                    $newid = $data->new_id;
                    if (isset($user->user_preferences)) {
                        //echo "Preferences exist in backup file<br />";                         //Debug
                        foreach($user->user_preferences as $user_preference) {
                            //echo $user_preference->name." = ".$user_preference->value."<br />";    //Debug
                            //We check if that user_preference exists in DB
                            if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name)) {
                                //echo "Creating it<br />";                                              //Debug
                                //Prepare the record and insert it
                                $user_preference->userid = $newid;
                                $status = insert_record("user_preferences",$user_preference);
                            }
                        }
                    }
                }
            }
        }

        return $status;
    }

    //This function creates all the structures messages and contacts
    function restore_create_messages($restore,$xml_file) {

        global $CFG;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //info will contain the id and name of every table
            //(message, message_read and message_contacts)
            //in backup_ids->info will be the real info (serialized)
            $info = restore_read_xml_messages($restore,$xml_file);

            //If we have info, then process messages & contacts
            if ($info > 0) {
                //Count how many we have
                $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message');
                $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_read');
                $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_contacts');
                if ($unreadcount || $readcount || $contactcount) {
                    //Start ul
                    if (!defined('RESTORE_SILENTLY')) {
                        echo '<ul>';
                    }
                    //Number of records to get in every chunk
                    $recordset_size = 4;

                    //Process unread
                    if ($unreadcount) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('unreadmessages','message').'</li>';
                        }
                        $counter = 0;
                        while ($counter < $unreadcount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,"message",$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the MESSAGE record structure
                                        $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
                                        $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
                                        $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
                                        $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
                                        $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
                                        $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
                                        //We have to recode the useridfrom field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
                                        if ($user) {
                                            //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->useridfrom = $user->new_id;
                                        }
                                        //We have to recode the useridto field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
                                        if ($user) {
                                            //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->useridto = $user->new_id;
                                        }
                                        //Check if the record doesn't exist in DB!
                                        $exist = get_record('message','useridfrom',$dbrec->useridfrom,
                                                                      'useridto',  $dbrec->useridto,
                                                                      'timecreated',$dbrec->timecreated);
                                        if (!$exist) {
                                            //Not exist. Insert
                                            $status = insert_record('message',$dbrec);
                                        } else {
                                            //Duplicate. Do nothing
                                        }
                                    }
                                    //Do some output
                                    $counter++;
                                    if ($counter % 10 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($counter % 200 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }

                    //Process read
                    if ($readcount) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.get_string('readmessages','message').'</li>';
                        }
                        $counter = 0;
                        while ($counter < $readcount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,"message_read",$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the MESSAGE_READ record structure
                                        $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
                                        $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
                                        $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
                                        $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
                                        $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
                                        $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
                                        $dbrec->timeread = backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
                                        $dbrec->mailed = backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
                                        //We have to recode the useridfrom field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
                                        if ($user) {
                                            //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->useridfrom = $user->new_id;
                                        }
                                        //We have to recode the useridto field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
                                        if ($user) {
                                            //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->useridto = $user->new_id;
                                        }
                                        //Check if the record doesn't exist in DB!
                                        $exist = get_record('message_read','useridfrom',$dbrec->useridfrom,
                                                                           'useridto',  $dbrec->useridto,
                                                                           'timecreated',$dbrec->timecreated);
                                        if (!$exist) {
                                            //Not exist. Insert
                                            $status = insert_record('message_read',$dbrec);
                                        } else {
                                            //Duplicate. Do nothing
                                        }
                                    }
                                    //Do some output
                                    $counter++;
                                    if ($counter % 10 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($counter % 200 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }

                    //Process contacts
                    if ($contactcount) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<li>'.strtolower(get_string('contacts','message')).'</li>';
                        }
                        $counter = 0;
                        while ($counter < $contactcount) {
                            //Fetch recordset_size records in each iteration
                            $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
                            if ($recs) {
                                foreach ($recs as $rec) {
                                    //Get the full record from backup_ids
                                    $data = backup_getid($restore->backup_unique_code,"message_contacts",$rec->old_id);
                                    if ($data) {
                                        //Now get completed xmlized object
                                        $info = $data->info;
                                        //traverse_xmlize($info);                            //Debug
                                        //print_object ($GLOBALS['traverse_array']);         //Debug
                                        //$GLOBALS['traverse_array']="";                     //Debug
                                        //Now build the MESSAGE_CONTACTS record structure
                                        $dbrec->userid = backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
                                        $dbrec->contactid = backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
                                        $dbrec->blocked = backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
                                        //We have to recode the userid field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->userid);
                                        if ($user) {
                                            //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->userid = $user->new_id;
                                        }
                                        //We have to recode the contactid field
                                        $user = backup_getid($restore->backup_unique_code,"user",$dbrec->contactid);
                                        if ($user) {
                                            //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />";   //Debug
                                            $dbrec->contactid = $user->new_id;
                                        }
                                        //Check if the record doesn't exist in DB!
                                        $exist = get_record('message_contacts','userid',$dbrec->userid,
                                                                               'contactid',  $dbrec->contactid);
                                        if (!$exist) {
                                            //Not exist. Insert
                                            $status = insert_record('message_contacts',$dbrec);
                                        } else {
                                            //Duplicate. Do nothing
                                        }
                                    }
                                    //Do some output
                                    $counter++;
                                    if ($counter % 10 == 0) {
                                        if (!defined('RESTORE_SILENTLY')) {
                                            echo ".";
                                            if ($counter % 200 == 0) {
                                                echo "<br />";
                                            }
                                        }
                                        backup_flush(300);
                                    }
                                }
                            }
                        }
                    }
                    if (!defined('RESTORE_SILENTLY')) {
                        //End ul
                        echo '</ul>';
                    }
                }
            }
        }

       return $status;
    }

    //This function creates all the categories and questions
    //from xml 
    function restore_create_questions($restore,$xml_file) {

        global $CFG, $db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //info will contain the old_id of every category
            //in backup_ids->info will be the real info (serialized)
            $info = restore_read_xml_questions($restore,$xml_file);
        }
        //Now, if we have anything in info, we have to restore that
        //categories/questions
        if ($info) {
            if ($info !== true) {
                //Iterate over each category
                foreach ($info as $category) {
                    //Skip empty categories (some backups can contain them)
                    if (!empty($category->id)) {
                        $catrestore = "restore_question_categories";
                        if (function_exists($catrestore)) {
                            //print_object ($category);                                                //Debug
                            $status = $catrestore($category,$restore);
                        } else {
                            //Something was wrong. Function should exist.
                            $status = false;
                        }
                    }
                }

                //Now we have to recode the parent field of each restored category
                $categories = get_records_sql("SELECT old_id, new_id 
                                               FROM {$CFG->prefix}backup_ids
                                               WHERE backup_code = $restore->backup_unique_code AND
                                                     table_name = 'question_categories'");
                if ($categories) {
                    foreach ($categories as $category) {
                        $restoredcategory = get_record('question_categories','id',$category->new_id);
                        if ($restoredcategory->parent != 0) {
                            //echo 'Parent '.$restoredcategory->parent.' is ';           //Debug
                            $idcat = backup_getid($restore->backup_unique_code,'question_categories',$restoredcategory->parent);
                            if ($idcat->new_id) {
                                $restoredcategory->parent = $idcat->new_id;
                            } else {
                                $restoredcategory->parent = 0;
                            }
                            //echo $restoredcategory->parent.' now<br />';  //Debug
                            update_record('question_categories', $restoredcategory);
                        }
                    }
                }
            }
        } else {
            $status = false;
        }   
        return $status;
    }

    //This function creates all the scales
    function restore_create_scales($restore,$xml_file) {

        global $CFG, $db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //scales will contain the old_id of every scale
            //in backup_ids->info will be the real info (serialized)
            $scales = restore_read_xml_scales($restore,$xml_file);
        }
        //Now, if we have anything in scales, we have to restore that
        //scales
        if ($scales) {
            //Get admin->id for later use
            $admin = get_admin();
            $adminid = $admin->id;
            if ($scales !== true) {
                //Iterate over each scale
                foreach ($scales as $scale) {
                    //Get record from backup_ids
                    $data = backup_getid($restore->backup_unique_code,"scale",$scale->id);
                    //Init variables
                    $create_scale = false;

                    if ($data) {
                        //Now get completed xmlized object
                        $info = $data->info;
                        //traverse_xmlize($info);                                                                     //Debug
                        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                        //$GLOBALS['traverse_array']="";                                                              //Debug

                        //Now build the SCALE record structure
                        $sca->courseid = backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
                        $sca->userid = backup_todb($info['SCALE']['#']['USERID']['0']['#']);
                        $sca->name = backup_todb($info['SCALE']['#']['NAME']['0']['#']);
                        $sca->scale = backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
                        $sca->description = backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
                        $sca->timemodified = backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);

                        //Now search if that scale exists (by scale field) in course 0 (Standar scale)
                        //or in restore->course_id course (Personal scale)
                        if ($sca->courseid == 0) {
                            $course_to_search = 0;
                        } else {
                            $course_to_search = $restore->course_id;
                        }
                        $sca_db = get_record("scale","scale",$sca->scale,"courseid",$course_to_search);
                        //If it doesn't exist, create
                        if (!$sca_db) {
                            $create_scale = true;
                        } 
                        //If we must create the scale
                        if ($create_scale) {
                            //Me must recode the courseid if it's <> 0 (common scale)
                            if ($sca->courseid != 0) {
                                $sca->courseid = $restore->course_id;
                            }
                            //We must recode the userid
                            $user = backup_getid($restore->backup_unique_code,"user",$sca->userid);
                            if ($user) {
                                $sca->userid = $user->new_id;
                            } else {
                                //Assign it to admin
                                $sca->userid = $adminid;
                            }
                            //The structure is equal to the db, so insert the scale
                            $newid = insert_record ("scale",$sca);
                        } else {
                            //get current scale id
                            $newid = $sca_db->id;
                        }
                        if ($newid) {
                            //We have the newid, update backup_ids
                            backup_putid($restore->backup_unique_code,"scale",
                                         $scale->id, $newid);
                        }
                    }
                }
            }
        } else {
            $status = false;
        }  
        return $status;
    }

    //This function creates all the groups
    function restore_create_groups($restore,$xml_file) {

        global $CFG, $db;

        $status = true;
        $status2 = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //groups will contain the old_id of every group
            //in backup_ids->info will be the real info (serialized)
            $groups = restore_read_xml_groups($restore,$xml_file);
        }
        //Now, if we have anything in groups, we have to restore that
        //groups
        if ($groups) {
            if ($groups !== true) {
                //Iterate over each group
                foreach ($groups as $group) {
                    //Get record from backup_ids
                    $data = backup_getid($restore->backup_unique_code,"groups",$group->id);
                    //Init variables
                    $create_group = false;

                    if ($data) {
                        //Now get completed xmlized object
                        $info = $data->info;
                        //traverse_xmlize($info);                                                                     //Debug
                        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                        //$GLOBALS['traverse_array']="";                                                              //Debug
                        //Now build the GROUP record structure
                        $gro->courseid = backup_todb($info['GROUP']['#']['COURSEID']['0']['#']);
                        $gro->name = backup_todb($info['GROUP']['#']['NAME']['0']['#']);
                        $gro->description = backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
                        $gro->password = backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
                        $gro->lang = backup_todb($info['GROUP']['#']['LANG']['0']['#']);
                        $gro->theme = backup_todb($info['GROUP']['#']['THEME']['0']['#']);
                        $gro->picture = backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
                        $gro->hidepicture = backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
                        $gro->timecreated = backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
                        $gro->timemodified = backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
                
                        //Now search if that group exists (by name and description field) in 
                        //restore->course_id course 
                        $gro_db = get_record("groups","courseid",$restore->course_id,"name",$gro->name,"description",$gro->description);
                        //If it doesn't exist, create
                        if (!$gro_db) {
                            $create_group = true;
                        }
                        //If we must create the group
                        if ($create_group) {
                            //Me must recode the courseid to the restore->course_id 
                            $gro->courseid = $restore->course_id;

                            //Check if the theme exists in destination server
                            $themes = get_list_of_themes();
                            if (!in_array($gro->theme, $themes)) {
                                $gro->theme = '';
                            }

                            //The structure is equal to the db, so insert the group
                            $newid = insert_record ("groups",$gro);
                        } else { 
                            //get current group id
                            $newid = $gro_db->id;
                        }
                        if ($newid) {
                            //We have the newid, update backup_ids
                            backup_putid($restore->backup_unique_code,"groups",
                                         $group->id, $newid);
                        }
                        //Now restore members in the groups_members, only if
                        //users are included
                        if ($restore->users != 2) {
                            $status2 = restore_create_groups_members($newid,$info,$restore);
                        }
                    }   
                }
                //Now, restore group_files
                if ($status && $status2) {
                    $status2 = restore_group_files($restore); 
                }
            }
        } else {
            $status = false;
        } 
        return ($status && $status2);
    }

    //This function restores the groups_members
    function restore_create_groups_members($group_id,$info,$restore) {

        global $CFG;

        $status = true;

        //Get the members array
        $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];

        //Iterate over members
        for($i = 0; $i < sizeof($members); $i++) {
            $mem_info = $members[$i];
            //traverse_xmlize($mem_info);                                                                 //Debug
            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
            //$GLOBALS['traverse_array']="";                                                              //Debug

            //Now, build the GROUPS_MEMBERS record structure
            $group_member->groupid = $group_id;
            $group_member->userid = backup_todb($mem_info['#']['USERID']['0']['#']);
            $group_member->timeadded = backup_todb($mem_info['#']['TIMEADDED']['0']['#']);

            //We have to recode the userid field
            $user = backup_getid($restore->backup_unique_code,"user",$group_member->userid);
            if ($user) {
                $group_member->userid = $user->new_id;
            }

            //The structure is equal to the db, so insert the groups_members
            $newid = insert_record ("groups_members",$group_member);
            //Do some output
            if (($i+1) % 50 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i+1) % 1000 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
            
            if (!$newid) {
                $status = false;
            }
        }

        return $status;
    }

    //This function creates all the course events
    function restore_create_events($restore,$xml_file) {

        global $CFG, $db;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //events will contain the old_id of every event
            //in backup_ids->info will be the real info (serialized)
            $events = restore_read_xml_events($restore,$xml_file);
        }

        //Get admin->id for later use
        $admin = get_admin();
        $adminid = $admin->id;

        //Now, if we have anything in events, we have to restore that
        //events
        if ($events) {
            if ($events !== true) {
                //Iterate over each event
                foreach ($events as $event) {
                    //Get record from backup_ids
                    $data = backup_getid($restore->backup_unique_code,"event",$event->id);
                    //Init variables
                    $create_event = false;

                    if ($data) {
                        //Now get completed xmlized object
                        $info = $data->info;
                        //traverse_xmlize($info);                                                                     //Debug
                        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                        //$GLOBALS['traverse_array']="";                                                              //Debug

                        //Now build the EVENT record structure
                        $eve->name = backup_todb($info['EVENT']['#']['NAME']['0']['#']);
                        $eve->description = backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
                        $eve->format = backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
                        $eve->courseid = $restore->course_id;
                        $eve->groupid = backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
                        $eve->userid = backup_todb($info['EVENT']['#']['USERID']['0']['#']);
                        $eve->repeatid = backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
                        $eve->modulename = "";
                        $eve->instance = 0;
                        $eve->eventtype = backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
                        $eve->timestart = backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
                        $eve->timeduration = backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
                        $eve->visible = backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
                        $eve->timemodified = backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);

                        //Now search if that event exists (by description and timestart field) in
                        //restore->course_id course 
                        $eve_db = get_record("event","courseid",$eve->courseid,"description",$eve->description,"timestart",$eve->timestart);
                        //If it doesn't exist, create
                        if (!$eve_db) {
                            $create_event = true;
                        }
                        //If we must create the event
                        if ($create_event) {

                            //We must recode the userid
                            $user = backup_getid($restore->backup_unique_code,"user",$eve->userid);
                            if ($user) {
                                $eve->userid = $user->new_id;
                            } else {
                                //Assign it to admin
                                $eve->userid = $adminid;
                            }

                            //We must recode the repeatid if the event has it
                            if (!empty($eve->repeatid)) {
                                $repeat_rec = backup_getid($restore->backup_unique_code,"event_repeatid",$eve->repeatid);
                                if ($repeat_rec) {    //Exists, so use it...
                                    $eve->repeatid = $repeat_rec->new_id;
                                } else {              //Doesn't exists, calculate the next and save it
                                    $oldrepeatid = $eve->repeatid;
                                    $max_rec = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix.'event');
                                    $eve->repeatid = empty($max_rec) ? 1 : $max_rec->repeatid + 1;
                                    backup_putid($restore->backup_unique_code,"event_repeatid", $oldrepeatid, $eve->repeatid);
                                }
                            }
 
                            //We have to recode the groupid field
                            $group = backup_getid($restore->backup_unique_code,"groups",$eve->groupid);
                            if ($group) {
                                $eve->groupid = $group->new_id;
                            } else {
                                //Assign it to group 0
                                $eve->groupid = 0;
                            }

                            //The structure is equal to the db, so insert the event
                            $newid = insert_record ("event",$eve);
                        } else {
                            //get current event id
                            $newid = $eve_db->id;
                        }
                        if ($newid) {
                            //We have the newid, update backup_ids
                            backup_putid($restore->backup_unique_code,"event",
                                         $event->id, $newid);
                        }
                    }
                }
            }
        } else {
            $status = false;
        } 
        return $status;
    }

    //This function decode things to make restore multi-site fully functional
    //It does this conversions:
    //    - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
    //                     |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
    //
    //Note: Inter-activities linking is being implemented as a final
    //step in the restore execution, because we need to have it 
    //finished to know all the oldid, newid equivaleces
    function restore_decode_absolute_links($content) {
                                     
        global $CFG,$restore;    

        //Now decode wwwroot and file.php calls
        $search = array ("$@FILEPHP@$");

        //Check for the status of the slasharguments config variable
        $slash = $CFG->slasharguments;
        
        //Build the replace string as needed
        if ($slash == 1) {
            $replace = array ($CFG->wwwroot."/file.php/".$restore->course_id);
        } else {
            $replace = array ($CFG->wwwroot."/file.php?file=/".$restore->course_id);
        }
    
        $result = str_replace($search,$replace,$content);

        if ($result != $content && $CFG->debug>7) {                                  //Debug
            if (!defined('RESTORE_SILENTLY')) {
                echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />';        //Debug
            }
        }                                                                            //Debug

        return $result;
    }

    //This function restores the userfiles from the temp (user_files) directory to the
    //dataroot/users directory
    function restore_user_files($restore) {

        global $CFG;

        $status = true;

        $counter = 0;

        //First, we check to "users" exists and create is as necessary
        //in CFG->dataroot
        $dest_dir = $CFG->dataroot."/users";
        $status = check_dir_exists($dest_dir,true);

        //Now, we iterate over "user_files" records to check if that user dir must be
        //copied (and renamed) to the "users" dir.
        $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/user_files";
        //Check if directory exists
        if (is_dir($rootdir)) {
            $list = list_directories ($rootdir);
            if ($list) {
                //Iterate
                $counter = 0;
                foreach ($list as $dir) {
                    //Look for dir like username in backup_ids
                    $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
                                                     "table_name","user",
                                                     "old_id",$dir);
                    //If thar user exists in backup_ids
                    if ($data) {
                        //Only it user has been created now
                        //or if it existed previously, but he hasn't image (see bug 1123)
                        if ((strpos($data->info,"new") !== false) or 
                            (!check_dir_exists($dest_dir."/".$data->new_id,false))) {
                            //Copy the old_dir to its new location (and name) !!
                            //Only if destination doesn't exists
                            if (!file_exists($dest_dir."/".$data->new_id)) {
                                $status = backup_copy_file($rootdir."/".$dir,
                                              $dest_dir."/".$data->new_id,true);
                                $counter ++;
                            }
                            //Do some output
                            if ($counter % 2 == 0) {
                                if (!defined('RESTORE_SILENTLY')) {
                                    echo ".";
                                    if ($counter % 40 == 0) {
                                        echo "<br />";
                                    }
                                }
                                backup_flush(300);
                            }
                        }
                    }
                }
            }
        }
        //If status is ok and whe have dirs created, returns counter to inform
        if ($status and $counter) {
            return $counter;
        } else {
            return $status;
        }
    }

    //This function restores the groupfiles from the temp (group_files) directory to the
    //dataroot/groups directory
    function restore_group_files($restore) {

        global $CFG;

        $status = true;

        $counter = 0;

        //First, we check to "groups" exists and create is as necessary
        //in CFG->dataroot
        $dest_dir = $CFG->dataroot.'/groups';
        $status = check_dir_exists($dest_dir,true);

        //Now, we iterate over "group_files" records to check if that user dir must be
        //copied (and renamed) to the "groups" dir.
        $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/group_files";
        //Check if directory exists
        if (is_dir($rootdir)) {
            $list = list_directories ($rootdir);
            if ($list) {
                //Iterate
                $counter = 0;
                foreach ($list as $dir) {
                    //Look for dir like groupid in backup_ids
                    $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
                                                     "table_name","groups",
                                                     "old_id",$dir);
                    //If that group exists in backup_ids
                    if ($data) {
                        if (!file_exists($dest_dir."/".$data->new_id)) {
                            $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id,true);
                            $counter ++;
                        }
                        //Do some output
                        if ($counter % 2 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 40 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        } 
                    }
                }
            }
        }
        //If status is ok and whe have dirs created, returns counter to inform
        if ($status and $counter) {
            return $counter;
        } else {
            return $status;
        }
    }

    //This function restores the course files from the temp (course_files) directory to the
    //dataroot/course_id directory
    function restore_course_files($restore) {

        global $CFG;

        $status = true;
 
        $counter = 0;

        //First, we check to "course_id" exists and create is as necessary
        //in CFG->dataroot
        $dest_dir = $CFG->dataroot."/".$restore->course_id;
        $status = check_dir_exists($dest_dir,true);

        //Now, we iterate over "course_files" records to check if that file/dir must be
        //copied to the "dest_dir" dir.
        $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/course_files";
        //Check if directory exists
        if (is_dir($rootdir)) {
            $list = list_directories_and_files ($rootdir);
            if ($list) {
                //Iterate
                $counter = 0;
                foreach ($list as $dir) {
                    //Copy the dir to its new location 
                    //Only if destination file/dir doesn exists
                    if (!file_exists($dest_dir."/".$dir)) {
                        $status = backup_copy_file($rootdir."/".$dir,
                                      $dest_dir."/".$dir,true);
                        $counter ++;
                    }
                    //Do some output
                    if ($counter % 2 == 0) {       
                        if (!defined('RESTORE_SILENTLY')) {
                            echo ".";
                            if ($counter % 40 == 0) {       
                                echo "<br />";
                            }
                        }
                        backup_flush(300);
                    }
                }
            }
        }
        //If status is ok and whe have dirs created, returns counter to inform
        if ($status and $counter) {
            return $counter;
        } else {
            return $status;
        }
    }
   

    //This function creates all the structures for every module in backup file
    //Depending what has been selected.
    function restore_create_modules($restore,$xml_file) {

        global $CFG;

        $status = true;
        //Check it exists
        if (!file_exists($xml_file)) {
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //info will contain the id and modtype of every module
            //in backup_ids->info will be the real info (serialized)
            $info = restore_read_xml_modules($restore,$xml_file);
        }
        //Now, if we have anything in info, we have to restore that mods
        //from backup_ids (calling every mod restore function)
        if ($info) {
            if ($info !== true) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo '<ul>';
                }
                //Iterate over each module
                foreach ($info as $mod) {
                    if (!is_array($restore->mods[$mod->modtype]->instances)  // we don't care about per instance
                        || (array_key_exists($mod->id,$restore->mods[$mod->modtype]->instances) 
                            && !empty($restore->mods[$mod->modtype]->instances[$mod->id]->restore))) {
                        $modrestore = $mod->modtype."_restore_mods";
                        if (function_exists($modrestore)) {
                            //print_object ($mod);                                                //Debug
                            $status = $status and $modrestore($mod,$restore); //bit operator & not reliable here!
                        } else {
                            //Something was wrong. Function should exist.
                            $status = false;
                        }
                    }
                }
                if (!defined('RESTORE_SILENTLY')) {
                    echo '</ul>';
                }
            }
        } else {
            $status = false;
        }
       return $status;
    }

    //This function creates all the structures for every log in backup file
    //Depending what has been selected.
    function restore_create_logs($restore,$xml_file) {
            
        global $CFG,$db;

        //Number of records to get in every chunk
        $recordset_size = 4;
        //Counter, points to current record
        $counter = 0;
        //To count all the recods to restore
        $count_logs = 0;
        
        $status = true;
        //Check it exists 
        if (!file_exists($xml_file)) { 
            $status = false;
        }
        //Get info from xml
        if ($status) {
            //count_logs will contain the number of logs entries to process
            //in backup_ids->info will be the real info (serialized)
            $count_logs = restore_read_xml_logs($restore,$xml_file);
        }
 
        //Now, if we have records in count_logs, we have to restore that logs
        //from backup_ids. This piece of code makes calls to:
        // - restore_log_course() if it's a course log
        // - restore_log_user() if it's a user log
        // - restore_log_module() if it's a module log.
        //And all is segmented in chunks to allow large recordsets to be restored !!
        if ($count_logs > 0) {
            while ($counter < $count_logs) {
                //Get a chunk of records
                //Take old_id twice to avoid adodb limitation
                $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id,old_id",$counter,$recordset_size);
                //We have logs
                if ($logs) {
                    //Iterate
                    foreach ($logs as $log) {
                        //Get the full record from backup_ids
                        $data = backup_getid($restore->backup_unique_code,"log",$log->old_id);
                        if ($data) {
                            //Now get completed xmlized object
                            $info = $data->info;
                            //traverse_xmlize($info);                                                                     //Debug
                            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                            //$GLOBALS['traverse_array']="";                                                              //Debug
                            //Now build the LOG record structure
                            $dblog->time = backup_todb($info['LOG']['#']['TIME']['0']['#']);
                            $dblog->userid = backup_todb($info['LOG']['#']['USERID']['0']['#']);
                            $dblog->ip = backup_todb($info['LOG']['#']['IP']['0']['#']);
                            $dblog->course = $restore->course_id;
                            $dblog->module = backup_todb($info['LOG']['#']['MODULE']['0']['#']);
                            $dblog->cmid = backup_todb($info['LOG']['#']['CMID']['0']['#']);
                            $dblog->action = backup_todb($info['LOG']['#']['ACTION']['0']['#']);
                            $dblog->url = backup_todb($info['LOG']['#']['URL']['0']['#']);
                            $dblog->info = backup_todb($info['LOG']['#']['INFO']['0']['#']);
                            //We have to recode the userid field
                            $user = backup_getid($restore->backup_unique_code,"user",$dblog->userid);
                            if ($user) {
                                //echo "User ".$dblog->userid." to user ".$user->new_id."<br />";                             //Debug
                                $dblog->userid = $user->new_id;
                            }
                            //We have to recode the cmid field (if module isn't "course" or "user")
                            if ($dblog->module != "course" and $dblog->module != "user") {
                                $cm = backup_getid($restore->backup_unique_code,"course_modules",$dblog->cmid);
                                if ($cm) {
                                    //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />";                         //Debug
                                    $dblog->cmid = $cm->new_id;
                                } else {
                                    $dblog->cmid = 0;
                                }
                            }
                            //print_object ($dblog);                                                                        //Debug
                            //Now, we redirect to the needed function to make all the work
                            if ($dblog->module == "course") {
                                //It's a course log,
                                $stat = restore_log_course($restore,$dblog);
                            } elseif ($dblog->module == "user") {
                                //It's a user log,
                                $stat = restore_log_user($restore,$dblog);
                            } else {
                                //It's a module log,
                                $stat = restore_log_module($restore,$dblog);
                            }
                        }

                        //Do some output
                        $counter++;
                        if ($counter % 10 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 200 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                } else {
                    //We never should arrive here
                    $counter = $count_logs;
                    $status = false;
                }
            }
        }

        return $status;
    }

    //This function inserts a course log record, calculating the URL field as necessary
    function restore_log_course($restore,$log) {

        $status = true;
        $toinsert = false;

        //echo "<hr />Before transformations<br />";                                        //Debug
        //print_object($log);                                                           //Debug
        //Depending of the action, we recode different things
        switch ($log->action) {
        case "view":
            $log->url = "view.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        case "guest":
            $log->url = "view.php?id=".$log->course;
            $toinsert = true;
            break;
        case "user report":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                //Now, extract the mode from the url field
                $mode = substr(strrchr($log->url,"="),1);
                $log->url = "user.php?id=".$log->course."&user=".$log->info."&mode=".$mode;
                $toinsert = true;
            }
            break;
        case "add mod":
            //Extract the course_module from the url field
            $cmid = substr(strrchr($log->url,"="),1);
            //recode the course_module to see it it has been restored
            $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
            if ($cm) {
                $cmid = $cm->new_id;
                //Extract the module name and the module id from the info field
                $modname = strtok($log->info," ");
                $modid = strtok(" ");
                //recode the module id to see if it has been restored
                $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
                if ($mod) {
                    $modid = $mod->new_id;
                    //Now I have everything so reconstruct url and info
                    $log->info = $modname." ".$modid;
                    $log->url = "../mod/".$modname."/view.php?id=".$cmid;
                    $toinsert = true;
                }
            }
            break;
        case "update mod":
            //Extract the course_module from the url field
            $cmid = substr(strrchr($log->url,"="),1);
            //recode the course_module to see it it has been restored
            $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
            if ($cm) {
                $cmid = $cm->new_id;
                //Extract the module name and the module id from the info field
                $modname = strtok($log->info," ");
                $modid = strtok(" ");
                //recode the module id to see if it has been restored
                $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
                if ($mod) {
                    $modid = $mod->new_id;
                    //Now I have everything so reconstruct url and info
                    $log->info = $modname." ".$modid;
                    $log->url = "../mod/".$modname."/view.php?id=".$cmid;
                    $toinsert = true;
                }
            }
            break;
        case "delete mod":
            $log->url = "view.php?id=".$log->course;
            $toinsert = true;
            break;
        case "update":
            $log->url = "edit.php?id=".$log->course;
            $log->info = "";
            $toinsert = true;
            break;
        case "unenrol":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->course;
                $toinsert = true;
            }
            break;
        case "enrol":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->course;
                $toinsert = true;
            }
            break;
        case "editsection":
            //Extract the course_section from the url field
            $secid = substr(strrchr($log->url,"="),1);
            //recode the course_section to see if it has been restored
            $sec = backup_getid($restore->backup_unique_code,"course_sections",$secid);
            if ($sec) {
                $secid = $sec->new_id;
                //Now I have everything so reconstruct url and info
                $log->url = "editsection.php?id=".$secid;
                $toinsert = true;
            }
            break;
        case "new":
            $log->url = "view.php?id=".$log->course;
            $log->info = "";
            $toinsert = true;
            break;
        case "recent":
            $log->url = "recent.php?id=".$log->course;
            $log->info = "";
            $toinsert = true;
            break;
        case "report log":
            $log->url = "report/log/index.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        case "report live":
            $log->url = "report/log/live.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        case "report outline":
            $log->url = "report/outline/index.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        case "report participation":
            $log->url = "report/participation/index.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        case "report stats":
            $log->url = "report/stats/index.php?id=".$log->course;
            $log->info = $log->course;
            $toinsert = true;
            break;
        default:
            echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />";                 //Debug
            break;
        }

        //echo "After transformations<br />";                                             //Debug
        //print_object($log);                                                           //Debug

        //Now if $toinsert is set, insert the record
        if ($toinsert) {
            //echo "Inserting record<br />";                                              //Debug
            $status = insert_record("log",$log);
        }
        return $status;
    }

    //This function inserts a user log record, calculating the URL field as necessary
    function restore_log_user($restore,$log) {

        $status = true;
        $toinsert = false;
        
        //echo "<hr />Before transformations<br />";                                        //Debug
        //print_object($log);                                                           //Debug
        //Depending of the action, we recode different things                           
        switch ($log->action) {
        case "view":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->info."&course=".$log->course;
                $toinsert = true;
            }
            break;
        case "change password":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->info."&course=".$log->course;
                $toinsert = true;
            }
            break;
        case "login":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->info."&course=".$log->course;
                $toinsert = true;
            }
            break;
        case "logout":
            //recode the info field (it's the user id)
            $user = backup_getid($restore->backup_unique_code,"user",$log->info);
            if ($user) {
                $log->info = $user->new_id;
                $log->url = "view.php?id=".$log->info."&course=".$log->course;
                $toinsert = true;
            }
            break;
        case "view all":
            $log->url = "view.php?id=".$log->course;
            $log->info = "";
            $toinsert = true;
        case "update":
            //We split the url by ampersand char 
            $first_part = strtok($log->url,"&");
            //Get data after the = char. It's the user being updated
            $userid = substr(strrchr($first_part,"="),1);
            //Recode the user
            $user = backup_getid($restore->backup_unique_code,"user",$userid);
            if ($user) {
                $log->info = "";
                $log->url = "view.php?id=".$user->new_id."&course=".$log->course;
                $toinsert = true;
            }
            break;
        default:
            echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />";                 //Debug
            break;
        }

        //echo "After transformations<br />";                                             //Debug
        //print_object($log);                                                           //Debug

        //Now if $toinsert is set, insert the record
        if ($toinsert) {
            //echo "Inserting record<br />";                                              //Debug
            $status = insert_record("log",$log);
        }
        return $status;
    }

    //This function inserts a module log record, calculating the URL field as necessary
    function restore_log_module($restore,$log) {

        $status = true;
        $toinsert = false;

        //echo "<hr />Before transformations<br />";                                        //Debug
        //print_object($log);                                                           //Debug

        //Now we see if the required function in the module exists
        $function = $log->module."_restore_logs";
        if (function_exists($function)) {
            //Call the function
            $log = $function($restore,$log);
            //If everything is ok, mark the insert flag
            if ($log) {
                $toinsert = true;
            }
        }

        //echo "After transformations<br />";                                             //Debug
        //print_object($log);                                                           //Debug

        //Now if $toinsert is set, insert the record
        if ($toinsert) {
            //echo "Inserting record<br />";                                              //Debug
            $status = insert_record("log",$log);
        }
        return $status;
    }

    //This function adjusts the instance field into course_modules. It's executed after
    //modules restore. There, we KNOW the new instance id !!
    function restore_check_instances($restore) {

        global $CFG;

        $status = true;

        //We are going to iterate over each course_module saved in backup_ids
        $course_modules = get_records_sql("SELECT old_id,new_id
                                           FROM {$CFG->prefix}backup_ids
                                           WHERE backup_code = '$restore->backup_unique_code' AND
                                                 table_name = 'course_modules'");
        if ($course_modules) {
            foreach($course_modules as $cm) {
                //Get full record, using backup_getids
                $cm_module = backup_getid($restore->backup_unique_code,"course_modules",$cm->old_id);
                //Now we are going to the REAL course_modules to get its type (field module)
                $module = get_record("course_modules","id",$cm_module->new_id);
                if ($module) {
                    //We know the module type id. Get the name from modules
                    $type = get_record("modules","id",$module->module);
                    if ($type) {
                        //We know the type name and the old_id. Get its new_id
                        //from backup_ids. It's the instance !!!
                        $instance =  backup_getid($restore->backup_unique_code,$type->name,$cm_module->info);
                        if ($instance) {
                            //We have the new instance, so update the record in course_modules
                            $module->instance = $instance->new_id;
                            //print_object ($module); 							//Debug
                            $status = update_record("course_modules",$module);
                        } else {
                            $status = false;
                        }
                    } else {
                        $status = false;
                    }
                } else {
                    $status = false;
               }
            }
        }


        return $status;
    }

    //=====================================================================================
    //==                                                                                 ==
    //==                         XML Functions (SAX)                                     ==
    //==                                                                                 ==
    //=====================================================================================

    //This is the class used to do all the xml parse
    class MoodleParser {

        var $level = 0;        //Level we are
        var $counter = 0;      //Counter
        var $tree = array();   //Array of levels we are
        var $content = "";     //Content under current level
        var $todo = "";        //What we hav to do when parsing
        var $info = "";        //Information collected. Temp storage. Used to return data after parsing.
        var $temp = "";        //Temp storage.
        var $preferences = ""; //Preferences about what to load !!
        var $finished = false; //Flag to say xml_parse to stop

        //This function is used to get the current contents property value
        //They are trimed (and converted from utf8 if needed)
        function getContents() {
            global $CFG;

            if (empty($CFG->unicodedb)) {
                return trim(utf8_decode($this->content));
            } else {
                return trim($this->content);
            }
        }
 
        //This is the startTag handler we use where we are reading the info zone (todo="INFO")
        function startElementInfo($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into INFO zone
            //if ($this->tree[2] == "INFO")                                                             //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
        function startElementCourseHeader($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into COURSE_HEADER zone
            //if ($this->tree[3] == "HEADER")                                                           //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
        function startElementBlocks($parser, $tagName, $attrs) {
            //Refresh properties     
            $this->level++;
            $this->tree[$this->level] = $tagName;   
            
            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into BLOCKS zone
            //if ($this->tree[3] == "BLOCKS")                                                         //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
        function startElementSections($parser, $tagName, $attrs) {
            //Refresh properties     
            $this->level++;
            $this->tree[$this->level] = $tagName;   

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into SECTIONS zone
            //if ($this->tree[3] == "SECTIONS")                                                         //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
        function startElementMetacourse($parser, $tagName, $attrs) {

            //Refresh properties     
            $this->level++;
            $this->tree[$this->level] = $tagName;   
            
            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into METACOURSE zone
            //if ($this->tree[3] == "METACOURSE")                                                         //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
        function startElementGradebook($parser, $tagName, $attrs) {

            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into GRADEBOOK zone
            //if ($this->tree[3] == "GRADEBOOK")                                                         //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";  //Debug

            //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
            if (isset($this->tree[5]) and isset($this->tree[3])) {
                if (($this->tree[5] == "GRADE_PREFERENCE" || $this->tree[5] == "GRADE_LETTER" || $this->tree[5] == "GRADE_CATEGORY" ) && ($this->tree[3] == "GRADEBOOK")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }
        
        
        //This is the startTag handler we use where we are reading the user zone (todo="USERS")
        function startElementUsers($parser, $tagName, $attrs) {
            //Refresh properties     
            $this->level++;
            $this->tree[$this->level] = $tagName;   

            //Check if we are into USERS zone  
            //if ($this->tree[3] == "USERS")                                                            //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }

        //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
        function startElementMessages($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into MESSAGES zone
            //if ($this->tree[3] == "MESSAGES")                                                          //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";  //Debug

            //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "MESSAGE" || $this->tree[5] == "CONTACT" ) and ($this->tree[3] == "MESSAGES")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }
        //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
        function startElementQuestions($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") {        //Debug
            //    echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-";                            //Debug
            //}                                                                                        //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into QUESTION_CATEGORIES zone
            //if ($this->tree[3] == "QUESTION_CATEGORIES")                                              //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "QUESTION_CATEGORY") and ($this->tree[3] == "QUESTION_CATEGORIES")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
        function startElementScales($parser, $tagName, $attrs) {
            //Refresh properties          
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") {                                 //Debug
            //    echo "<P>SCALE: ".strftime ("%X",time()),"-";                                        //Debug
            //}                                                                                        //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into SCALES zone
            //if ($this->tree[3] == "SCALES")                                                           //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a SCALE tag under a SCALES zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "SCALE") and ($this->tree[3] == "SCALES")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        function startElementGroups($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") {                                 //Debug
            //    echo "<P>GROUP: ".strftime ("%X",time()),"-";                                        //Debug
            //}                                                                                        //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into GROUPS zone
            //if ($this->tree[3] == "GROUPS")                                                           //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a GROUP tag under a GROUPS zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "GROUP") and ($this->tree[3] == "GROUPS")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
        function startElementEvents($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") {                                 //Debug
            //    echo "<P>EVENT: ".strftime ("%X",time()),"-";                                        //Debug
            //}                                                                                        //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into EVENTS zone
            //if ($this->tree[3] == "EVENTS")                                                           //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a EVENT tag under a EVENTS zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "EVENT") and ($this->tree[3] == "EVENTS")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
        function startElementModules($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "MOD" && $this->tree[3] == "MODULES") {                                     //Debug
            //    echo "<P>MOD: ".strftime ("%X",time()),"-";                                             //Debug
            //}                                                                                           //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into MODULES zone
            //if ($this->tree[3] == "MODULES")                                                          //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a MOD tag under a MODULES zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "MOD") and ($this->tree[3] == "MODULES")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
        function startElementLogs($parser, $tagName, $attrs) {
            //Refresh properties
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //if ($tagName == "LOG" && $this->tree[3] == "LOGS") {                                        //Debug
            //    echo "<P>LOG: ".strftime ("%X",time()),"-";                                             //Debug
            //}                                                                                           //Debug

            //Output something to avoid browser timeouts...
            backup_flush();

            //Check if we are into LOGS zone
            //if ($this->tree[3] == "LOGS")                                                             //Debug
            //    echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug

            //If we are under a LOG tag under a LOGS zone, accumule it
            if (isset($this->tree[4]) and isset($this->tree[3])) {
                if (($this->tree[4] == "LOG") and ($this->tree[3] == "LOGS")) {
                    if (!isset($this->temp)) {
                        $this->temp = "";
                    }
                    $this->temp .= "<".$tagName.">";
                }
            }
        }

        //This is the startTag default handler we use when todo is undefined
        function startElement($parser, $tagName, $attrs) {
            $this->level++;
            $this->tree[$this->level] = $tagName;

            //Output something to avoid browser timeouts...
            backup_flush();

            echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n";   //Debug
        }
 
        //This is the endTag handler we use where we are reading the info zone (todo="INFO")
        function endElementInfo($parser, $tagName) {
            //Check if we are into INFO zone
            if ($this->tree[2] == "INFO") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 3) {
                    switch ($tagName) {
                        case "NAME":
                            $this->info->backup_name = $this->getContents();
                            break;
                        case "MOODLE_VERSION":
                            $this->info->backup_moodle_version = $this->getContents();
                            break;
                        case "MOODLE_RELEASE":
                            $this->info->backup_moodle_release = $this->getContents();
                            break;
                        case "BACKUP_VERSION":
                            $this->info->backup_backup_version = $this->getContents();
                            break;
                        case "BACKUP_RELEASE":
                            $this->info->backup_backup_release = $this->getContents();
                            break;
                        case "DATE":
                            $this->info->backup_date = $this->getContents();
                            break;
                        case "ORIGINAL_WWWROOT":
                            $this->info->original_wwwroot = $this->getContents();
                            break;
                    }
                }
                if ($this->tree[3] == "DETAILS") {
                    if ($this->level == 4) {
                        switch ($tagName) {
                            case "METACOURSE":
                                $this->info->backup_metacourse = $this->getContents();
                                break;
                            case "USERS":
                                $this->info->backup_users = $this->getContents();
                                break;
                            case "LOGS":
                                $this->info->backup_logs = $this->getContents();
                                break;
                            case "USERFILES":
                                $this->info->backup_user_files = $this->getContents();
                                break;
                            case "COURSEFILES":
                                $this->info->backup_course_files = $this->getContents();
                                break;
                            case "MESSAGES":
                                $this->info->backup_messages = $this->getContents();
                                break;
                            case 'BLOCKFORMAT':
                                $this->info->backup_block_format = $this->getContents();
                                break;
                        }
                    }
                    if ($this->level == 5) {
                        switch ($tagName) {
                            case "NAME":
                                $this->info->tempName = $this->getContents();
                                break;
                            case "INCLUDED":
                                $this->info->mods[$this->info->tempName]->backup = $this->getContents();
                                break;
                            case "USERINFO":
                                $this->info->mods[$this->info->tempName]->userinfo = $this->getContents();
                                break;
                        }
                    }
                    if ($this->level == 7) {
                        switch ($tagName) {
                            case "ID":
                                $this->info->tempId = $this->getContents();
                                $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->id = $this->info->tempId;
                                break;
                            case "NAME":
                                $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->name = $this->getContents();
                                break;
                            case "INCLUDED":
                                $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->backup = $this->getContents();
                                break;
                            case "USERINFO":
                                $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->userinfo = $this->getContents();
                                break;
                        }
                    }
                }
            }

            //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "INFO") {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
        function endElementCourseHeader($parser, $tagName) {
            //Check if we are into COURSE_HEADER zone
            if ($this->tree[3] == "HEADER") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 4) {
                    switch ($tagName) {
                        case "ID":
                            $this->info->course_id = $this->getContents();
                            break;
                        case "PASSWORD":
                            $this->info->course_password = $this->getContents();
                            break;
                        case "FULLNAME":
                            $this->info->course_fullname = $this->getContents();
                            break;
                        case "SHORTNAME":
                            $this->info->course_shortname = $this->getContents();
                            break;
                        case "IDNUMBER":
                            $this->info->course_idnumber = $this->getContents();
                            break;
                        case "SUMMARY":
                            $this->info->course_summary = $this->getContents();
                            break;
                        case "FORMAT":
                            $this->info->course_format = $this->getContents();
                            break;
                        case "SHOWGRADES":
                            $this->info->course_showgrades = $this->getContents();
                            break;
                        case "BLOCKINFO":
                            $this->info->blockinfo = $this->getContents();
                            break;
                        case "NEWSITEMS":
                            $this->info->course_newsitems = $this->getContents();
                            break;
                        case "TEACHER":
                            $this->info->course_teacher = $this->getContents();
                            break;
                        case "TEACHERS":
                            $this->info->course_teachers = $this->getContents();
                            break;
                        case "STUDENT":
                            $this->info->course_student = $this->getContents();
                            break;
                        case "STUDENTS":
                            $this->info->course_students = $this->getContents();
                            break;
                        case "GUEST":
                            $this->info->course_guest = $this->getContents();
                            break;
                        case "STARTDATE":
                            $this->info->course_startdate = $this->getContents();
                            break;
                        case "ENROLPERIOD":
                            $this->info->course_enrolperiod = $this->getContents();
                            break;
                        case "NUMSECTIONS":
                            $this->info->course_numsections = $this->getContents();
                            break;
                        //case "SHOWRECENT":                                          INFO: This is out in 1.3
                        //    $this->info->course_showrecent = $this->getContents();
                        //    break;
                        case "MAXBYTES":
                            $this->info->course_maxbytes = $this->getContents();
                            break;
                        case "SHOWREPORTS":
                            $this->info->course_showreports = $this->getContents();
                            break;
                        case "GROUPMODE":
                            $this->info->course_groupmode = $this->getContents();
                            break;
                        case "GROUPMODEFORCE":
                            $this->info->course_groupmodeforce = $this->getContents();
                            break;
                        case "LANG":
                            $this->info->course_lang = $this->getContents();
                            break;
                        case "THEME":
                            $this->info->course_theme = $this->getContents();
                            break;
                        case "COST":
                            $this->info->course_cost = $this->getContents();
                            break;
                        case "CURRENCY":
                            $this->info->course_currency = $this->getContents();
                            break;
                        case "MARKER":
                            $this->info->course_marker = $this->getContents();
                            break;
                        case "VISIBLE":
                            $this->info->course_visible = $this->getContents();
                            break;
                        case "HIDDENSECTIONS":
                            $this->info->course_hiddensections = $this->getContents();
                            break;
                        case "TIMECREATED":
                            $this->info->course_timecreated = $this->getContents();
                            break;
                        case "TIMEMODIFIED":
                            $this->info->course_timemodified = $this->getContents();
                            break;
                        case "METACOURSE":
                            $this->info->course_metacourse = $this->getContents();
                            break;
                    }
                }
                if ($this->tree[4] == "CATEGORY") {
                    if ($this->level == 5) {
                        switch ($tagName) {
                            case "ID":
                                $this->info->category->id = $this->getContents();
                                break;
                            case "NAME":
                                $this->info->category->name = $this->getContents();
                                break;
                        }
                    }
                }

            }

            //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "HEADER") {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
        function endElementBlocks($parser, $tagName) {
            //Check if we are into BLOCKS zone
            if ($this->tree[3] == 'BLOCKS') {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 4) {
                    switch ($tagName) {
                        case 'BLOCK':
                            //We've finalized a block, get it
                            $this->info->instances[] = $this->info->tempinstance;
                            unset($this->info->tempinstance);
                            break;
                        default:
                            die($tagName);
                    }
                }
                if ($this->level == 5) {
                    switch ($tagName) {
                        case 'NAME':
                            $this->info->tempinstance->name = $this->getContents();
                            break;
                        case 'PAGEID':
                            $this->info->tempinstance->pageid = $this->getContents();
                            break;
                        case 'PAGETYPE':
                            $this->info->tempinstance->pagetype = $this->getContents();
                            break;
                        case 'POSITION':
                            $this->info->tempinstance->position = $this->getContents();
                            break;
                        case 'WEIGHT':
                            $this->info->tempinstance->weight = $this->getContents();
                            break;
                        case 'VISIBLE':
                            $this->info->tempinstance->visible = $this->getContents();
                            break;
                        case 'CONFIGDATA':
                            $this->info->tempinstance->configdata = $this->getContents();
                            break;
                    }
                }
            }

            //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
            //         THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
            if ($this->tree[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = '';
            $this->level--;
            $this->content = "";
        }

        //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
        function endElementSections($parser, $tagName) {
            //Check if we are into SECTIONS zone
            if ($this->tree[3] == "SECTIONS") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 4) {
                    switch ($tagName) {
                        case "SECTION":
                            //We've finalized a section, get it
                            $this->info->sections[$this->info->tempsection->id] = $this->info->tempsection;
                            unset($this->info->tempsection);
                    }
                }
                if ($this->level == 5) {
                    switch ($tagName) {
                        case "ID":
                            $this->info->tempsection->id = $this->getContents();
                            break;
                        case "NUMBER":
                            $this->info->tempsection->number = $this->getContents();
                            break;
                        case "SUMMARY":
                            $this->info->tempsection->summary = $this->getContents();
                            break;
                        case "VISIBLE":
                            $this->info->tempsection->visible = $this->getContents();
                            break;
                    }
                }
                if ($this->level == 6) {
                    switch ($tagName) {
                        case "MOD":
                            //We've finalized a mod, get it
                            $this->info->tempsection->mods[$this->info->tempmod->id]->type = 
                                $this->info->tempmod->type;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->instance = 
                                $this->info->tempmod->instance;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->added = 
                                $this->info->tempmod->added;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->score = 
                                $this->info->tempmod->score;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->indent = 
                                $this->info->tempmod->indent;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->visible = 
                                $this->info->tempmod->visible;
                            $this->info->tempsection->mods[$this->info->tempmod->id]->groupmode = 
                                $this->info->tempmod->groupmode;
                            unset($this->info->tempmod);
                    }
                }
                if ($this->level == 7) {
                    switch ($tagName) {
                        case "ID":
                            $this->info->tempmod->id = $this->getContents();
                            break;
                        case "TYPE":
                            $this->info->tempmod->type = $this->getContents();
                            break;
                        case "INSTANCE":
                            $this->info->tempmod->instance = $this->getContents();
                            break;
                        case "ADDED":
                            $this->info->tempmod->added = $this->getContents();
                            break;
                        case "SCORE":
                            $this->info->tempmod->score = $this->getContents();
                            break;
                        case "INDENT":
                            $this->info->tempmod->indent = $this->getContents();
                            break;
                        case "VISIBLE":
                            $this->info->tempmod->visible = $this->getContents();
                            break;
                        case "GROUPMODE":
                            $this->info->tempmod->groupmode = $this->getContents();
                            break;
                    }
                }
            }

            //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "SECTIONS") {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
        function endElementMetacourse($parser, $tagName) {
            //Check if we are into METACOURSE zone
            if ($this->tree[3] == 'METACOURSE') {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 5) {
                    switch ($tagName) {
                        case 'CHILD':
                            //We've finalized a child, get it
                            $this->info->childs[] = $this->info->tempmeta;
                            unset($this->info->tempmeta);
                            break;
                        case 'PARENT':
                            //We've finalized a parent, get it
                            $this->info->parents[] = $this->info->tempmeta;
                            unset($this->info->tempmeta);
                            break;
                        default:
                            die($tagName);
                    }
                }
                if ($this->level == 6) {
                    switch ($tagName) {
                        case 'ID':
                            $this->info->tempmeta->id = $this->getContents();
                            break;
                        case 'IDNUMBER':
                            $this->info->tempmeta->idnumber = $this->getContents();
                            break;
                        case 'SHORTNAME':
                            $this->info->tempmeta->shortname = $this->getContents();
                            break;
                    }
                }
            }

            //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($this->tree[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = '';
            $this->level--;
            $this->content = "";
        }

        //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
        function endElementGradebook($parser, $tagName) {
            //Check if we are into GRADEBOOK zone
            if ($this->tree[3] == "GRADEBOOK") {
                //if (trim($this->content))                                                             //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //We have finished preferences, letters or categories, reset accumulated
                //data because they are close tags
                if ($this->level == 4) {
                    $this->temp = "";
                }
                //If we've finished a message, xmlize it an save to db
                if (($this->level == 5) and ($tagName == "GRADE_PREFERENCE")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one PREFERENCE)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                    //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                              //Debug
                    //traverse_xmlize($data);                                                         //Debug
                    //print_object ($GLOBALS['traverse_array']);                                      //Debug
                    //$GLOBALS['traverse_array']="";                                                  //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and status from data
                    $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
                    $this->counter++;
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code, 'grade_preferences', $preference_id, 
                                           null,$data);
                    //Create returning info
                    $this->info = $this->counter;
                    //Reset temp
                    unset($this->temp);
                }
                //If we've finished a grade_letter, xmlize it an save to db
                if (($this->level == 5) and ($tagName == "GRADE_LETTER")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one LETTER)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                    //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                              //Debug
                    //traverse_xmlize($data);                                                         //Debug
                    //print_object ($GLOBALS['traverse_array']);                                      //Debug
                    //$GLOBALS['traverse_array']="";                                                  //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and status from data
                    $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
                    $this->counter++;
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code, 'grade_letter' ,$letter_id, 
                                           null,$data);
                    //Create returning info
                    $this->info = $this->counter;
                    //Reset temp
                    unset($this->temp);
                }

                //If we've finished a grade_category, xmlize it an save to db
                if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one CATECORY)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                    //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                              //Debug
                    //traverse_xmlize($data);                                                         //Debug
                    //print_object ($GLOBALS['traverse_array']);                                      //Debug
                    //$GLOBALS['traverse_array']="";                                                  //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and status from data
                    $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
                    $this->counter++;
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code, 'grade_category' ,$category_id,
                                           null,$data);
                    //Create returning info
                    $this->info = $this->counter;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "GRADEBOOK" and $this->level == 3) {
                $this->finished = true;
                $this->counter = 0;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }
        
        //This is the endTag handler we use where we are reading the users zone (todo="USERS")
        function endElementUsers($parser, $tagName) {
            //Check if we are into USERS zone
            if ($this->tree[3] == "USERS") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Dependig of different combinations, do different things
                if ($this->level == 4) {
                    switch ($tagName) {
                        case "USER":
                            //Increment counter
                            $this->counter++;
                            //Save to db
                            backup_putid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id,
                                          null,$this->info->tempuser);

                            //Do some output   
                            if ($this->counter % 10 == 0) {
                                if (!defined('RESTORE_SILENTLY')) {
                                    echo ".";
                                    if ($this->counter % 200 == 0) {
                                        echo "<br />";
                                    }
                                }
                                backup_flush(300);
                            }

                            //Delete temp obejct
                            unset($this->info->tempuser);
                            break;
                    }
                }
                if ($this->level == 5) {
                    switch ($tagName) {
                        case "ID": 
                            $this->info->users[$this->getContents()] = $this->getContents();
                            $this->info->tempuser->id = $this->getContents();
                            break;
                        case "AUTH": 
                            $this->info->tempuser->auth = $this->getContents();
                            break;
                        case "CONFIRMED": 
                            $this->info->tempuser->confirmed = $this->getContents();
                            break;
                        case "POLICYAGREED": 
                            $this->info->tempuser->policyagreed = $this->getContents();
                            break;
                        case "DELETED": 
                            $this->info->tempuser->deleted = $this->getContents();
                            break;
                        case "USERNAME": 
                            $this->info->tempuser->username = $this->getContents();
                            break;
                        case "PASSWORD": 
                            $this->info->tempuser->password = $this->getContents();
                            break;
                        case "IDNUMBER": 
                            $this->info->tempuser->idnumber = $this->getContents();
                            break;
                        case "FIRSTNAME": 
                            $this->info->tempuser->firstname = $this->getContents();
                            break;
                        case "LASTNAME": 
                            $this->info->tempuser->lastname = $this->getContents();
                            break;
                        case "EMAIL": 
                            $this->info->tempuser->email = $this->getContents();
                            break;
                        case "EMAILSTOP": 
                            $this->info->tempuser->emailstop = $this->getContents();
                            break;
                        case "ICQ": 
                            $this->info->tempuser->icq = $this->getContents();
                            break;
                        case "SKYPE": 
                            $this->info->tempuser->skype = $this->getContents();
                            break;
                        case "AIM": 
                            $this->info->tempuser->aim = $this->getContents();
                            break;
                        case "YAHOO": 
                            $this->info->tempuser->yahoo = $this->getContents();
                            break;
                        case "MSN": 
                            $this->info->tempuser->msn = $this->getContents();
                            break;
                        case "PHONE1": 
                            $this->info->tempuser->phone1 = $this->getContents();
                            break;
                        case "PHONE2": 
                            $this->info->tempuser->phone2 = $this->getContents();
                            break;
                        case "INSTITUTION": 
                            $this->info->tempuser->institution = $this->getContents();
                            break;
                        case "DEPARTMENT": 
                            $this->info->tempuser->department = $this->getContents();
                            break;
                        case "ADDRESS": 
                            $this->info->tempuser->address = $this->getContents();
                            break;
                        case "CITY": 
                            $this->info->tempuser->city = $this->getContents();
                            break;
                        case "COUNTRY": 
                            $this->info->tempuser->country = $this->getContents();
                            break;
                        case "LANG": 
                            $this->info->tempuser->lang = $this->getContents();
                            break;
                        case "THEME": 
                            $this->info->tempuser->theme = $this->getContents();
                            break;
                        case "TIMEZONE": 
                            $this->info->tempuser->timezone = $this->getContents();
                            break;
                        case "FIRSTACCESS": 
                            $this->info->tempuser->firstaccess = $this->getContents();
                            break;
                        case "LASTACCESS": 
                            $this->info->tempuser->lastaccess = $this->getContents();
                            break;
                        case "LASTLOGIN": 
                            $this->info->tempuser->lastlogin = $this->getContents();
                            break;
                        case "CURRENTLOGIN": 
                            $this->info->tempuser->currentlogin = $this->getContents();
                            break;
                        case "LASTIP": 
                            $this->info->tempuser->lastip = $this->getContents();
                            break;
                        case "SECRET": 
                            $this->info->tempuser->secret = $this->getContents();
                            break;
                        case "PICTURE": 
                            $this->info->tempuser->picture = $this->getContents();
                            break;
                        case "URL": 
                            $this->info->tempuser->url = $this->getContents();
                            break;
                        case "DESCRIPTION": 
                            $this->info->tempuser->description = $this->getContents();
                            break;
                        case "MAILFORMAT": 
                            $this->info->tempuser->mailformat = $this->getContents();
                            break;
                        case "MAILDIGEST": 
                            $this->info->tempuser->maildigest = $this->getContents();
                            break;
                        case "MAILDISPLAY": 
                            $this->info->tempuser->maildisplay = $this->getContents();
                            break;
                        case "HTMLEDITOR": 
                            $this->info->tempuser->htmleditor = $this->getContents();
                            break;
                        case "AUTOSUBSCRIBE": 
                            $this->info->tempuser->autosubscribe = $this->getContents();
                            break;
                        case "TRACKFORUMS": 
                            $this->info->tempuser->trackforums = $this->getContents();
                            break;
                        case "TIMEMODIFIED": 
                            $this->info->tempuser->timemodified = $this->getContents();
                            break;
                    }
                }
                if ($this->level == 6) {
                    switch ($tagName) {
                        case "ROLE":
                            //We've finalized a role, get it
                            $this->info->tempuser->roles[$this->info->temprole->type] = $this->info->temprole;
                            unset($this->info->temprole);
                            break;
                        case "USER_PREFERENCE":
                            //We've finalized a user_preference, get it
                            $this->info->tempuser->user_preferences[$this->info->tempuserpreference->name] = $this->info->tempuserpreference;
                            unset($this->info->tempuserpreference);
                            break;
                    }
                }
                if ($this->level == 7) {
                    switch ($tagName) {
                        case "TYPE":
                            $this->info->temprole->type = $this->getContents();
                            break;
                        case "AUTHORITY":
                            $this->info->temprole->authority = $this->getContents();
                            break;
                        case "TEA_ROLE":
                            $this->info->temprole->tea_role = $this->getContents();
                            break;
                        case "EDITALL":
                            $this->info->temprole->editall = $this->getContents();
                            break;
                        case "TIMESTART":
                            $this->info->temprole->timestart = $this->getContents();
                            break;
                        case "TIMEEND":
                            $this->info->temprole->timeend = $this->getContents();
                            break;
                        case "TIMEMODIFIED":
                            $this->info->temprole->timemodified = $this->getContents();
                            break;
                        case "TIMESTART":
                            $this->info->temprole->timestart = $this->getContents();
                            break;
                        case "TIMEEND":
                            $this->info->temprole->timeend = $this->getContents();
                            break;
                        case "TIME":
                            $this->info->temprole->time = $this->getContents();
                            break;
                        case "TIMEACCESS":
                            $this->info->temprole->timeaccess = $this->getContents();
                            break;
                        case "ENROL":
                            $this->info->temprole->enrol = $this->getContents();
                            break;
                        case "NAME":
                            $this->info->tempuserpreference->name = $this->getContents();
                            break;
                        case "VALUE":
                            $this->info->tempuserpreference->value = $this->getContents();
                            break;
                    }
                }
            }

            //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "USERS" and $this->level == 3) {
                $this->finished = true;
                $this->counter = 0;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
        function endElementMessages($parser, $tagName) {
            //Check if we are into MESSAGES zone
            if ($this->tree[3] == "MESSAGES") {
                //if (trim($this->content))                                                             //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a message, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "MESSAGE")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one MESSAGE)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                    //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                              //Debug
                    //traverse_xmlize($data);                                                         //Debug
                    //print_object ($GLOBALS['traverse_array']);                                      //Debug
                    //$GLOBALS['traverse_array']="";                                                  //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and status from data
                    $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
                    $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
                    if ($message_status == "READ") {
                        $table = "message_read";
                    } else {
                        $table = "message";
                    }
                    $this->counter++;
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code, $table,$message_id, 
                                           null,$data);
                    //Create returning info
                    $this->info = $this->counter;
                    //Reset temp
                    unset($this->temp);
                }
                //If we've finished a contact, xmlize it an save to db
                if (($this->level == 5) and ($tagName == "CONTACT")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one MESSAGE)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                    //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                              //Debug
                    //traverse_xmlize($data);                                                         //Debug
                    //print_object ($GLOBALS['traverse_array']);                                      //Debug
                    //$GLOBALS['traverse_array']="";                                                  //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and status from data
                    $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
                    $this->counter++;
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code, 'message_contacts' ,$contact_id, 
                                           null,$data);
                    //Create returning info
                    $this->info = $this->counter;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "MESSAGES" and $this->level == 3) {
                $this->finished = true;
                $this->counter = 0;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")  
        function endElementQuestions($parser, $tagName) {
            //Check if we are into QUESTION_CATEGORIES zone
            if ($this->tree[3] == "QUESTION_CATEGORIES") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a mod, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "QUESTION_CATEGORY")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                                          //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id from data
                    $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code,"question_categories",$category_id,
                                     null,$data);
                    //Create returning info
                    $ret_info->id = $category_id;
                    $this->info[] = $ret_info;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "QUESTION_CATEGORIES" and $this->level == 3) {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
        function endElementScales($parser, $tagName) {
            //Check if we are into SCALES zone
            if ($this->tree[3] == "SCALES") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a scale, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "SCALE")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one SCALE)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                                          //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and from data
                    $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code,"scale",$scale_id,
                                     null,$data);
                    //Create returning info
                    $ret_info->id = $scale_id;
                    $this->info[] = $ret_info;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "SCALES" and $this->level == 3) {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
        function endElementGroups($parser, $tagName) {
            //Check if we are into GROUPS zone
            if ($this->tree[3] == "GROUPS") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a group, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "GROUP")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one GROUP)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                                          //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and from data
                    $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code,"groups",$group_id,
                                     null,$data);
                    //Create returning info
                    $ret_info->id = $group_id;
                    $this->info[] = $ret_info;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "GROUPS" and $this->level == 3) {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
        function endElementEvents($parser, $tagName) {
            //Check if we are into EVENTS zone
            if ($this->tree[3] == "EVENTS") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a event, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "EVENT")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one EVENT)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                                          //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and from data
                    $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
                    //Save to db
                    $status = backup_putid($this->preferences->backup_unique_code,"event",$event_id,
                                     null,$data);
                    //Create returning info
                    $ret_info->id = $event_id;
                    $this->info[] = $ret_info;
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "EVENTS" and $this->level == 3) {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
        function endElementModules($parser, $tagName) {
            //Check if we are into MODULES zone
            if ($this->tree[3] == "MODULES") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a mod, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "MOD")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one MOD)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                  //Debug
                    $data = xmlize($xml_data,0);         
                    //echo strftime ("%X",time())."<p>";                                                            //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and modtype from data
                    $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
                    $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
                    //Only if we've selected to restore it
                    if  ($this->preferences->mods[$mod_type]->restore) {
                        //Save to db
                        $status = backup_putid($this->preferences->backup_unique_code,$mod_type,$mod_id,
                                     null,$data);
                        //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>";   //Debug
                        //Create returning info
                        $ret_info->id = $mod_id;
                        $ret_info->modtype = $mod_type;
                        $this->info[] = $ret_info;
                    }
                    //Reset temp
                    unset($this->temp);
                }
            }



            //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "MODULES" and $this->level == 3) {
                $this->finished = true;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
        function endElementLogs($parser, $tagName) {
            //Check if we are into LOGS zone
            if ($this->tree[3] == "LOGS") {
                //if (trim($this->content))                                                                     //Debug
                //    echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
                //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug
                //Acumulate data to info (content + close tag)
                //Reconvert: strip htmlchars again and trim to generate xml data
                if (!isset($this->temp)) {
                    $this->temp = "";
                }
                $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
                //If we've finished a log, xmlize it an save to db
                if (($this->level == 4) and ($tagName == "LOG")) {
                    //Prepend XML standard header to info gathered
                    $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
                    //Call to xmlize for this portion of xml data (one LOG)
                    //echo "-XMLIZE: ".strftime ("%X",time()),"-";                                                //Debug
                    $data = xmlize($xml_data,0);
                    //echo strftime ("%X",time())."<p>";                                                          //Debug
                    //traverse_xmlize($data);                                                                     //Debug
                    //print_object ($GLOBALS['traverse_array']);                                                  //Debug
                    //$GLOBALS['traverse_array']="";                                                              //Debug
                    //Now, save data to db. We'll use it later
                    //Get id and modtype from data
                    $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
                    $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
                    //We only save log entries from backup file if they are:
                    // - Course logs
                    // - User logs
                    // - Module logs about one restored module
                    if  ($log_module == "course" or
                         $log_module == "user" or
                        $this->preferences->mods[$log_module]->restore) {
                        //Increment counter
                        $this->counter++;
                        //Save to db
                        $status = backup_putid($this->preferences->backup_unique_code,"log",$log_id,
                                     null,$data);
                        //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>";   //Debug
                        //Create returning info
                        $this->info = $this->counter;
                    }
                    //Reset temp
                    unset($this->temp);
                }
            }

            //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
            //Speed up a lot (avoid parse all)
            if ($tagName == "LOGS" and $this->level == 3) {
                $this->finished = true;
                $this->counter = 0;
            }

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";

        }

        //This is the endTag default handler we use when todo is undefined
        function endElement($parser, $tagName) {
            if (trim($this->content))                                                                     //Debug
                echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n";           //Debug
            echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";          //Debug

            //Clear things
            $this->tree[$this->level] = "";
            $this->level--;
            $this->content = "";
        }

        //This is the handler to read data contents (simple accumule it)
        function characterData($parser, $data) {
            $this->content .= $data;
        }
    }
    
    //This function executes the MoodleParser
    function restore_read_xml ($xml_file,$todo,$preferences) {
        
        $status = true;

        $xml_parser = xml_parser_create('UTF-8');
        $moodle_parser = new MoodleParser();
        $moodle_parser->todo = $todo;
        $moodle_parser->preferences = $preferences;
        xml_set_object($xml_parser,$moodle_parser);
        //Depending of the todo we use some element_handler or another
        if ($todo == "INFO") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
        } else if ($todo == "COURSE_HEADER") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
        } else if ($todo == 'BLOCKS') {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
        } else if ($todo == "SECTIONS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
        } else if ($todo == "METACOURSE") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
        } else if ($todo == "GRADEBOOK") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
        } else if ($todo == "USERS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
        } else if ($todo == "MESSAGES") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
        } else if ($todo == "QUESTIONS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
        } else if ($todo == "SCALES") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
        } else if ($todo == "GROUPS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
        } else if ($todo == "EVENTS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
        } else if ($todo == "MODULES") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
        } else if ($todo == "LOGS") {
            //Define handlers to that zone
            xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
        } else {
            //Define default handlers (must no be invoked when everything become finished)
            xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
        }
        xml_set_character_data_handler($xml_parser, "characterData");
        $fp = fopen($xml_file,"r")
            or $status = false;
        if ($status) {
            while ($data = fread($fp, 4096) and !$moodle_parser->finished)
                    xml_parse($xml_parser, $data, feof($fp))
                            or die(sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                                    xml_get_current_line_number($xml_parser)));
            fclose($fp);
        }
        //Get info from parser
        $info = $moodle_parser->info;

        //Clear parser mem
        xml_parser_free($xml_parser);

        if ($status && !empty($info)) {
            return $info;
        } else {
            return $status;
        }
    }

    /**
     * @param string $errorstr passed by reference, if silent is true,
     * errorstr will be populated and this function will return false rather than calling error() or notify()
     * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or 
     * redirect to the next step in the restore process, instead will return $backup_unique_code
     */
    function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
        
        global $CFG, $SESSION;

        //Prepend dataroot to variable to have the absolute path
        $file = $CFG->dataroot."/".$file;
        
        if (!defined('RESTORE_SILENTLY')) {
            //Start the main table
            echo "<table cellpadding=\"5\">";
            echo "<tr><td>";
            
            //Start the mail ul
            echo "<ul>";
        }

        //Check the file exists 
        if (!is_file($file)) {
            if (!defined('RESTORE_SILENTLY')) {
                error ("File not exists ($file)");
            } else {
                $errorstr = "File not exists ($file)";
                return false;
            }
        }
        
        //Check the file name ends with .zip
        if (!substr($file,-4) == ".zip") {
            if (!defined('RESTORE_SILENTLY')) {
                error ("File has an incorrect extension");
            } else {
                $errorstr = 'File has an incorrect extension';
                return false;
            }
        }
        
        //Now calculate the unique_code for this restore
        $backup_unique_code = time();
        
        //Now check and create the backup dir (if it doesn't exist)
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>".get_string("creatingtemporarystructures").'</li>';
        }
        $status = check_and_create_backup_dir($backup_unique_code);
        //Empty dir
        if ($status) {
            $status = clear_backup_dir($backup_unique_code);
        }
        
        //Now delete old data and directories under dataroot/temp/backup
        if ($status) {   
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("deletingolddata").'</li>';
            }
            $status = backup_delete_old_data();
        }
        
        //Now copy he zip file to dataroot/temp/backup/backup_unique_code
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("copyingzipfile").'</li>';
            }
            if (! $status = backup_copy_file($file,$CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error copying backup file. Invalid name or bad perms.");
                } else {
                    $errorstr = "Error copying backup file. Invalid name or bad perms";
                    return false;
                }
            }
        }
        
        //Now unzip the file
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("unzippingbackup").'</li>';
            }
            if (! $status = restore_unzip ($CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error unzipping backup file. Invalid zip file.");
                } else {
                    $errorstr = "Error unzipping backup file. Invalid zip file.";
                    return false;
                }
            }
        }

        //Check for Blackboard backups and convert
        if ($status){
            require_once("$CFG->dirroot/backup/bb/restore_bb.php");
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("checkingforbbexport");
            }
            $status = blackboard_convert($CFG->dataroot."/temp/backup/".$backup_unique_code);
        }
        
        //Now check for the moodle.xml file
        if ($status) {
            $xml_file  = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("checkingbackup").'</li>';
            }
            if (! $status = restore_check_moodle_file ($xml_file)) {
                if (!is_file($xml_file)) {
                    $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
                } else {
                    $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
                }
                if (!defined('RESTORE_SILENTLY')) {
                    notify($errorstr);
                } else {
                    return false;
                }
            }
        }
        
        $info = "";
        $course_header = "";
        
        //Now read the info tag (all)
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("readinginfofrombackup").'</li>';
            }
            //Reading info from file
            $info = restore_read_xml_info ($xml_file);
            //Reading course_header from file
            $course_header = restore_read_xml_course_header ($xml_file);
        }
        
        if (!defined('RESTORE_SILENTLY')) {
            //End the main ul
            echo "</ul>";
            
            //End the main table
            echo "</td></tr>";
            echo "</table>";
        }
        
        //We compare Moodle's versions
        if ($CFG->version < $info->backup_moodle_version && $status) {
            $message->serverversion = $CFG->version;
            $message->serverrelease = $CFG->release;
            $message->backupversion = $info->backup_moodle_version;
            $message->backuprelease = $info->backup_moodle_release;
            print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
            
        }
        
        //Now we print in other table, the backup and the course it contains info
        if ($info and $course_header and $status) {
            //First, the course info
            if (!defined('RESTORE_SILENTLY')) {
                $status = restore_print_course_header($course_header);
            }
            //Now, the backup info
            if ($status) {
                if (!defined('RESTORE_SILENTLY')) {
                    $status = restore_print_info($info);
                }
            }
        }
        
        //Save course header and info into php session
        if ($status) {
            $SESSION->info = $info;
            $SESSION->course_header = $course_header;
        }
        
        //Finally, a little form to continue
        //with some hidden fields
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<br /><center>";
                $hidden["backup_unique_code"] = $backup_unique_code;
                $hidden["launch"]             = "form";
                $hidden["file"]               =  $file;
                $hidden["id"]                 =  $id;
                print_single_button("restore.php", $hidden, get_string("continue"),"post");
                echo "</center>";
            }
            else {
                if (empty($noredirect)) {
                    redirect($CFG->wwwroot.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
                } else {
                    return $backup_unique_code;
                }
            }
        }
        
        if (!$status) {
            if (!defined('RESTORE_SILENTLY')) {
                error ("An error has ocurred");
            } else {
                $errorstr = "An error has occured"; // helpful! :P
                return false;
            }
        }
        return true;
    }

    function restore_setup_for_check(&$restore,$backup_unique_code) {
        global $SESSION;
        $restore->backup_unique_code=$backup_unique_code;
        $restore->users = 2; // yuk
        $restore->course_files = $SESSION->restore->restore_course_files;
        if ($allmods = get_records("modules")) {
            foreach ($allmods as $mod) {
                $modname = $mod->name;
                $var = "restore_".$modname;
                //Now check that we have that module info in the backup file
                if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
                    $restore->$var = 1; 
                }
            }
        }
        return true;
    }

    function backup_to_restore_array($backup,$k=0) {
        if (is_array($backup) ) {
            foreach ($backup as $key => $value) {
                $newkey = str_replace('backup','restore',$key);
                $restore[$newkey] = backup_to_restore_array($value,$key);
            }
        }
        else if (is_object($backup)) { 
            $tmp = get_object_vars($backup);
            foreach ($tmp as $key => $value) {
                $newkey = str_replace('backup','restore',$key);
                $restore->$newkey = backup_to_restore_array($value,$key);   
            }
        }
        else {
            $newkey = str_replace('backup','restore',$k);
            $restore = $backup;
        }
        return $restore;
    }

    /** 
     * compatibility function
     * checks for per-instance backups AND 
     * older per-module backups
     * and returns whether userdata has been selected.
     */
    function restore_userdata_selected($restore,$modname,$modid) {
        // check first for per instance array
        if (!empty($restore->mods[$modname]->instances)) { // supports per instance
            return array_key_exists($modid,$restore->mods[$modname]->instances) 
                && !empty($restore->mods[$modname]->instances[$modid]->userinfo);
        }
        return !empty($restore->mods[$modname]->userinfo);
    }

    function restore_execute(&$restore,$info,$course_header,&$errorstr) {
        global $CFG, $USER;
        $status = true;
        //Checks for the required files/functions to restore every module
        //and include them
        if ($allmods = get_records("modules") ) {
            foreach ($allmods as $mod) {
                $modname = $mod->name;
                $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
                //If file exists and we have selected to restore that type of module
                if ((file_exists($modfile)) and ($restore->mods[$modname]->restore)) {
                    include_once($modfile);
                }
            }
        }

        if (!defined('RESTORE_SILENTLY')) {
            //Start the main table
            echo "<table cellpadding=\"5\">";
            echo "<tr><td>";
            
            //Start the main ul
            echo "<ul>";
        }
        
        //Localtion of the xml file
        $xml_file  = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml";
        
        //If we've selected to restore into new course
        //create it (course)
        //Saving conversion id variables into backup_tables
        if ($restore->restoreto == 2) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingnewcourse");
            }
            $oldidnumber = $course_header->course_idnumber;
            if (!$status = restore_create_new_course($restore,$course_header)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error while creating the new empty course.");
                } else {
                    $errorstr = "Error while creating the new empty course.";
                    return false;
                }
            }
            
            //Print course fullname and shortname and category
            if ($status) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<ul>";
                    echo "<li>".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
                    echo "<li>".get_string("category").": ".$course_header->category->name.'</li>';
                    if (!empty($oldidnumber)) {
                        echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
                    }
                    echo "</ul></li>";
                    //Put the destination course_id
                }
                $restore->course_id = $course_header->course_id;
            }
        } else {
            $course = get_record("course","id",$restore->course_id);
            if ($course) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<li>".get_string("usingexistingcourse"); 
                    echo "<ul>";
                    echo "<li>".get_string("from").": ".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
                    echo "<li>".get_string("to").": ".$course->fullname." (".$course->shortname.")".'</li>';
                    if (($restore->deleting)) {
                        echo "<li>".get_string("deletingexistingcoursedata").'</li>';
                    } else {
                        echo "<li>".get_string("addingdatatoexisting").'</li>';
                    }
                    echo "</ul></li>";
                }
                //If we have selected to restore deleting, we do it now.
                if ($restore->deleting) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo "<li>".get_string("deletingolddata").'</li>';
                    }
                    $status = remove_course_contents($restore->course_id,false) and 
                        delete_dir_contents($CFG->dataroot."/".$restore->course_id,"backupdata");
                    if ($status) {
                        //Now , this situation is equivalent to the "restore to new course" one (we
                        //have a course record and nothing more), so define it as "to new course"
                        $restore->restoreto = 2;
                    } else {
                        if (!defined('RESTORE_SILENTLY')) {
                            notify("An error occurred while deleting some of the course contents.");
                        } else {
                            $errrostr = "An error occurred while deleting some of the course contents.";
                            return false;
                        }
                    }
                }
            } else {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error opening existing course.");
                    $status = false;
                } else {
                    $errorstr = "Error opening existing course.";
                    return false;
                }
            }
        }
        
        //Now create the course_sections and their associated course_modules
        if ($status) {
            //Into new course
            if ($restore->restoreto == 2) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<li>".get_string("creatingsections").'</li>';
                }
                if (!$status = restore_create_sections($restore,$xml_file)) {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("Error creating sections in the existing course.");
                    } else {
                        $errorstr = "Error creating sections in the existing course.";
                        return false;
                    }
                }
                //Into existing course
            } else if ($restore->restoreto == 0 or $restore->restoreto == 1) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<li>".get_string("checkingsections").'</li>';
                }
                if (!$status = restore_create_sections($restore,$xml_file)) {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("Error creating sections in the existing course.");
                    } else {
                        $errorstr = "Error creating sections in the existing course.";
                        return false;
                    } 
                }
                //Error
            } else {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Neither a new course or an existing one was specified.");
                    $status = false;
                } else {
                    $errorstr = "Neither a new course or an existing one was specified.";
                    return false;
                }
            }
        }

        //Now create users as needed 
        if ($status and ($restore->users == 0 or $restore->users == 1)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingusers")."<br />";
            }
            if (!$status = restore_create_users($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore users.");
                } else {
                    $errorstr = "Could not restore users.";
                    return false;
                }
            }
            //Now print info about the work done
            if ($status) {
                $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
                                     where backup_code = '$restore->backup_unique_code' and
                                     table_name = 'user'");
                //We've records
                if ($recs) {
                    $new_count = 0;
                    $exists_count = 0;
                    $student_count = 0;
                    $teacher_count = 0;
                    $counter = 0;
                    //Iterate, filling counters
                    foreach ($recs as $rec) {
                        //Get full record, using backup_getids
                        $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id);
                        if (strpos($record->info,"new") !== false) {
                            $new_count++;
                        } 
                        if (strpos($record->info,"exists") !== false) {
                            $exists_count++;
                        }
                        if (strpos($record->info,"student") !== false) {
                            $student_count++;
                        } else if (strpos($record->info,"teacher") !== false) {
                            $teacher_count++;
                        }
                        //Do some output
                        $counter++;
                        if ($counter % 10 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 200 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                    if (!defined('RESTORE_SILENTLY')) {
                        //Now print information gathered
                        echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
                        echo "<ul>";
                        echo "<li>".get_string("students").": ".$student_count.'</li>';
                        echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
                        echo "</ul>";
                    }
                } else {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("No users were found!");
                    } // no need to return false here, it's recoverable.
                }
            }
        }
        
        //Now create metacourse info
        if ($status and $restore->metacourse) {
            //Only to new courses!
            if ($restore->restoreto == 2) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "</li><li>".get_string("creatingmetacoursedata");
                }
                if (!$status = restore_create_metacourse($restore,$xml_file)) {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("Error creating metacourse in the course.");
                    } else {
                        $errorstr = "Error creating metacourse in the course.";
                        return false;
                    }
                }
            }
        }
        

        //Now create categories and questions as needed
        if ($status and ($restore->mods['quiz']->restore)) {
            include_once("$CFG->dirroot/question/restorelib.php");
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li><li>".get_string("creatingcategoriesandquestions");
                echo "<ul>";
            }
            if (!$status = restore_create_questions($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore categories and questions!");
                } else {
                    $errorstr = "Could not restore categories and questions!";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo "</ul></li>";
            }
        }

        //Now create user_files as needed
        if ($status and ($restore->user_files)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("copyinguserfiles");
            }
            if (!$status = restore_user_files($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore user files!");
                } else {
                    $errorstr = "Could not restore user files!";
                    return false;
                }
            }
            //If all is ok (and we have a counter)
            if ($status and ($status !== true)) {
                //Inform about user dirs created from backup
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<ul>";
                    echo "<li>".get_string("userzones").": ".$status;
                    echo "</li></ul>";
                }
            }
        }

        //Now create course files as needed
        if ($status and ($restore->course_files)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li><li>".get_string("copyingcoursefiles")."</li>";
            }
            if (!$status = restore_course_files($restore)) {
                if (empty($status)) {
                    notify("Could not restore course files!");
                } else {
                    $errorstr = "Could not restore course files!";
                    return false;
                }
            }
            //If all is ok (and we have a counter)
            if ($status and ($status !== true)) {
                //Inform about user dirs created from backup
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<ul>";
                    echo "<li>".get_string("filesfolders").": ".$status;
                    echo "</ul>";
                }       
            }
        }

        //Now create messages as needed
        if ($status and ($restore->messages)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingmessagesinfo");
            }
            if (!$status = restore_create_messages($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore messages!");
                } else {
                    $errorstr = "Could not restore messages!";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li>";
            }
        }

        //Now create scales as needed
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingscales").'</li>';
            }
            if (!$status = restore_create_scales($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore custom scales!");
                } else {
                    $errorstr = "Could not restore custom scales!";
                    return false;
                }
            }
        }

        //Now create groups as needed
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatinggroups").'</li>';
            }
            if (!$status = restore_create_groups($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore groups!");
                } else {
                    $errorstr = "Could not restore groups!";
                    return false;
                }
            }
        }
        
        //Now create events as needed
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingevents").'</li>';
            }
            if (!$status = restore_create_events($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore course events!");
                } else {
                    $errorstr = "Could not restore course events!";
                    return false;
                }
            }
        }

        //Now create course modules as needed
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatingcoursemodules");
            } 
            if (!$status = restore_create_modules($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore modules!");
                } else {
                    $errorstr = "Could not restore modules!";
                    return false;
                }
            }
        }

        //Now create gradebook as needed -- AFTER modules!!!
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("creatinggradebook");
            } 
            if (!$status = restore_create_gradebook($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore gradebook!");
                } else {
                    $errorstr = "Could not restore gradebook!";
                    return false;
                }
            }
        }

        //Bring back the course blocks -- do it AFTER the modules!!!
        if($status) {
            //If we are deleting and bringing into a course or making a new course, same situation
            if($restore->restoreto == 0 || $restore->restoreto == 2) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo '<li>'.get_string('creatingblocks').'</li>';
                }
                $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
                if (!$status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file)) {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify('Error while creating the course blocks');
                    } else {
                        $errorstr = "Error while creating the course blocks";
                        return false;
                    }
                }
            }
        }

        //Now create log entries as needed
        if ($status and ($restore->logs)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li><li>".get_string("creatinglogentries");
            }
            if (!$status = restore_create_logs($restore,$xml_file)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore logs!");
                } else {
                    $errorstr = "Could not restore logs!";
                    return false;
                }
            }
        }    

        //Now, if all is OK, adjust the instance field in course_modules !!
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li><li>".get_string("checkinginstances").'</li>';
            }
            if (!$status = restore_check_instances($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not adjust instances in course_modules!");
                } else {
                    $errorstr = "Could not adjust instances in course_modules!";
                    return false;
                }
            }
        }

        //Now, if all is OK, adjust activity events
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("refreshingevents").'</li>';
            }
            if (!$status = restore_refresh_events($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not refresh events for activities!");
                } else {
                    $errorstr = "Could not refresh events for activities!";
                    return false;
                }
            }
        }

        //Now, if all is OK, adjust inter-activity links
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("decodinginternallinks");
            }
            if (!$status = restore_decode_content_links($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not refresh events for activities!");
                } else {
                    $errorstr = "Could not refresh events for activities!";
                    return false;
                }
            }
        }

        //Now, with backup files prior to version 2005041100,
        //convert all the wiki texts in the course to markdown
        if ($status && $restore->backup_version < 2005041100) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("convertingwikitomarkdown");
            }
            if (!$status = restore_convert_wiki2markdown($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not convert wiki texts to markdown!");
                } else {
                    $errorstr = "Could not convert wiki texts to markdown!";
                    return false;
                }
            }
        }

        //Now if all is OK, update:
        //   - course modinfo field 
        //   - categories table
        //   - add user as teacher
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "</li><li>".get_string("checkingcourse").'</li>';
            } 
            //modinfo field
            rebuild_course_cache($restore->course_id);
            //categories table
            $course = get_record("course","id",$restore->course_id); 
            fix_course_sortorder();
            //Make the user a teacher if the course hasn't teachers (bug 2381)
            if (!isadmin()) {
                if (!$checktea = get_records('user_teachers','course', $restore->course_id)) {
                    //Add the teacher to the course
                    $status = add_teacher($USER->id, $restore->course_id);
                }
            }
        }

        //Cleanup temps (files and db)
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("cleaningtempdata").'</li>';
            }
            if (!$status = clean_temp_data ($restore)) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not clean up temporary data from files and database");
                } else {
                    $errorstr = "Could not clean up temporary data from files and database";
                    return false;
                }
            }
        }

        if (!defined('RESTORE_SILENTLY')) {
            //End the main ul
            echo "</ul>";
            
            //End the main table     
            echo "</td></tr>";
            echo "</table>";
        }

        return $status;
    }

?>