backup.php 191 KB
Newer Older
alain's avatar
alain committed
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
<?php

if (!defined('UPDRAFTPLUS_DIR')) die('No direct access allowed');
if (!class_exists('UpdraftPlus_PclZip')) require_once(UPDRAFTPLUS_DIR.'/includes/class-zip.php');

/**
 * This file contains code that is only needed/loaded when a backup is running
 */
class UpdraftPlus_Backup {

	private $index = 0;

	private $manifest_path;

	private $zipfiles_added;

	private $zipfiles_added_thisrun = 0;

	public $zipfiles_dirbatched;

	public $zipfiles_batched;

	public $zipfiles_skipped_notaltered;

	private $zip_split_every = 419430400; // 400MB

	private $zip_last_ratio = 1;

	private $whichone;

	private $zip_basename = '';

	private $backup_basename = '';

	private $zipfiles_lastwritetime;

	// 0 = unknown; false = failed
	public $binzip = 0;

	private $dbhandle;

	private $dbhandle_isgz;

	// Array of entities => times
	private $altered_since = -1;

	// Time for the current entity
	private $makezip_if_altered_since = -1;

	private $excluded_extensions = false;

	private $use_zip_object = 'UpdraftPlus_ZipArchive';

	public $debug = false;

	public $updraft_dir;

	private $site_name;

	private $wpdb_obj;

	private $job_file_entities = array();

	private $first_run = 0;

	// Record of zip files created
	private $backup_files_array = array();

	// Used when deciding to use the 'store' or 'deflate' zip storage method
	private $extensions_to_not_compress = array();

	// Append to this any skipped tables
	private $skipped_tables;
	
	// When initialised, a boolean
	public $last_storage_instance;
	
	// The absolute upper limit that will be considered for a zip batch (in bytes)
	private $zip_batch_ceiling;

	private $backup_excluded_patterns = array();
	
	// Bytes of uncompressed data written since last open
	private $db_current_raw_bytes = 0;
	
	private $table_prefix;

	private $table_prefix_raw;
	
	/**
	 * Class constructor
	 *
	 * @param Array|String $backup_files  - files to backup, or (string)'no'
	 * @param Integer	   $altered_since - only backup files altered since this time (UNIX epoch time)
	 */
	public function __construct($backup_files, $altered_since = -1) {

		global $updraftplus;

		$this->site_name = $this->get_site_name();

		// Decide which zip engine to begin with
		$this->debug = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode');
		$this->updraft_dir = $updraftplus->backups_dir_location();
		$this->updraft_dir_realpath = realpath($this->updraft_dir);

		require_once(UPDRAFTPLUS_DIR.'/includes/class-database-utility.php');

		if ('no' === $backup_files) {
			$this->use_zip_object = 'UpdraftPlus_PclZip';
			return;
		}

		$this->extensions_to_not_compress = array_unique(array_map('strtolower', array_map('trim', explode(',', UPDRAFTPLUS_ZIP_NOCOMPRESS))));

		$this->backup_excluded_patterns = array(
			array(
				// all in one wp migration pattern: WP_PLUGIN_DIR/all-in-one-wp-migration/storage/*/*.wpress, `ai1wm-backups` folder in wp-content is already implicitly handled on the UDP settings with a `*backups` predefined exclusion rule for `others` directory
				'directory' => realpath(WP_PLUGIN_DIR).DIRECTORY_SEPARATOR.'all-in-one-wp-migration'.DIRECTORY_SEPARATOR.'storage',
				'regex' => '/.+\.wpress$/is',
			),
		);

		$this->altered_since = $altered_since;

		$resumptions_since_last_successful = $updraftplus->current_resumption - $updraftplus->last_successful_resumption;
		
		// false means 'tried + failed'; whereas 0 means 'not yet tried'
		// Disallow binzip on OpenVZ when we're not sure there's plenty of memory
		if (0 === $this->binzip && (!defined('UPDRAFTPLUS_PREFERPCLZIP') || !UPDRAFTPLUS_PREFERPCLZIP) && (!defined('UPDRAFTPLUS_NO_BINZIP') || !UPDRAFTPLUS_NO_BINZIP) && ($updraftplus->current_resumption < 9 || $resumptions_since_last_successful < 2)) {

			if (@file_exists('/proc/user_beancounters') && @file_exists('/proc/meminfo') && @is_readable('/proc/meminfo')) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
				$meminfo = @file_get_contents('/proc/meminfo', false, null, 0, 200);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
				if (is_string($meminfo) && preg_match('/MemTotal:\s+(\d+) kB/', $meminfo, $matches)) {
					$memory_mb = $matches[1]/1024;
					// If the report is of a large amount, then we're probably getting the total memory on the hypervisor (this has been observed), and don't really know the VPS's memory
					$vz_log = "OpenVZ; reported memory: ".round($memory_mb, 1)." MB";
					if ($memory_mb < 1024 || $memory_mb > 8192) {
						$openvz_lowmem = true;
						$vz_log .= " (will not use BinZip)";
					}
					$updraftplus->log($vz_log);
				}
			}
			if (empty($openvz_lowmem)) {
				$updraftplus->log('Checking if we have a zip executable available');
				$binzip = $updraftplus->find_working_bin_zip();
				if (is_string($binzip)) {
					$updraftplus->log("Zip engine: found/will use a binary zip: $binzip");
					$this->binzip = $binzip;
					$this->use_zip_object = 'UpdraftPlus_BinZip';
				}
			}
		}

		// In tests, PclZip was found to be 25% slower than ZipArchive
		if ('UpdraftPlus_PclZip' != $this->use_zip_object && empty($this->binzip) && ((defined('UPDRAFTPLUS_PREFERPCLZIP') && UPDRAFTPLUS_PREFERPCLZIP == true) || !class_exists('ZipArchive') || !class_exists('UpdraftPlus_ZipArchive') || (!extension_loaded('zip') && !method_exists('ZipArchive', 'AddFile')))) {
			global $updraftplus;
			$updraftplus->log("Zip engine: ZipArchive (a.k.a. php-zip) is not available or is disabled (will use PclZip (much slower) if needed)");
			$this->use_zip_object = 'UpdraftPlus_PclZip';
		}
		
		$this->zip_batch_ceiling = (defined('UPDRAFTPLUS_ZIP_BATCH_CEILING') && UPDRAFTPLUS_ZIP_BATCH_CEILING > 104857600) ? UPDRAFTPLUS_ZIP_BATCH_CEILING : 200 * 1048576;

		add_filter('updraftplus_exclude_file', array($this, 'backup_exclude_file'), 10, 2);

	}

	/**
	 * Get a site name suitable for use in the backup filename
	 *
	 * @return String
	 */
	private function get_site_name() {
		// Get the blog name and rip out known-problematic characters. Remember that we may need to be able to upload this to any FTP server or cloud storage, where filename support may be unknown
		$site_name = str_replace('__', '_', preg_replace('/[^A-Za-z0-9_]/', '', str_replace(' ', '_', substr(get_bloginfo(), 0, 32))));
		if (!$site_name || preg_match('#^_+$#', $site_name)) {
			// Try again...
			$parsed_url = parse_url(home_url(), PHP_URL_HOST);
			$parsed_subdir = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
			if ($parsed_subdir && '/' != $parsed_subdir) $parsed_url .= str_replace(array('/', '\\'), '_', $parsed_subdir);
			$site_name = str_replace('__', '_', preg_replace('/[^A-Za-z0-9_]/', '', str_replace(' ', '_', substr($parsed_url, 0, 32))));
			if (!$site_name || preg_match('#^_+$#', $site_name)) $site_name = 'WordPress_Backup';
		}

		// Allow an over-ride. Careful about introducing characters not supported by your filesystem or cloud storage.
		return apply_filters('updraftplus_blog_name', $site_name);
	}

	/**
	 * Public, because called from the 'More Files' add-on
	 *
	 * @param String|Array	  $create_from_dir      Directory/ies to create the zip
	 * @param String		  $whichone             Entity being backed up (e.g. 'plugins', 'uploads')
	 * @param String		  $backup_file_basename Name of backup file
	 * @param Integer		  $index                Index of zip in the sequence
	 * @param Integer|Boolean $first_linked_index   First linked index in the sequence, or false
	 *
	 * @return Boolean
	 */
	public function create_zip($create_from_dir, $whichone, $backup_file_basename, $index, $first_linked_index = false) {
		// Note: $create_from_dir can be an array or a string
		
		set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
		
		$original_index = $index;

		$this->index = $index;
		$this->first_linked_index = (false === $first_linked_index) ? 0 : $first_linked_index;
		$this->whichone = $whichone;

		global $updraftplus;

		$this->zip_split_every = max((int) $updraftplus->jobdata_get('split_every'), UPDRAFTPLUS_SPLIT_MIN)*1048576;

		if ('others' != $whichone) $updraftplus->log("Beginning creation of dump of $whichone (split every: ".round($this->zip_split_every/1048576, 1)." MB)");

		if (is_string($create_from_dir) && !file_exists($create_from_dir)) {
			$flag_error = true;
			$updraftplus->log("Does not exist: $create_from_dir");
			if ('mu-plugins' == $whichone) {
				if (!function_exists('get_mu_plugins')) include_once(ABSPATH.'wp-admin/includes/plugin.php');
				$mu_plugins = get_mu_plugins();
				if (count($mu_plugins) == 0) {
					$updraftplus->log("There appear to be no mu-plugins to backup. Will not raise an error.");
					$flag_error = false;
				}
			}
			if ($flag_error) $updraftplus->log(sprintf(__("%s - could not back this entity up; the corresponding directory does not exist (%s)", 'updraftplus'), $whichone, $create_from_dir), 'error');
			return false;
		}

		$itext = empty($index) ? '' : $index+1;
		$base_path = $backup_file_basename.'-'.$whichone.$itext.'.zip';
		$full_path = $this->updraft_dir.'/'.$base_path;
		$time_now = time();

		// This is compatible with filenames which indicate increments, as it is looking only for the current increment
		if (file_exists($full_path)) {
			// Gather any further files that may also exist
			$files_existing = array();
			while (file_exists($full_path)) {
				$files_existing[] = $base_path;
				$time_mod = (int) @filemtime($full_path);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
				$updraftplus->log($base_path.": this file has already been created (age: ".round($time_now-$time_mod, 1)." s)");
				if ($time_mod > 100 && ($time_now - $time_mod) < 30) {
					UpdraftPlus_Job_Scheduler::terminate_due_to_activity($base_path, $time_now, $time_mod);
				}
				$index++;
				// This is compatible with filenames which indicate increments, as it is looking only for the current increment
				$base_path = $backup_file_basename.'-'.$whichone.($index+1).'.zip';
				$full_path = $this->updraft_dir.'/'.$base_path;
			}
		}

		// Temporary file, to be able to detect actual completion (upon which, it is renamed)

		// Jun-13 - be more aggressive in removing temporary files from earlier attempts - anything >=600 seconds old of this kind
		UpdraftPlus_Filesystem_Functions::clean_temporary_files('_'.$updraftplus->file_nonce."-$whichone", 600);

		// Firstly, make sure that the temporary file is not already being written to - which can happen if a resumption takes place whilst an old run is still active
		$zip_name = $full_path.'.tmp';
		$time_mod = (int) @filemtime($zip_name);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
		if (file_exists($zip_name) && $time_mod>100 && ($time_now-$time_mod)<30) {
			UpdraftPlus_Job_Scheduler::terminate_due_to_activity($zip_name, $time_now, $time_mod);
		}

		if (file_exists($zip_name)) {
			$updraftplus->log("File exists ($zip_name), but was apparently not modified within the last 30 seconds, so we assume that any previous run has now terminated (time_mod=$time_mod, time_now=$time_now, diff=".($time_now-$time_mod).")");
		}

		// Now, check for other forms of temporary file, which would indicate that some activity is going on (even if it hasn't made it into the main zip file yet)
		// Note: this doesn't catch PclZip temporary files
		$d = dir($this->updraft_dir);
		$match = '_'.$updraftplus->file_nonce."-".$whichone;
		while (false !== ($e = $d->read())) {
			if ('.' == $e || '..' == $e || !is_file($this->updraft_dir.'/'.$e)) continue;
			$ziparchive_match = preg_match("/$match([0-9]+)?\.zip\.tmp\.([A-Za-z0-9]){6}?$/i", $e);
			$binzip_match = preg_match("/^zi([A-Za-z0-9]){6}$/", $e);
			$pclzip_match = preg_match("/^pclzip-[a-z0-9]+.tmp$/", $e);
			if ($time_now-filemtime($this->updraft_dir.'/'.$e) < 30 && ($ziparchive_match || (0 != $updraftplus->current_resumption && ($binzip_match || $pclzip_match)))) {
				UpdraftPlus_Job_Scheduler::terminate_due_to_activity($this->updraft_dir.'/'.$e, $time_now, filemtime($this->updraft_dir.'/'.$e));
			}
		}
		@$d->close();// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
		clearstatcache();

		if (isset($files_existing)) {
			// Because of zip-splitting, the mere fact that files exist is not enough to indicate that the entity is finished. For that, we need to also see that no subsequent file has been started.
			// Q. What if the previous runner died in between zips, and it is our job to start the next one? A. The next temporary file is created before finishing the former zip, so we are safe (and we are also safe-guarded by the updated value of the index being stored in the database).
			return $files_existing;
		}

		$this->log_account_space();

		$this->zip_microtime_start = microtime(true);

		// The paths in the zip should then begin with '$whichone', having removed WP_CONTENT_DIR from the front
		$zipcode = $this->make_zipfile($create_from_dir, $backup_file_basename, $whichone);
		if (true !== $zipcode) {
			$updraftplus->log("ERROR: Zip failure: Could not create $whichone zip (".$this->index." / $index)");
			$updraftplus->log(sprintf(__("Could not create %s zip. Consult the log file for more information.", 'updraftplus'), $whichone), 'error');
			// The caller is required to update $index from $this->index
			return false;
		} else {
			$itext = empty($this->index) ? '' : $this->index+1;
			$full_path = $this->updraft_dir.'/'.$backup_file_basename.'-'.$whichone.$itext.'.zip';
			if (file_exists($full_path.'.tmp')) {
				if (@filesize($full_path.'.tmp') === 0) {// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
					$updraftplus->log("Did not create $whichone zip (".$this->index.") - not needed");
					@unlink($full_path.'.tmp');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
				} else {
				
					$checksum_description = '';
		
					$checksums = $updraftplus->which_checksums();
		
					foreach ($checksums as $checksum) {
					
						$cksum = hash_file($checksum, $full_path.'.tmp');
						$updraftplus->jobdata_set($checksum.'-'.$whichone.$this->index, $cksum);
						if ($checksum_description) $checksum_description .= ', ';
						$checksum_description .= "$checksum: $cksum";
					
					}
				
					@rename($full_path.'.tmp', $full_path);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
					$timetaken = max(microtime(true)-$this->zip_microtime_start, 0.000001);
					$kbsize = filesize($full_path)/1024;
					$rate = round($kbsize/$timetaken, 1);
					$updraftplus->log("Created $whichone zip (".$this->index.") - ".round($kbsize, 1)." KB in ".round($timetaken, 1)." s ($rate KB/s) ($checksum_description)");
					// We can now remove any left-over temporary files from this job
				}
			} elseif ($this->index > $original_index) {
				$updraftplus->log("Did not create $whichone zip (".$this->index.") - not needed (2)");
				// Added 12-Feb-2014 (to help multiple morefiles)
				$this->index--;
			} else {
				$updraftplus->log("Looked-for $whichone zip (".$this->index.") was not found (".basename($full_path).".tmp)", 'warning');
			}
			UpdraftPlus_Filesystem_Functions::clean_temporary_files('_'.$updraftplus->file_nonce."-$whichone", 0);
		}

		// Remove cache list files as well, if there are any
		UpdraftPlus_Filesystem_Functions::clean_temporary_files('_'.$updraftplus->file_nonce."-$whichone", 0, true);

		// Create the results array to send back (just the new ones, not any prior ones)
		$files_existing = array();
		$res_index = $original_index;
		for ($i = $original_index; $i<= $this->index; $i++) {
			$itext = empty($i) ? '' : ($i+1);
			$full_path = $this->updraft_dir.'/'.$backup_file_basename.'-'.$whichone.$itext.'.zip';
			if (file_exists($full_path)) {
				$files_existing[$res_index] = $backup_file_basename.'-'.$whichone.$itext.'.zip';
			}
			$res_index++;
		}
		return $files_existing;
	}

	/**
	 * This method is for calling outside of a cloud_backup() context. It constructs a list of services for which prune operations should be attempted, and then calls prune_retained_backups() if necessary upon them.
	 */
	public function do_prune_standalone() {
		global $updraftplus;

		$services = (array) $updraftplus->just_one($updraftplus->jobdata_get('service'));

		$prune_services = array();

		foreach ($services as $service) {
			if ('none' === $service || '' == $service) continue;

			$objname = "UpdraftPlus_BackupModule_${service}";
			if (!class_exists($objname) && file_exists(UPDRAFTPLUS_DIR.'/methods/'.$service.'.php')) {
				include_once(UPDRAFTPLUS_DIR.'/methods/'.$service.'.php');
			}
			if (class_exists($objname)) {
				$remote_obj = new $objname;
				$prune_services[$service]['all'] = array($remote_obj, null);
			} else {
				$updraftplus->log("Could not prune from service $service: remote method not found");
			}

		}

		if (!empty($prune_services)) $this->prune_retained_backups($prune_services);
	}

	/**
	 * Dispatch to the relevant function
	 *
	 * @param Array $backup_array List of archives for the backup
	 */
	public function cloud_backup($backup_array) {

		global $updraftplus;

		$services = (array) $updraftplus->just_one($updraftplus->jobdata_get('service'));
		$remote_storage_instances = $updraftplus->jobdata_get('remote_storage_instances', array());

		// We need to make sure that the loop below actually runs
		if (empty($services)) $services = array('none');
		
		$storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_enabled_storage_objects_and_ids($services, $remote_storage_instances);

		$total_instances_count = 0;

		foreach ($storage_objects_and_ids as $service) {
			if ($service['object']->supports_feature('multi_options')) $total_instances_count += count($service['instance_settings']);
		}

		$updraftplus->jobdata_set('jobstatus', 'clouduploading');

		$updraftplus->register_wp_http_option_hooks();

		$upload_status = $updraftplus->jobdata_get('uploading_substatus');
		if (!is_array($upload_status) || !isset($upload_status['t'])) {
			$upload_status = array('i' => 0, 'p' => 0, 't' => max(1, $total_instances_count)*count($backup_array));
			$updraftplus->jobdata_set('uploading_substatus', $upload_status);
		}

		$do_prune = array();

		// If there was no check-in last time, then attempt a different service first - in case a time-out on the attempted service leads to no activity and everything stopping
		if (count($services) >1 && !empty($updraftplus->no_checkin_last_time)) {
			$updraftplus->log('No check-in last time: will try a different remote service first');
			array_push($services, array_shift($services));
			// Make sure that the 'no worthwhile activity' detector isn't flumoxed by the starting of a new upload at 0%
			if ($updraftplus->current_resumption > 9) $updraftplus->jobdata_set('uploaded_lastreset', $updraftplus->current_resumption);
			if (1 == ($updraftplus->current_resumption % 2) && count($services)>2) array_push($services, array_shift($services));
		}

		$errors_before_uploads = $updraftplus->error_count();

		foreach ($services as $ind => $service) {
			try {
				$instance_id_count = 0;
				$total_instance_ids = ('none' !== $service && '' !== $service && $storage_objects_and_ids[$service]['object']->supports_feature('multi_options')) ? count($storage_objects_and_ids[$service]['instance_settings']) : 1;
	
				// Used for logging by record_upload_chunk()
				$this->current_service = $service;
	
				// Used when deciding whether to delete the local file
				$this->last_storage_instance = ($ind+1 >= count($services) && $instance_id_count+1 >= $total_instance_ids && $errors_before_uploads == $updraftplus->error_count()) ? true : false;
				$log_extra = $this->last_storage_instance ? ' (last)' : '';
				$updraftplus->log("Cloud backup selection (".($ind+1)."/".count($services)."): ".$service." with instance (".($instance_id_count+1)."/".$total_instance_ids.")".$log_extra);
				@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
	
				if ('none' == $service || '' == $service) {
					$updraftplus->log('No remote despatch: user chose no remote backup service');
					// Still want to mark as "uploaded", to signal that nothing more needs doing. (Important on incremental runs with no cloud storage).
					foreach ($backup_array as $file) {
						if ($updraftplus->is_uploaded($file)) {
							$updraftplus->log("Already uploaded: $file");
						} else {
							$updraftplus->uploaded_file($file, true);
						}
					}
					$this->prune_retained_backups(array('none' => array('all' => array(null, null))));
				} elseif (!empty($storage_objects_and_ids[$service]['object']) && !$storage_objects_and_ids[$service]['object']->supports_feature('multi_options')) {
					$remote_obj = $storage_objects_and_ids[$service]['object'];
					
					$do_prune = array_merge_recursive($do_prune, $this->upload_cloud($remote_obj, $service, $backup_array, ''));
				} elseif (!empty($storage_objects_and_ids[$service]['instance_settings'])) {
					foreach ($storage_objects_and_ids[$service]['instance_settings'] as $instance_id => $options) {
					
						if ($instance_id_count > 0) {
							$this->last_storage_instance = ($ind+1 >= count($services) && $instance_id_count+1 >= $total_instance_ids && $errors_before_uploads == $updraftplus->error_count()) ? true : false;
							$log_extra = $this->last_storage_instance ? ' (last)' : '';
							$updraftplus->log("Cloud backup selection (".($ind+1)."/".count($services)."): ".$service." with instance (".($instance_id_count+1)."/".$total_instance_ids.")".$log_extra);
						}
					
						// Used for logging by record_upload_chunk()
						$this->current_instance = $instance_id;
	
						if (!isset($options['instance_enabled'])) $options['instance_enabled'] = 1;
	
						// if $remote_storage_instances is not empty then we are looping over a list of instances the user wants to backup to so we want to ignore if the instance is enabled or not
						if (1 == $options['instance_enabled'] || !empty($remote_storage_instances)) {
							$remote_obj = $storage_objects_and_ids[$service]['object'];
							$remote_obj->set_options($options, true, $instance_id);
							$do_prune = array_merge_recursive($do_prune, $this->upload_cloud($remote_obj, $service, $backup_array, $instance_id));
						} else {
							$updraftplus->log("This instance id ($instance_id) is set as inactive.");
						}
	
						$instance_id_count++;
					}
				}
			} catch (Exception $e) {
				$log_message = 'Exception ('.get_class($e).') occurred during backup uploads to the '.$service.'. Exception Message: '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
				$updraftplus->log($log_message);
				error_log($log_message);
				$updraftplus->log(sprintf(__('A PHP exception (%s) has occurred: %s', 'updraftplus'), get_class($e), $e->getMessage()), 'error');
			// @codingStandardsIgnoreLine
			} catch (Error $e) {
				$log_message = 'PHP Fatal error ('.get_class($e).') has occurred during backup uploads to the '.$service.'. Error Message: '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
				$updraftplus->log($log_message);
				error_log($log_message);
				$updraftplus->log(sprintf(__('A PHP fatal error (%s) has occurred: %s', 'updraftplus'), get_class($e), $e->getMessage()), 'error');
			}
		}

		if (!empty($do_prune)) $this->prune_retained_backups($do_prune);

		$updraftplus->register_wp_http_option_hooks(false);

	}

	/**
	 * This method will start the upload of the backups to the chosen remote storage method and return an array of files to be pruned and their location.
	 *
	 * @param  Object $remote_obj   - the remote storage object
	 * @param  String $service      - the name of the service we are uploading to
	 * @param  Array  $backup_array - an array that contains the backup files we want to upload
	 * @param  String $instance_id  - the instance id we are using
	 * @return Array                - an array with information about what files to prune and where they are located
	 */
	private function upload_cloud($remote_obj, $service, $backup_array, $instance_id) {

		global $updraftplus;

		$do_prune = array();

		if ('' == $instance_id) {
			$updraftplus->log("Beginning dispatch of backup to remote ($service)");
		} else {
			$updraftplus->log("Beginning dispatch of backup to remote ($service) (instance identifier $instance_id)");
		}

		$errors_before_uploads = $updraftplus->error_count();

		$sarray = array();
		foreach ($backup_array as $bind => $file) {
			if ($updraftplus->is_uploaded($file, $service, $instance_id)) {
				if ('' == $instance_id) {
					$updraftplus->log("Already uploaded to $service: $file", 'notice', false, true);
				} else {
					$updraftplus->log("Already uploaded to $service / $instance_id: $file", 'notice', false, true);
				}
			} else {
				$sarray[$bind] = $file;
			}
		}
		
		if (count($sarray) > 0) {
			$pass_to_prune = $remote_obj->backup($sarray);
			if ('remotesend' != $service) {
				$do_prune[$service][$instance_id] = array($remote_obj, $pass_to_prune);
			} else {
				$do_prune[$service]['default'] = array($remote_obj, $pass_to_prune);
			}

			// Check there are no errors in the uploads, if none then call upload_completed() if it exists otherwise mark as complete
			if ($errors_before_uploads == $updraftplus->error_count()) {
				if (is_callable(array($remote_obj, 'upload_completed'))) {
					$result = $remote_obj->upload_completed();
					if ($result) $updraftplus->mark_upload_complete($service);
				} else {
					$updraftplus->mark_upload_complete($service);
				}
			}
		} else {
			// We still need to make sure that prune is run on this remote storage method, even if all entities were previously uploaded
			$do_prune[$service]['all'] = array($remote_obj, null);
		}

		return $do_prune;
	}

	/**
	 * Group the backup history into sets for retention processing and indicate the retention rule to apply to each group. This is a 'default' function which just puts them all in together.
	 *
	 * @param Array $backup_history
	 *
	 * @return Array
	 */
	private function group_backups($backup_history) {
		return array(array('sets' => $backup_history, 'process_order' => 'keep_newest'));
	}
	
	/**
	 * Logs a message; with the message being logged to the database also only if that has not been done in the last 3 seconds. Useful for better overall performance on slow database servers with rapid logging.
	 *
	 * @uses UpdraftPlus::log()
	 *
	 * @param String $message - the message to log
	 * @param String $level	  - the log level
	 */
	private function log_with_db_occasionally($message, $level = 'notice') {
		global $updraftplus;
		static $last_db = false;
		
		if (time() > $last_db + 3) {
			$last_db = time();
			$skip_dblog = false;
		} else {
			$skip_dblog = true;
		}
		
		return $updraftplus->log($message, $level, false, $skip_dblog);
	}
	
	/**
	 * Prunes historical backups, according to the user's settings
	 *
	 * @param Array $services - An associative array with list of services as key and remote object and boolean flag as values to prune on. This must be an array (i.e. it is not flexible like some other places)
	 *
	 * @return void
	 */
	public function prune_retained_backups($services) {

		global $updraftplus, $wpdb;

		if ('' != $updraftplus->jobdata_get('remotesend_info')) {
			$updraftplus->log("Prune old backups from local store: skipping, as this was a remote send operation");
			return;
		}

		if (method_exists($wpdb, 'check_connection') && (!defined('UPDRAFTPLUS_SUPPRESS_CONNECTION_CHECKS') || !UPDRAFTPLUS_SUPPRESS_CONNECTION_CHECKS)) {
			if (!$wpdb->check_connection(false)) {
				UpdraftPlus_Job_Scheduler::reschedule(60);
				$updraftplus->log('It seems the database went away; scheduling a resumption and terminating for now');
				UpdraftPlus_Job_Scheduler::record_still_alive();
				die;
			}
		}

		// If they turned off deletion on local backups, then there is nothing to do
		if (!UpdraftPlus_Options::get_updraft_option('updraft_delete_local', 1) && 1 == count($services) && array_key_exists('none', $services)) {
			$updraftplus->log("Prune old backups from local store: nothing to do, since the user disabled local deletion and we are using local backups");
			return;
		}

		$updraftplus->jobdata_set_multi(array('jobstatus' => 'pruning', 'prune' => 'begun'));

		// Number of backups to retain - files
		$updraft_retain = UpdraftPlus_Options::get_updraft_option('updraft_retain', 2);
		$updraft_retain = is_numeric($updraft_retain) ? $updraft_retain : 1;

		// Number of backups to retain - db
		$updraft_retain_db = UpdraftPlus_Options::get_updraft_option('updraft_retain_db', $updraft_retain);
		$updraft_retain_db = is_numeric($updraft_retain_db) ? $updraft_retain_db : 1;

		$updraftplus->log("Retain: beginning examination of existing backup sets; user setting: retain_files=$updraft_retain, retain_db=$updraft_retain_db");

		// Returns an array, most recent first, of backup sets
		$backup_history = UpdraftPlus_Backup_History::get_history();
		
		$ignored_because_imported = array();
		
		// Remove non-native (imported) backups, which are neither counted nor pruned. It's neater to do these in advance, and log only one line.
		$functional_backup_history = $backup_history;
		foreach ($functional_backup_history as $backup_time => $backup_to_examine) {
			if (isset($backup_to_examine['native']) && false == $backup_to_examine['native']) {
				$ignored_because_imported[] = $backup_time;
				unset($functional_backup_history[$backup_time]);
			}
		}
		if (!empty($ignored_because_imported)) {
			$updraftplus->log("These backup set(s) were imported from a remote location, so will not be counted or pruned. Skipping: ".implode(', ', $ignored_because_imported));
		}
		
		$backupable_entities = $updraftplus->get_backupable_file_entities(true);

		$database_backups_found = array();

		$file_entities_backups_found = array();
		foreach ($backupable_entities as $entity => $info) {
			$file_entities_backups_found[$entity] = 0;
		}

		if (false === ($backup_db_groups = apply_filters('updraftplus_group_backups_for_pruning', false, $functional_backup_history, 'db'))) {
			$backup_db_groups = $this->group_backups($functional_backup_history);
		}
		$updraftplus->log("Number of backup sets in history: ".count($backup_history)."; groups (db): ".count($backup_db_groups));

		foreach ($backup_db_groups as $group_id => $group) {
			
			// N.B. The array returned by UpdraftPlus_Backup_History::get_history() is already sorted, with most-recent first

			if (empty($group['sets']) || !is_array($group['sets'])) continue;
			$sets = $group['sets'];

			// Sort the groups into the desired "keep this first" order
			$process_order = (!empty($group['process_order']) && 'keep_oldest' == $group['process_order']) ? 'keep_oldest' : 'keep_newest';
			if ('keep_oldest' == $process_order) ksort($sets);
			
			$rule = !empty($group['rule']) ? $group['rule'] : array('after-howmany' => 0, 'after-period' => 0, 'every-period' => 1, 'every-howmany' => 1);
			
			foreach ($sets as $backup_datestamp => $backup_to_examine) {

				$files_to_prune = array();
				$nonce = empty($backup_to_examine['nonce']) ? '???' : $backup_to_examine['nonce'];

				// $backup_to_examine is an array of file names, keyed on db/plugins/themes/uploads
				// The new backup_history array is saved afterwards, so remember to unset the ones that are to be deleted
				$this->log_with_db_occasionally(sprintf("Examining (for databases) backup set with group_id=$group_id, nonce=%s, datestamp=%s (%s)", $nonce, $backup_datestamp, gmdate('M d Y H:i:s', $backup_datestamp)));
				
				// "Always Keep" Backups should be counted in the count of how many have been retained for purposes of the "how many to retain" count... but if that count is already matched, it's not a problem
				$is_always_keep = !empty($backup_to_examine['always_keep']);
				
				// Auto-backups are only counted or deleted once we have reached the retain limit - before that, they are skipped
				$is_autobackup = !empty($backup_to_examine['autobackup']);
				
				$remote_sent = (!empty($backup_to_examine['service']) && ((is_array($backup_to_examine['service']) && in_array('remotesend', $backup_to_examine['service'])) || 'remotesend' === $backup_to_examine['service'])) ? true : false;

				$any_deleted_via_filter_yet = false;

				// Databases
				foreach ($backup_to_examine as $key => $data) {
					if ('db' != strtolower(substr($key, 0, 2)) || '-size' == substr($key, -5, 5)) continue;

					if (empty($database_backups_found[$key])) $database_backups_found[$key] = 0;
					
					if ($nonce == $updraftplus->nonce || $nonce == $updraftplus->file_nonce) {
						$this->log_with_db_occasionally("This backup set is the backup set just made, so will not be deleted.");
						$database_backups_found[$key]++;
						continue;
					}
					
					if ($is_always_keep) {
						if ($database_backups_found[$key] < $updraft_retain) {
							$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an 'Always Keep' backup, and we have not yet reached any retain limits, so it should be counted in the count of how many have been retained for purposes of the 'how many to retain' count. It will not be pruned. Skipping.");
							$database_backups_found[$key]++;
						} else {
							$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an 'Always Keep' backup, so it will not be pruned. Skipping.");
						}
						continue;
					}
					
					if ($is_autobackup) {
						if ($any_deleted_via_filter_yet) {
							$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an automatic backup, but we have previously deleted a backup due to a limit, so it will be pruned (but not counted towards numerical limits).");
							$prune_it = true;
						} elseif ($database_backups_found[$key] < $updraft_retain_db) {
							$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an automatic backup, and we have not yet reached any retain limits, so it will not be counted or pruned. Skipping.");
							continue;
						} else {
							$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an automatic backup, and we have already reached retain limits, so it will be pruned.");
							$prune_it = true;
						}
					} else {
						$prune_it = false;
					}

					if ($remote_sent) {
						$prune_it = true;
						$this->log_with_db_occasionally("$backup_datestamp: $key: was sent to remote site; will remove from local record (only)");
					}
					
					// All non-auto backups must be run through this filter (in date order) regardless of the current state of $prune_it - so that filters are able to track state.
					$prune_it_before_filter = $prune_it;

					if (!$is_autobackup) $prune_it = apply_filters('updraftplus_prune_or_not', $prune_it, 'db', $backup_datestamp, $key, $database_backups_found[$key], $rule, $group_id);

					// Apply the final retention limit list (do not increase the 'retained' counter before seeing if the backup is being pruned for some other reason)
					if (!$prune_it && !$is_autobackup) {

						if ($database_backups_found[$key] + 1 > $updraft_retain_db) {
							$prune_it = true;

							$fname = is_string($data) ? $data : $data[0];
							$this->log_with_db_occasionally("$backup_datestamp: $key: this set includes a database (".$fname."); db count is now ".$database_backups_found[$key]);

							$this->log_with_db_occasionally("$backup_datestamp: $key: over retain limit ($updraft_retain_db); will delete this database");
						}
					
					}
					
					if ($prune_it) {
						if (!$prune_it_before_filter) $any_deleted_via_filter_yet = true;

						if (!empty($data)) {
							$size_key = $key.'-size';
							$size = isset($backup_to_examine[$size_key]) ? $backup_to_examine[$size_key] : null;
							foreach ($services as $service => $instance_ids_to_prune) {
								foreach ($instance_ids_to_prune as $instance_id_to_prune => $sd) {
									if ('none' != $service && '' != $service && $sd[0]->supports_feature('multi_options')) {
										$storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_storage_objects_and_ids(array($service));
										if ('all' == $instance_id_to_prune) {
											foreach ($storage_objects_and_ids[$service]['instance_settings'] as $saved_instance_id => $options) {
												$sd[0]->set_options($options, false, $saved_instance_id);
												$this->prune_file($service, $data, $sd[0], $sd[1], array($size));
											}
										} else {
											$opts = $storage_objects_and_ids[$service]['instance_settings'][$instance_id_to_prune];
											$sd[0]->set_options($opts, false, $instance_id_to_prune);
											$this->prune_file($service, $data, $sd[0], $sd[1], array($size));
										}
									} else {
										$this->prune_file($service, $data, $sd[0], $sd[1], array($size));
									}
								}
							}
						}
						unset($backup_to_examine[$key]);
						UpdraftPlus_Job_Scheduler::record_still_alive();
					} elseif (!$is_autobackup) {
						$database_backups_found[$key]++;
					}

					$backup_to_examine = $this->remove_backup_set_if_empty($backup_to_examine, $backupable_entities);
					if (empty($backup_to_examine)) {
						unset($functional_backup_history[$backup_datestamp]);
						unset($backup_history[$backup_datestamp]);
						$this->maybe_save_backup_history_and_reschedule($backup_history);
					} else {
						$functional_backup_history[$backup_datestamp] = $backup_to_examine;
						$backup_history[$backup_datestamp] = $backup_to_examine;
					}
				}
			}
		}

		if (false === ($backup_files_groups = apply_filters('updraftplus_group_backups_for_pruning', false, $functional_backup_history, 'files'))) {
			$backup_files_groups = $this->group_backups($functional_backup_history);
		}

		$updraftplus->log("Number of backup sets in history: ".count($backup_history)."; groups (files): ".count($backup_files_groups));
		
		// Now again - this time for the files
		foreach ($backup_files_groups as $group_id => $group) {
			
			// N.B. The array returned by UpdraftPlus_Backup_History::get_history() is already sorted, with most-recent first

			if (empty($group['sets']) || !is_array($group['sets'])) continue;
			$sets = $group['sets'];
			
			// Sort the groups into the desired "keep this first" order
			$process_order = (!empty($group['process_order']) && 'keep_oldest' == $group['process_order']) ? 'keep_oldest' : 'keep_newest';
			// Youngest - i.e. smallest epoch - first
			if ('keep_oldest' == $process_order) ksort($sets);

			$rule = !empty($group['rule']) ? $group['rule'] : array('after-howmany' => 0, 'after-period' => 0, 'every-period' => 1, 'every-howmany' => 1);
			
			foreach ($sets as $backup_datestamp => $backup_to_examine) {

				$files_to_prune = array();
				$nonce = empty($backup_to_examine['nonce']) ? '???' : $backup_to_examine['nonce'];

				// $backup_to_examine is an array of file names, keyed on db/plugins/themes/uploads
				// The new backup_history array is saved afterwards, so remember to unset the ones that are to be deleted
				$this->log_with_db_occasionally(sprintf("Examining (for files) backup set with nonce=%s, datestamp=%s (%s)", $nonce, $backup_datestamp, gmdate('M d Y H:i:s', $backup_datestamp)));

				// "Always Keep" Backups should be counted in the count of how many have been retained for purposes of the "how many to retain" count... but if that count is already matched, it's not a problem
				$is_always_keep = !empty($backup_to_examine['always_keep']);
				
				// Auto-backups are only counted or deleted once we have reached the retain limit - before that, they are skipped
				$is_autobackup = !empty($backup_to_examine['autobackup']);

				$remote_sent = (!empty($backup_to_examine['service']) && ((is_array($backup_to_examine['service']) && in_array('remotesend', $backup_to_examine['service'])) || 'remotesend' === $backup_to_examine['service'])) ? true : false;

				$any_deleted_via_filter_yet = false;
		
				$file_sizes = array();

				// Files
				foreach ($backupable_entities as $entity => $info) {
					if (!empty($backup_to_examine[$entity])) {
					
						// This should only be able to happen if you import backups with a future timestamp
						if ($nonce == $updraftplus->nonce || $nonce == $updraftplus->file_nonce) {
							$updraftplus->log("This backup set is the backup set just made, so will not be deleted.");
							$file_entities_backups_found[$entity]++;
							continue;
						}

						if ($is_always_keep) {
							if ($file_entities_backups_found[$entity] < $updraft_retain) {
								$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an 'Always Keep' backup, and we have not yet reached any retain limits, so it should be counted in the count of how many have been retained for purposes of the 'how many to retain' count. It will not be pruned. Skipping.");
								$file_entities_backups_found[$entity]++;
							} else {
								$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an 'Always Keep' backup, so it will not be pruned. Skipping.");
							}
							continue;
						}
						
						if ($is_autobackup) {
							if ($any_deleted_via_filter_yet) {
								$this->log_with_db_occasionally("This backup set was an automatic backup, but we have previously deleted a backup due to a limit, so it will be pruned (but not counted towards numerical limits).");
								$prune_it = true;
							} elseif ($file_entities_backups_found[$entity] < $updraft_retain) {
								$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an automatic backup, and we have not yet reached any retain limits, so it will not be counted or pruned. Skipping.");
								continue;
							} else {
								$this->log_with_db_occasionally("This backup set ($backup_datestamp) was an automatic backup, and we have already reached retain limits, so it will be pruned.");
								$prune_it = true;
							}
						} else {
							$prune_it = false;
						}

						if ($remote_sent) {
							$prune_it = true;
						}

						// All non-auto backups must be run through this filter (in date order) regardless of the current state of $prune_it - so that filters are able to track state.
						$prune_it_before_filter = $prune_it;
						if (!$is_autobackup) $prune_it = apply_filters('updraftplus_prune_or_not', $prune_it, 'files', $backup_datestamp, $entity, $file_entities_backups_found[$entity], $rule, $group_id);

						// The "more than maximum to keep?" counter should not be increased until we actually know that the set is being kept. Before verison 1.11.22, we checked this before running the filter, which resulted in the counter being increased for sets that got pruned via the filter (i.e. not kept) - and too many backups were thus deleted
						if (!$prune_it && !$is_autobackup) {
							if ($file_entities_backups_found[$entity] >= $updraft_retain) {
								$this->log_with_db_occasionally("$entity: over retain limit ($updraft_retain); will delete this file entity");
								$prune_it = true;
							}
						}
						
						if ($prune_it) {
							if (!$prune_it_before_filter) $any_deleted_via_filter_yet = true;
							$prune_this = $backup_to_examine[$entity];
							if (is_string($prune_this)) $prune_this = array($prune_this);

							foreach ($prune_this as $k => $prune_file) {
								if ($remote_sent) {
									$updraftplus->log("$entity: $backup_datestamp: was sent to remote site; will remove from local record (only)");
								}
								$size_key = (0 == $k) ? $entity.'-size' : $entity.$k.'-size';
								$size = (isset($backup_to_examine[$size_key])) ? $backup_to_examine[$size_key] : null;
								$files_to_prune[] = $prune_file;
								$file_sizes[] = $size;
							}
							unset($backup_to_examine[$entity]);
							
						} elseif (!$is_autobackup) {
							$file_entities_backups_found[$entity]++;
						}
					}
				}

				// Sending an empty array is not itself a problem - except that the remote storage method may not check that before setting up a connection, which can waste time: especially if this is done every time around the loop.
				if (!empty($files_to_prune)) {
					// Actually delete the files
					foreach ($services as $service => $instance_ids_to_prune) {
						foreach ($instance_ids_to_prune as $instance_id_to_prune => $sd) {
							if ("none" != $service && '' != $service && $sd[0]->supports_feature('multi_options')) {
								$storage_objects_and_ids = UpdraftPlus_Storage_Methods_Interface::get_storage_objects_and_ids(array($service));
								if ('all' == $instance_id_to_prune) {
									foreach ($storage_objects_and_ids[$service]['instance_settings'] as $saved_instance_id => $options) {
										$sd[0]->set_options($options, false, $saved_instance_id);
										$this->prune_file($service, $files_to_prune, $sd[0], $sd[1], array($size));
									}
								} else {
									$opts = $storage_objects_and_ids[$service]['instance_settings'][$instance_id_to_prune];
									$sd[0]->set_options($opts, false, $instance_id_to_prune);
									$this->prune_file($service, $files_to_prune, $sd[0], $sd[1], array($size));
								}
							} else {
								$this->prune_file($service, $files_to_prune, $sd[0], $sd[1], array($size));
							}
							UpdraftPlus_Job_Scheduler::record_still_alive();
						}
					}
				}

				$backup_to_examine = $this->remove_backup_set_if_empty($backup_to_examine, $backupable_entities);
				if (empty($backup_to_examine)) {
// unset($functional_backup_history[$backup_datestamp]);
					unset($backup_history[$backup_datestamp]);
					$this->maybe_save_backup_history_and_reschedule($backup_history);
				} else {
// $functional_backup_history[$backup_datestamp] = $backup_to_examine;
					$backup_history[$backup_datestamp] = $backup_to_examine;
				}

			// Loop over backup sets
			}
			
		// Look over backup groups
		}

		$updraftplus->log("Retain: saving new backup history (sets now: ".count($backup_history).") and finishing retain operation");
		UpdraftPlus_Backup_History::save_history($backup_history, false);

		do_action('updraftplus_prune_retained_backups_finished');
		
		$updraftplus->jobdata_set('prune', 'finished');

	}

	/**
	 * The purpose of this is to save the backup history periodically - for the benefit of setups where the pruning takes longer than the total allow run time (e.g. if the network communications to the remote storage have delays in, and there are a lot of sets to scan)
	 *
	 * @param Array $backup_history - the backup history to possible save
	 */
	private function maybe_save_backup_history_and_reschedule($backup_history) {
		static $last_saved_at = 0;
		if (!$last_saved_at) $last_saved_at = time();
		if (time() - $last_saved_at >= 10) {
			global $updraftplus;
			$updraftplus->log("Retain: saving new backup history, because at least 10 seconds have passed since the last save (sets now: ".count($backup_history).")");
			UpdraftPlus_Backup_History::save_history($backup_history, false);
			UpdraftPlus_Job_Scheduler::something_useful_happened();
			$last_saved_at = time();
		}
	}
	
	/**
	 * Examine a backup set; if it is empty (no files or DB), then remove the associated log file
	 *
	 * @param Array $backup_to_examine	 - backup set
	 * @param Array $backupable_entities - compare with this list of backup entities
	 *
	 * @return Array|Boolean - if it was empty, false is returned
	 */
	private function remove_backup_set_if_empty($backup_to_examine, $backupable_entities) {
	
		global $updraftplus;

		// Get new result, post-deletion; anything left in this set?
		$contains_files = 0;
		foreach ($backupable_entities as $entity => $info) {
			if (isset($backup_to_examine[$entity])) {
				$contains_files = 1;
				break;
			}
		}

		$contains_db = 0;
		foreach ($backup_to_examine as $key => $data) {
			if ('db' == strtolower(substr($key, 0, 2)) && '-size' != substr($key, -5, 5)) {
				$contains_db = 1;
				break;
			}
		}

		// Delete backup set completely if empty, o/w just remove DB
		// We search on the four keys which represent data, allowing other keys to be used to track other things
		if (!$contains_files && !$contains_db) {
			$updraftplus->log("This backup set is now empty; will remove from history");
			if (isset($backup_to_examine['nonce'])) {
				$fullpath = $this->updraft_dir."/log.".$backup_to_examine['nonce'].".txt";
				if (is_file($fullpath)) {
					$updraftplus->log("Deleting log file (log.".$backup_to_examine['nonce'].".txt)");
					@unlink($fullpath);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
				} else {
					$updraftplus->log("Corresponding log file (log.".$backup_to_examine['nonce'].".txt) not found - must have already been deleted");
				}
			} else {
				$updraftplus->log("No nonce record found in the backup set, so cannot delete any remaining log file");
			}
			return false;
		} else {
			$updraftplus->log("This backup set remains non-empty (f=$contains_files/d=$contains_db); will retain in history");
			return $backup_to_examine;
		}
		
	}
	
	/**
	 * Prune files from remote and local storage
	 *
	 * @param String	   $service         Service to prune (one only)
	 * @param Array|String $dofiles         An array of files (or a single string for one file)
	 * @param Array		   $method_object   specific method object
	 * @param Array		   $object_passback specific passback object
	 * @param Array		   $file_sizes      size of files
	 */
	private function prune_file($service, $dofiles, $method_object = null, $object_passback = null, $file_sizes = array()) {
		global $updraftplus;
		if (!is_array($dofiles)) $dofiles = array($dofiles);
		
		if (!apply_filters('updraftplus_prune_file', true, $dofiles, $service, $method_object, $object_passback, $file_sizes)) {
			$updraftplus->log("Prune: service=$service: skipped via filter");
		}
		
		foreach ($dofiles as $dofile) {
			if (empty($dofile)) continue;
			$updraftplus->log("Delete file: $dofile, service=$service");
			$fullpath = $this->updraft_dir.'/'.$dofile;
			// delete it if it's locally available
			if (file_exists($fullpath)) {
				$updraftplus->log("Deleting local copy ($dofile)");
				unlink($fullpath);
			}
		}
		// Despatch to the particular method's deletion routine
		if (!is_null($method_object)) $method_object->delete($dofiles, $object_passback, $file_sizes);
	}

	/**
	 * The purpose of this function is to make sure that the options table is put in the database first, then the users table, then the site + blogs tables (if present - multisite), then the usermeta table; and after that the core WP tables - so that when restoring we restore the core tables first
	 *
	 * @param Array $a_arr First array to be compared
	 * @param Array $b_arr Second array to be compared
	 * @return Integer - according to the rules of usort()
	 */
	private function backup_db_sorttables($a_arr, $b_arr) {

		$a = $a_arr['name'];
		$a_table_type = $a_arr['type'];
		$b = $b_arr['name'];
		$b_table_type = $b_arr['type'];
	
		// Views must always go after tables (since they can depend upon them)
		if ('VIEW' == $a_table_type && 'VIEW' != $b_table_type) return 1;
		if ('VIEW' == $b_table_type && 'VIEW' != $a_table_type) return -1;
	
		if ('wp' != $this->whichdb) return strcmp($a, $b);

		global $updraftplus;
		if ($a == $b) return 0;
		$our_table_prefix = $this->table_prefix_raw;
		if ($a == $our_table_prefix.'options') return -1;
		if ($b == $our_table_prefix.'options') return 1;
		if ($a == $our_table_prefix.'site') return -1;
		if ($b == $our_table_prefix.'site') return 1;
		if ($a == $our_table_prefix.'blogs') return -1;
		if ($b == $our_table_prefix.'blogs') return 1;
		if ($a == $our_table_prefix.'users') return -1;
		if ($b == $our_table_prefix.'users') return 1;
		if ($a == $our_table_prefix.'usermeta') return -1;
		if ($b == $our_table_prefix.'usermeta') return 1;

		if (empty($our_table_prefix)) return strcmp($a, $b);

		try {
			$core_tables = array_merge($this->wpdb_obj->tables, $this->wpdb_obj->global_tables, $this->wpdb_obj->ms_global_tables);
		} catch (Exception $e) {
			$updraftplus->log($e->getMessage());
		}
		
		if (empty($core_tables)) $core_tables = array('terms', 'term_taxonomy', 'termmeta', 'term_relationships', 'commentmeta', 'comments', 'links', 'postmeta', 'posts', 'site', 'sitemeta', 'blogs', 'blogversions', 'blogmeta');

		global $updraftplus;
		$na = UpdraftPlus_Manipulation_Functions::str_replace_once($our_table_prefix, '', $a);
		$nb = UpdraftPlus_Manipulation_Functions::str_replace_once($our_table_prefix, '', $b);
		if (in_array($na, $core_tables) && !in_array($nb, $core_tables)) return -1;
		if (!in_array($na, $core_tables) && in_array($nb, $core_tables)) return 1;
		return strcmp($a, $b);
	}

	/**
	 * Log the amount account space free/used, if possible
	 */
	private function log_account_space() {
		// Don't waste time if space is huge
		if (!empty($this->account_space_oodles)) return;
		global $updraftplus;
		$hosting_bytes_free = $updraftplus->get_hosting_disk_quota_free();
		if (is_array($hosting_bytes_free)) {
			$perc = round(100*$hosting_bytes_free[1]/(max($hosting_bytes_free[2], 1)), 1);
			$updraftplus->log(sprintf('Free disk space in account: %s (%s used)', round($hosting_bytes_free[3]/1048576, 1)." MB", "$perc %"));
		}
	}

	/**
	 * Returns the basename up to and including the nonce (but not the entity)
	 *
	 * @param Integer $use_time epoch time to use
	 * @return String
	 */
	private function get_backup_file_basename_from_time($use_time) {
		global $updraftplus;
		return apply_filters('updraftplus_get_backup_file_basename_from_time', 'backup_'.get_date_from_gmt(gmdate('Y-m-d H:i:s', $use_time), 'Y-m-d-Hi').'_'.$this->site_name.'_'.$updraftplus->file_nonce, $use_time, $this->site_name);
	}

	/**
	 * Find the zip files for a given nonce
	 *
	 * @param String $dir		  - directory to look in
	 * @param Strign $match_nonce - backup ID to match
	 *
	 * @return Array
	 */
	private function find_existing_zips($dir, $match_nonce) {
		$zips = array();
		if ($handle = opendir($dir)) {
			while (false !== ($entry = readdir($handle))) {
				if ("." != $entry && ".." != $entry) {
					if (preg_match('/^backup_(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})_.*_([0-9a-f]{12})-([\-a-z]+)([0-9]+)?\.zip$/i', $entry, $matches)) {
						if ($matches[6] !== $match_nonce) continue;
						$timestamp = mktime($matches[4], $matches[5], 0, $matches[2], $matches[3], $matches[1]);
						$entity = $matches[7];
						$index = empty($matches[8]) ? '0' : $matches[8];
						$zips[$entity][$index] = array($timestamp, $entry);
					}
				}
			}
		}
		return $zips;
	}

	/**
	 * Get information on whether a particular file exists in a set
	 *
	 * @param  Array   $files  should be an array as returned by find_existing_zips()]
	 * @param  String  $entity entty of the file (e.g. 'plugins')
	 * @param  Integer $index  Index within the files array
	 * @return String|Boolean - false if the file does not exist; otherwise, the basename
	 */
	private function file_exists($files, $entity, $index = 0) {
		if (isset($files[$entity]) && isset($files[$entity][$index])) {
			$file = $files[$entity][$index];
			// Return the filename
			return $file[1];
		} else {
			return false;
		}
	}

	/**
	 * This function is resumable
	 *
	 * @param String $job_status Current status
	 *
	 * @return Array - array of backed-up files
	 */
	private function backup_dirs($job_status) {

		global $updraftplus;

		if (!$updraftplus->backup_time) $updraftplus->backup_time_nonce();

		$use_time = $updraftplus->backup_time;
		$backup_file_basename = $this->get_backup_file_basename_from_time($use_time);

		$backup_array = array();

		// Was there a check-in last time? If not, then reduce the amount of data attempted
		if ('finished' != $job_status && $updraftplus->current_resumption >= 2) {

			// NOTYET: Possible amendment to original algorithm; not just no check-in, but if the check in was very early (can happen if we get a very early checkin for some trivial operation, then attempt something too big)

			// 03-Sep-2015 - came across a case (HS#2052) where there apparently was a check-in 'last time', but no resumption was scheduled because the 'useful_checkin' jobdata was *not* last time - which must indicate dying at a very unfortunate/unlikely point in the code. As a result, the split was not auto-reduced. Consequently, we've added !$updraftplus->newresumption_scheduled as a condition on the first check here (it was already on the second), as if no resumption is scheduled then whatever checkin there was last time was only partial. This was on GoDaddy, for which a number of curious I/O event combinations have been seen in recent months - their platform appears to have some odd behaviour when PHP is killed off.
			// 04-Sep-2015 - move the '$updraftplus->current_resumption<=10' check to the inner loop (instead of applying to this whole section), as I see no reason for that restriction (case seen in HS#2064 where it was required on resumption 15)
			if (!empty($updraftplus->no_checkin_last_time) || !$updraftplus->newresumption_scheduled) {
				// Apr 2015: !$updraftplus->newresumption_scheduled added after seeing a log where there was no activity on resumption 9, and extra resumption 10 then tried the same operation.
				if ($updraftplus->current_resumption - $updraftplus->last_successful_resumption > 2 || !$updraftplus->newresumption_scheduled) {
					$this->try_split = true;
				} elseif ($updraftplus->current_resumption <= 10) {
					$maxzipbatch = $updraftplus->jobdata_get('maxzipbatch', 26214400);
					if ((int) $maxzipbatch < 1) $maxzipbatch = 26214400;
					$new_maxzipbatch = max(floor($maxzipbatch * 0.75), 20971520);
					if ($new_maxzipbatch < $maxzipbatch) {
						$updraftplus->log("No check-in was detected on the previous run - as a result, we are reducing the batch amount (old=$maxzipbatch, new=$new_maxzipbatch)");
						$updraftplus->jobdata_set('maxzipbatch', $new_maxzipbatch);
						$updraftplus->jobdata_set('maxzipbatch_ceiling', $new_maxzipbatch);
					}
				}
			}
		}

		if ('finished' != $job_status && !UpdraftPlus_Filesystem_Functions::really_is_writable($this->updraft_dir)) {
			$updraftplus->log("Backup directory (".$this->updraft_dir.") is not writable, or does not exist");
			$updraftplus->log(sprintf(__("Backup directory (%s) is not writable, or does not exist.", 'updraftplus'), $this->updraft_dir), 'error');
			return array();
		}

		$this->job_file_entities = $updraftplus->jobdata_get('job_file_entities');
		
		// This is just used for the visual feedback (via the 'substatus' key)
		$which_entity = 0;
		// e.g. plugins, themes, uploads, others
		// $whichdir might be an array (if $youwhat is 'more')

		// Returns an array (keyed off the entity) of ($timestamp, $filename) arrays
		$existing_zips = $this->find_existing_zips($this->updraft_dir, $updraftplus->file_nonce);

		$possible_backups = $updraftplus->get_backupable_file_entities(true);

		foreach ($possible_backups as $youwhat => $whichdir) {

			if (!isset($this->job_file_entities[$youwhat])) {
				$updraftplus->log("No backup of $youwhat: excluded by user's options");
				continue;
			}

			$index = (int) $this->job_file_entities[$youwhat]['index'];
			if (empty($index)) $index=0;
			$indextext = (0 == $index) ? '' : (1+$index);

			$zip_file = $this->updraft_dir.'/'.$backup_file_basename.'-'.$youwhat.$indextext.'.zip';

			// Split needed?
			$split_every = max((int) $updraftplus->jobdata_get('split_every'), 250);

			if (false != ($existing_file = $this->file_exists($existing_zips, $youwhat, $index)) && filesize($this->updraft_dir.'/'.$existing_file) > $split_every*1048576) {
				$index++;
				$this->job_file_entities[$youwhat]['index'] = $index;
				$updraftplus->jobdata_set('job_file_entities', $this->job_file_entities);
			}

			// Populate prior parts of $backup_array, if we're on a subsequent zip file
			if ($index > 0) {
				for ($i=0; $i<$index; $i++) {
					$itext = (0 == $i) ? '' : ($i+1);
					// Get the previously-stored filename if possible (which should be always); failing that, base it on the current run

					$zip_file = (isset($this->backup_files_array[$youwhat]) && isset($this->backup_files_array[$youwhat][$i])) ? $this->backup_files_array[$youwhat][$i] : $backup_file_basename.'-'.$youwhat.$itext.'.zip';

					$backup_array[$youwhat][$i] = $zip_file;
					$z = $this->updraft_dir.'/'.$zip_file;
					$itext = (0 == $i) ? '' : $i;

					$fs_key = $youwhat.$itext.'-size';
					if (file_exists($z)) {
						$backup_array[$fs_key] = filesize($z);
					} elseif (isset($this->backup_files_array[$fs_key])) {
						$backup_array[$fs_key] = $this->backup_files_array[$fs_key];
					}
				}
			}

			// I am not certain that all the conditions in here are possible. But there's no harm.
			if ('finished' == $job_status) {
				// Add the final part of the array
				if ($index > 0) {
					$zip_file = (isset($this->backup_files_array[$youwhat]) && isset($this->backup_files_array[$youwhat][$index])) ? $this->backup_files_array[$youwhat][$index] : $backup_file_basename.'-'.$youwhat.($index+1).'.zip';
					$z = $this->updraft_dir.'/'.$zip_file;
					$fs_key = $youwhat.$index.'-size';
					$backup_array[$youwhat][$index] = $zip_file;
					if (file_exists($z)) {
						$backup_array[$fs_key] = filesize($z);
					} elseif (isset($this->backup_files_array[$fs_key])) {
						$backup_array[$fs_key] = $this->backup_files_array[$fs_key];
					}
				} else {
					$zip_file = (isset($this->backup_files_array[$youwhat]) && isset($this->backup_files_array[$youwhat][0])) ? $this->backup_files_array[$youwhat][0] : $backup_file_basename.'-'.$youwhat.'.zip';

					$backup_array[$youwhat] = $zip_file;
					$fs_key=$youwhat.'-size';

					if (file_exists($zip_file)) {
						$backup_array[$fs_key] = filesize($zip_file);
					} elseif (isset($this->backup_files_array[$fs_key])) {
						$backup_array[$fs_key] = $this->backup_files_array[$fs_key];
					}
				}
			} else {

				$which_entity++;
				$updraftplus->jobdata_set('filecreating_substatus', array('e' => $youwhat, 'i' => $which_entity, 't' => count($this->job_file_entities)));

				if ('others' == $youwhat) $updraftplus->log("Beginning backup of other directories found in the content directory (index: $index)");

				// Apply a filter to allow add-ons to provide their own method for creating a zip of the entity
				$created = apply_filters('updraftplus_backup_makezip_'.$youwhat, $whichdir, $backup_file_basename, $index);

				// If the filter did not lead to something being created, then use the default method
				if ($created === $whichdir) {

					// http://www.phpconcept.net/pclzip/user-guide/53
					/* First parameter to create is:
						An array of filenames or dirnames,
						or
						A string containing the filename or a dirname,
						or
						A string containing a list of filename or dirname separated by a comma.
					*/

					if ('others' == $youwhat) {
						$dirlist = $updraftplus->backup_others_dirlist(true);
					} elseif ('uploads' == $youwhat) {
						$dirlist = $updraftplus->backup_uploads_dirlist(true);
					} else {
						$dirlist = $whichdir;
						if (is_array($dirlist)) $dirlist = array_shift($dirlist);
					}

					if (!empty($dirlist)) {
						$created = $this->create_zip($dirlist, $youwhat, $backup_file_basename, $index);
						// Now, store the results
						if (!is_string($created) && !is_array($created)) $updraftplus->log("$youwhat: create_zip returned an error");
					} else {
						$updraftplus->log("No backup of $youwhat: there was nothing found to backup");
					}
				}

				if ($created != $whichdir && (is_string($created) || is_array($created))) {
					if (is_string($created)) $created =array($created);
					foreach ($created as $fname) {
						$backup_array[$youwhat][$index] = $fname;
						$itext = (0 == $index) ? '' : $index;
						$index++;
						$backup_array[$youwhat.$itext.'-size'] = filesize($this->updraft_dir.'/'.$fname);
					}
				}

				$this->job_file_entities[$youwhat]['index'] = $this->index;
				$updraftplus->jobdata_set('job_file_entities', $this->job_file_entities);

			}
		}

		return $backup_array;
	}

	/**
	 * This uses a saved status indicator; its only purpose is to indicate *total* completion; there is no actual danger, just wasted time, in resuming when it was not needed. So the saved status indicator just helps save resources.
	 *
	 * @param Integer $resumption_no Check for first run
	 *
	 * @return Array
	 */
	public function resumable_backup_of_files($resumption_no) {
		global $updraftplus;
		// Backup directories and return a numerically indexed array of file paths to the backup files
		$bfiles_status = $updraftplus->jobdata_get('backup_files');
		$this->backup_files_array = $updraftplus->jobdata_get('backup_files_array');

		if (!is_array($this->backup_files_array)) $this->backup_files_array = array();
		if ('finished' == $bfiles_status) {
			$updraftplus->log("Creation of backups of directories: already finished");
			// Check for recent activity
			foreach ($this->backup_files_array as $files) {
				if (!is_array($files)) $files =array($files);
				foreach ($files as $file) $updraftplus->check_recent_modification($this->updraft_dir.'/'.$file);
			}
		} elseif ('begun' == $bfiles_status) {
			$this->first_run = apply_filters('updraftplus_filerun_firstrun', 0);
			if ($resumption_no > $this->first_run) {
				$updraftplus->log("Creation of backups of directories: had begun; will resume");
			} else {
				$updraftplus->log("Creation of backups of directories: beginning");
			}
			$updraftplus->jobdata_set('jobstatus', 'filescreating');
			$this->backup_files_array = $this->backup_dirs($bfiles_status);
			$updraftplus->jobdata_set('backup_files_array', $this->backup_files_array);
			$updraftplus->jobdata_set('backup_files', 'finished');
			$updraftplus->jobdata_set('jobstatus', 'filescreated');
		} else {
			// This is not necessarily a backup run which is meant to contain files at all
			$updraftplus->log('This backup run is not intended for files - skipping');
			return array();
		}

		/*
		// DOES NOT WORK: there is no crash-safe way to do this here - have to be renamed at cloud-upload time instead
		$new_backup_array = array();
		foreach ($backup_array as $entity => $files) {
			if (!is_array($files)) $files=array($files);
			$outof = count($files);
			foreach ($files as $ind => $file) {
				$nval = $file;
				if (preg_match('/^(backup_[\-0-9]{15}_.*_[0-9a-f]{12}-[\-a-z]+)([0-9]+)?\.zip$/i', $file, $matches)) {
					$num = max((int)$matches[2],1);
					$new = $matches[1].$num.'of'.$outof.'.zip';
					if (file_exists($this->updraft_dir.'/'.$file)) {
						if (@rename($this->updraft_dir.'/'.$file, $this->updraft_dir.'/'.$new)) {
							$updraftplus->log(sprintf("Renaming: %s to %s", $file, $new));
							$nval = $new;
						}
					} elseif (file_exists($this->updraft_dir.'/'.$new)) {
						$nval = $new;
					}
				}
				$new_backup_array[$entity][$ind] = $nval;
			}
		}
		*/
		return $this->backup_files_array;
	}

	/**
	 * This function is resumable, using the following method:
	 * Each table is written out to ($final_filename).table.tmp
	 * When the writing finishes, it is renamed to ($final_filename).table
	 * When all tables are finished, they are concatenated into the final file
	 *
	 * @param String $already_done Status of backup
	 * @param String $whichdb      Indicated which database is being backed up
	 * @param Array  $dbinfo       is only used when whichdb != 'wp'; and the keys should be: user, pass, name, host, prefix
	 *
	 * @return Boolean|String - the basename of the database backup, or false for failure
	 */
	public function backup_db($already_done = 'begun', $whichdb = 'wp', $dbinfo = array()) {

		global $updraftplus, $wpdb;

		$this->whichdb = $whichdb;
		$this->whichdb_suffix = ('wp' == $whichdb) ? '' : $whichdb;

		if (!$updraftplus->backup_time) $updraftplus->backup_time_nonce();
		if (!$updraftplus->opened_log_time) $updraftplus->logfile_open($updraftplus->nonce);

		if ('wp' == $this->whichdb) {
			$this->wpdb_obj = $wpdb;
			// The table prefix after being filtered - i.e. what filters what we'll actually backup
			$this->table_prefix = $updraftplus->get_table_prefix(true);
			// The unfiltered table prefix - i.e. the real prefix that things are relative to
			$this->table_prefix_raw = $updraftplus->get_table_prefix(false);
			$dbinfo['host'] = DB_HOST;
			$dbinfo['name'] = DB_NAME;
			$dbinfo['user'] = DB_USER;
			$dbinfo['pass'] = DB_PASSWORD;
		} else {
			if (!is_array($dbinfo) || empty($dbinfo['host'])) return false;
			// The methods that we may use: check_connection (WP>=3.9), get_results, get_row, query
			$this->wpdb_obj = new UpdraftPlus_WPDB_OtherDB($dbinfo['user'], $dbinfo['pass'], $dbinfo['name'], $dbinfo['host']);
			if (!empty($this->wpdb_obj->error)) {
				$updraftplus->log($dbinfo['user'].'@'.$dbinfo['host'].'/'.$dbinfo['name'].' : database connection attempt failed');
				$updraftplus->log($dbinfo['user'].'@'.$dbinfo['host'].'/'.$dbinfo['name'].' : '.__('database connection attempt failed.', 'updraftplus').' '.__('Connection failed: check your access details, that the database server is up, and that the network connection is not firewalled.', 'updraftplus'), 'error');
				return $updraftplus->log_wp_error($this->wpdb_obj->error);
			}
			$this->table_prefix = $dbinfo['prefix'];
			$this->table_prefix_raw =