/var/www/(Del)hsihk.com/wp-content/plugins/backupbuddy/lib/xzipbuddy/zbzipexec.php


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
<?php
/**
 *    pluginbuddy_zbzipexec Class
 *
 *  Extends the zip capability core class with proc specific capability
 *    
 *    Version: 1.0.0
 *    Author:
 *    Author URI:
 *
 *    @param        $parent        object        Optional parent object which can provide functions for reporting, etc.
 *    @return        null
 *
 */
if ( !class_exists"pluginbuddy_zbzipexec" ) ) {

    
/**
     *    pb_backupbuddy_exec_helper Class
     *
     *    Extends the parent pb_backupbuddy_zip_helper class for the exec method.
     *    Although we are having the instance handling here it isn't strictly required
     *    for teh exec method because we have no callbacks to handle - but does no harm
     *    and maybe we'll just elevate this to the abstract class?
     *
     */
    
class pb_backupbuddy_exec_helper extends pb_backupbuddy_zip_helper {
    
        
// This is a deliberately low default period for now as we have found that some
        // servers get slower and slower so if this is too high the burst content size gets
        // increased too quickly and then when the server slows down it takes too long
        // for a burst and we still get the server timeout. Aim is to make this configurable
        // and adaptive in some way.
        
const ZIP_EXEC_BURST_MAX_PERIOD 20;
    
        protected 
$_burst_content_size 0;
        protected 
$_burst_content_count 0;
        protected 
$_burst_count 0;
        protected 
$_burst_content_complete false;
        protected 
$_last_burst_duration 0;
        protected 
$_last_burst_size 0;

        
/**
         * Our object instance
         * 
         * @var $_instance     object
         */
        
protected static $_instance NULL;
    
        
// Create an instance - normally would call this
        /**
         *    __construct()
         *    
         *    Default constructor.
         *    Record our own instance and then use the parent constructor.
         *    
         *    @return        none
         *
         */
        
public function __construct() {
        
            
self::$_instance $this;
            
parent::__construct();
            
            
// Override the 'auto' value already set as that is based on max_execution_time
            // which is not so relevant for exec mode - we are more concerned with timeout like
            // fcgid iotimeout which we cannot know programmatically - so assume a
            // common minimum (so our maximum burst period) and then we reset the burst
            // threshold period by 'auto' based on the max period we just set - although
            // the burst threshold period doesn't really come into play here because we are
            // working by size rather than period.
            
$this->set_burst_max_periodself::ZIP_EXEC_BURST_MAX_PERIOD );
            
$this->set_burst_threshold_period'auto' );
        }
        
        
/**
         *    __destruct()
         *    
         *    Default destructor.
         *    Nullify our own instance and then use the parent destructor.
         *    
         *    @return        none
         *
         */
        
public function __destruct() {
        
            
self::$_instance NULL;
            
parent::__destruct();
        
        }
    
        
/**
         * 
         *    get_instance()
         *
         *    If the object is already created then simply return the instance else
         *    create an object and return the instance.
         *    Currently only one instance is allowed at a time but currently there is
         *    no scenario that would require more than one at any time.
         *
         *    @return        object                    This object instance    
         *
         */
        
public static function get_instance() {
        
            if ( 
NULL === self::$_instance ) {
            
                
self::$_instance = new self;
                
            }
        
            return 
self::$_instance;
            
        }
        
        public function 
get_burst_count() {
        
            return 
$this->_burst_count;
        }
        
        public function 
get_burst_content_size() {
        
            return 
$this->_burst_content_size;
        
        }
        
        public function 
get_burst_content_count() {
        
            return 
$this->_burst_content_count;
        
        }
        
        
/**
         * 
         *    burst_begin()
         *
         *    Initializes to begin putting together content for a new burst
         *
         *    @return        none
         *
         */
        
public function burst_begin() {
        
            
$this->_burst_content_size 0;
            
$this->_burst_content_count 0;
            ++
$this->_burst_count;
            
$this->_burst_content_complete false;
            
$this->_last_burst_duration 0;
            
$this->_last_burst_size 0;
        
        }
        
        
/**
         * 
         *    burst_end()
         *
         *    Wrap up after the end of the current burst
         *
         *    @return        none
         *
         */
        
public function burst_end() {
        
            
// Used to make sure we do not report items multiple times
            // Bit of a kludge for now
            
$this->_reported false;
            
            
// Burst is finished - do all those periodic tasks
            
$this->monitor_progress);
            
$this->monitor_usage();
            
$this->handle_burst_mode();
            
$this->tickle_server();
        
        }
        
        
/**
         * 
         *    burst_content_added()
         *
         *    Gives us information on what has just been added to burst content so we
         *    can assess the progress against our criteria for completion of the current
         *    burst content.
         *
         *    @param        array        $content    Details about the item just added
         *    @return        none
         *
         */
        
public function burst_content_added$content ) {
        
            
// Increment the appropriate count
            
true === $content'directory' ] ) ? $this->incr_added_dir_count() : $this->incr_added_file_count() ;
            
            
// Increment the total size of current burst
            
$this->_burst_content_size += (int)$content'size' ];
            ++
$this->_burst_content_count;
            
            
$this->_burst_content_complete = ( $this->get_burst_current_size_threshold() <= $this->_burst_content_size );
            
        }
        
        
/**
         * 
         *    burst_content_complete()
         *
         *    Return whether or not we consider the burst content to be complete for the
         *    current burst
         *
         *    @return        bool                    True if complete, false otherwise
         *
         */
        
public function burst_content_complete() {
        
            return 
$this->_burst_content_complete;
        
        }
        
        
/**
         * 
         *    burst_start()
         *
         *    Signals that the burst activity is about to be started so we can start to
         *    monitor it for the purposes of assessing how it went and how that will impact
         *    the next burst
         *
         *    @return        none
         *
         */
        
public function burst_start() {
        
            
$this->set_burst_start_timetime() ); // Note when we started
        
        
}
        
        
/**
         * 
         *    burst_stop()
         *
         *    Signals that the burst activity has completed so we can stop the monitoring
         *    and decide how the next burst is going to go
         *
         *    @return        none
         *
         */
        
public function burst_stop() {
        
            
$this->set_burst_stop_time();
            
            
// Update the threshold in case we have more to do
            
$this->update_burst_current_size_threshold();
            
        }
        
        
/**
         * 
         *    update_burst_current_size_threshold()
         *
         *    Signals that the burst activity has completed so we can stop the monitoring
         *    and decide how the next burst is going to go
         *
         *    Current algorithm is quite simple:
         *    Nbt - New Burst Threshold
         *    Cbt - Current Burst Threshold
         *    Lbd - Last Burst Duration
         *    Bdmp - Burst Default Max Period
         *    
         *    Nbt = Cbt + ( Cbt * ( ( Bdmp - Ldb ) / Bdmp ) )
         *    
         *    Which basically means the longer the burst of the current size threshold takes
         *    to complete the smaller the amount by which we increase the burst size threshold.
         *    Additionally, if the actual last burst duration _exceeds_ the maximum time we want
         *    to allow a burst to run then the increment factor will become negative and we'll
         *    reduce the burst size threshold, the bigger the overrun the bigger the reduction.
         *    Finally we'll make sure that we keep the threshold within some min/max limits
         *    which are currently predefined but in theory later we could make these adaptive
         *    and/or allow the user to set them to allow for specific server capabilities - i.e.,
         *    if the server is very fast then the high cap could be raised.
         *
         *    Note: an additional option would be to allow the user to set an initial
         *    threshold size and if that were very large (or maybe 0 meaning no limit) then
         *    the process would revert to a single burst.
         *
         *    @return        none
         *
         */
        
public function update_burst_current_size_threshold() {
        
            
$last_burst_duration = ( $this->get_burst_stop_time() - $this->get_burst_start_time() );
            
$last_burst_duration = ( $last_burst_duration ) ? $last_burst_duration;
            
            
// Calculate the increment factor - this will be +ve if the last burst took less
            // than our allowed maximum time (so we can try increasing the burst content size) or
            // -ve if the burst took longer than we would like (in which case we'll reduce the
            // burst content size).
            
$factor = (float)( ( (float)$this->get_burst_max_period() - (float)$last_burst_duration ) / (float)$this->get_burst_max_period() );
            
            
// Calculate a new burst size threshold - under extreme conditions it could come
            // out negative but in any case we're then going to make sure it is within certain
            // sensible bounds.
            
$this->set_burst_current_size_threshold ( (int)( $this->get_burst_current_size_threshold() + ( (float)$this->get_burst_current_size_threshold() * (float)$factor) ) );

            
// Now let's make sure we stay within min/max threshoild limits
            
$this->set_burst_current_size_threshold ( ( $this->get_burst_size_min() > $this->get_burst_current_size_threshold() ) ? $this->get_burst_size_min() : $this->get_burst_current_size_threshold() );
            
$this->set_burst_current_size_threshold ( ( $this->get_burst_current_size_threshold() < $this->get_burst_size_max() ) ? $this->get_burst_current_size_threshold() : $this->get_burst_size_max() );
            
        }

    }

    class 
pluginbuddy_zbzipexec extends pluginbuddy_zbzipcore {
    
        
// Constants for file handling
        
const ZIP_LOG_FILE_NAME        'temp_zip_exec_log.txt';
        const 
ZIP_ERRORS_FILE_NAME     'last_exec_errors.txt';
        const 
ZIP_WARNINGS_FILE_NAME   'last_exec_warnings.txt';
        const 
ZIP_OTHERS_FILE_NAME     'last_exec_others.txt';
        const 
ZIP_CONTENT_FILE_NAME    'last_exec_list.txt';
        const 
ZIP_EXCLUSIONS_FILE_NAME 'exclusions.txt';
        const 
ZIP_INCLUSIONS_FILE_NAME 'inclusions.txt';
        const 
ZIP_TEST_FILE            '/zbzip.php'// Contains file test.txt with content "Hello World"
        
const ZIP_TEST_FILE_SIG        "0a0f9b28c5ff89dfb4f2a0472be0ea8f";
        
        
// Possible executable path sets
        
const DEFAULT_EXECUTABLE_PATHS '/usr/local/bin::/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/bin';
        const 
WINDOWS_EXECUTABLE_PATHS '';
        
        
/**
         * method tag used to refer to the method and entities associated with it such as class name
         * 
         * @var $_method_tag     string
         */
        
public static $_method_tag 'exec';
            
        
/**
         * This tells us whether this method is regarded as a "compatibility" method
         * 
         * @var bool
         */
        
public static $_is_compatibility_method false;
            
        
/**
         * This tells us the dependencies of this method so they can be check to see if the method can be supported
         * 
         * @var array
         */
        
public static $_method_dependencies = array( 'classes' => array(),
                                                       
'functions' => array( 'exec' ),
                                                       
'extensions' => array(),
                                                       
'files' => array(),
                                                       
'check_func' => 'check_method_dependencies_static'
                                                    
);
            
        
/**
         * Boolean to indicate if we can support comment handling based on dependency check
         * 
         * @var $_allow_is_commenter bool
         */
        
protected static $_allow_is_commenter true;
        
        
/**
         * 
         * get_method_tag_static()
         *
         * Get the static method tag in a static context
         *
         * @return        string    The method tag
         *
         */
        
public static function get_method_tag_static() {
        
            return 
self::$_method_tag;
            
        }

        
/**
         * 
         * get_is_compatibility_method_static()
         *
         * Get the compatibility method indicator in a static context
         *
         * @return        bool    True if is a compatibility method
         *
         */
        
public static function get_is_compatibility_method_static() {
        
            return 
self::$_is_compatibility_method;
        }

        
/**
         * 
         * get_method_dependencies_static()
         *
         * Get the method dependencies array in a static context
         *
         * @return        array    The dependencies of the method that is requires to be a supported method
         *
         */
        
public static function get_method_dependencies_static() {
        
            return 
self::$_method_dependencies;
        }

        
/**
         * 
         * check_method_dependencies_static()
         *
         * Allows additional method dependency checks beyond the standard in a static context
         *
         * @return        bool    True if additional dependency checks passed
         *
         */
        
public static function check_method_dependencies_static() {
        
            
$result true;
            
            
// Need to check if function escapeshellarg os available - if not then exec cannot
            // be used for comment handling. This isn't a show stopper so we'll return true
            // but set an internal flag to disable commenting capability.
            
            
$functions = array( 'escapeshellarg' );
            
            
$disabled_functions array_map"trim"explode','ini_get'disable_functions' ) ) );
            
            
// Check each function dependency and bail out on first failure
            
foreach ( $functions as $function ) {
            
                
$function trim$function );
                
                if ( !( ( 
function_exists$function ) ) && ( !in_array$function$disabled_functions ) ) ) ) {

                    
$result false;
                    break;
                    
                }
            
            }
            
            if ( 
false === $result ) {
            
                
// Found that escapeshellarg not available so exec cannot be used for comment handling
                
self::$_allow_is_commenter false;
            
            }
            
            return 
true;
        
        }

        
/**
         *    __construct()
         *    
         *    Default constructor.
         *    
         *    @param        reference    &$parent        [optional] Reference to the object containing the status() function for status updates.
         *    @return        null
         *
         */
        
public function __construct( &$parent NULL ) {

            
parent::__construct$parent );
            
            
// Set the internal flag indicating if exec_dir is set in the PHP environment
            
$this->set_exec_dir_flag();
            
            
// Setup the OS specific null device for if we need/can use it
            
$this->set_null_device();
            
            
// Override some of parent defaults
            
$this->_method_details'attr' ] = array_merge$this->_method_details'attr' ],
                                                            array( 
'name' => 'Exec Method',
                                                                     
'compatibility' => pluginbuddy_zbzipexec::$_is_compatibility_method )
                                                             );
                                                             
            
// Now set up the default executable paths (not merging but setting)
            // Note: Parent constructor set the os type value
            
switch ( $this->get_os_type() ) {
            
                case 
self::OS_TYPE_NIX:
                
                    
$this->set_executable_pathsexplodePATH_SEPARATORself::DEFAULT_EXECUTABLE_PATHS ), false);
                    break;
                    
                case 
self::OS_TYPE_WIN:
                    
                    
$this->set_executable_pathsexplodePATH_SEPARATORself::WINDOWS_EXECUTABLE_PATHS ), false);
                    
                    
// Need to merge in ABSPATH here because we cannot set that in the defaults - it is prepended
                    
$this->set_executable_paths( array( rtrimABSPATHDIRECTORY_SEPARATOR ) ) );
                    break;
                    
                default:
                    
// Log error and leave paths empty
                    
pb_backupbuddy::status'details'sprintf__('Unknown OS type (%1$s) could not set executable paths','it-l10n-backupbuddy' ), $this->get_os_type() ) );
                    
            }
            
        }
        
        
/**
         *    __destruct()
         *    
         *    Default destructor.
         *    
         *    @return        null
         *
         */
        
public function __destruct( ) {
        
            
parent::__destruct();

        }
        
        
/**
         *    get_method_tag()
         *    
         *    Returns the (static) method tag
         *    
         *    @return        string The method tag
         *
         */
        
public function get_method_tag() {
        
            return 
pluginbuddy_zbzipexec::$_method_tag;
            
        }
        
        
/**
         *    get_is_compatibility_method()
         *    
         *    Returns the (static) is_compatibility_method boolean
         *    
         *    @return        bool
         *
         */
        
public function get_is_compatibility_method() {
        
            return 
pluginbuddy_zbzipexec::$_is_compatibility_method;
            
        }
        
        
/**
         *    get_command_path()
         *    
         *    This returns the path for the requested command from the method details
         *    If not found then will return empty string which is the same as if the
         *    command is being accessed through PATH
         *    
         *    @return        string                Path for command, trimmed - may be empty
         *
         */
        
protected function get_command_path$command self::COMMAND_UNKNOWN_PATH ) {
        
            
$result '';
            
            switch( 
$command ) {
            
                case 
self::COMMAND_ZIP_PATH:
                
                    
// If there is a common path use it otherwise look for the command specific path
                    
if ( isset( $this->_method_details'param' ][ 'path' ] ) ) {
                    
                        
$result trim$this->_method_details'param' ][ 'path' ] );
                        
                    } elseif ( isset( 
$this->_method_details'param' ][ 'zip' ][ 'path' ] ) ) {
                    
                        
$result trim$this->_method_details'param' ][ 'zip' ][ 'path' ] );
                    }
                    
                    break;
                
                case 
self::COMMAND_UNZIP_PATH:
                
                    
// If there is a common path use it otherwise look for the command specific path
                    
if ( isset( $this->_method_details'param' ][ 'path' ] ) ) {
                    
                        
$result trim$this->_method_details'param' ][ 'path' ] );
                        
                    } elseif ( isset( 
$this->_method_details'param' ][ 'unzip' ][ 'path' ] ) ) {
                    
                        
$result trim$this->_method_details'param' ][ 'unzip' ][ 'path' ] );
                    }
                    
                    break;
                
                default:
                
                    
// Return the empty string default for now
            
            
}

            return 
$result;
        
        }
        
        
/**
         *    set_zip_version()
         *    
         *    This sets the zip version information in the method details
         *    Use "zip -h" to get a standardized help output that contains the zip version.
         *    Theoretically we should be able to use "zip -v" to get zip version and build
         *    details but pre-v3 zip running "zip -v" will not produce the required output because
         *    there is no tty attached (when running through exec() or equivalent), instead
         *    it will (or should) produce a zip file. However, it has been found that even this
         *    is not reliable and some installations just seem to freeze when "zip -v" is run
         *    which borks the whole process.
         *    So we use "zip -h" first to get the basic zip version information and as a future
         *    extension if it is version 3.0+ (3.0 is current and 3.1 hasn't been officially
         *    released) we may then run "zip -v" to get the extended version and build information.
         *    
         *    @param        int        $major        Value to use if none found or override true
         *    @param        int        $minor        Value to use if none found or override true
         *    @param        bool    $override    True to use passed in value(s) regardless
         *    @return        object                This object reference
         *
         */
        
protected function set_zip_version$major 0$minor 0$override false ) {
        
            
$exitcode 127;
            
$output = array();
            
$zippath '';
            
$command '';
            
$matches = array();
            
$info '';
        
            
// If we have been given a value to use with override then just use it
            
if ( ( ( is_int$major) ) && ( $major ) && ( is_int$minor ) ) ) && ( true === $override ) ) {
            
                
// Set the given version regardless
                
$this->_method_details'param' ][ 'zip' ][ 'version' ] = array( 'major' => $major'minor' => $minor );
                return 
$this
            
            }
            
            
// Get the command path for the zip command - should return a trimmed string
            
$zippath $this->get_command_pathself::COMMAND_ZIP_PATH );
            
            
// Add the trailing slash if required
            
$command $this->slashify$zippath ) . 'zip -h';
            @
exec$command$output$exitcode );
            
            if ( 
=== $exitcode ) {
            
                
// Expect format like: Zip 3.0 (July 5th 2008)...
                //                     Zip 3.1c BETA (June 22nd 2010)...
                // The match should take only the major/minor digits and ignore any following alpha
                // May extend to capture the alpha and also whether BETA indicated but not currently
                // required.
                
foreach ( $output as $line ) {

                    if ( 
preg_match'/^\s*(zip)\s+(?P<major>\d)\.(?P<minor>\d+)/i'$line$matches ) ) {
                    
                        
$major = (int)$matches'major' ];
                        
$minor = (int)$matches'minor' ];
                        break;
                    
                    }
                
                }
                
                
// If we didn't match a version then suspect this is still not valid version info
//                 if ( !empty( $matches ) ) {
//                 
//                     // We did match a version so check if we have a chance of getting additional information
//                     if ( 3 === $major ) {
//                     
//                         $exitcode = 127;
//                         $output = array();
//                     
//                         // Add the trailing slash if required
//                         $command = $this->slashify( $zippath ) . 'zip -v';
//                         @exec( $command, $output, $exitcode );
//                         
//                         if ( 0 === $exitcode ) {
//                 
//                             // Now create the info string
//                             // Note: not worth compressing as that gives a larger string after converting
//                             // from binary to hex format for saving
//                             $info = implode( PHP_EOL, $output );
//                             $this->_method_details[ 'param' ][ 'zip' ][ 'info' ] = $info;
//                         
//                         }
//                     
//                     }
//                 
//                 }
            
            
}

            
// Now use either what we got or what we were given...
            
if ( ( is_int$major) ) && ( $major ) && ( is_int$minor ) ) ) {
            
                
// Set the given version regardless
                
$this->_method_details'param' ][ 'zip' ][ 'version' ] = array( 'major' => $major'minor' => $minor );
            
            }
            
            return 
$this
        
        }
        
        
/**
         *    get_zip_version()
         *    
         *    This gets the zip version as an array of major/minor or returns false if not known
         *    TODO: Pass parameter to specify what format to return in
         *    
         *    @return        array|bool                Returns array(major, minor) or false if not known
         *
         */
        
protected function get_zip_version() {
        
            
$result $this->_method_details'param' ][ 'zip' ][ 'version' ];
            
            if ( 
=== $result'major' ] ) {
            
                
$result false;
                
            }
            
            return 
$result;
            
        }
        
        
/**
         *    set_unzip_version()
         *    
         *    This sets the unzip version information in the method details
         *    
         *    @param        int        $major        Value to use if none found or override true
         *    @param        int        $minor        Value to use if none found or override true
         *    @param        bool    $override    True to use passed in value(s) regardless
         *    @return        object                This object reference
         *
         */
        
protected function set_unzip_version$major 0$minor 0$override false ) {
        
            
$exitcode 0;
            
$output = array();
            
$zippath '';
            
$command '';
            
$matches = array();
        
            
// If we have been given a value to use with override then just use it
            
if ( ( ( is_int$major) ) && ( $major ) && ( is_int$minor ) ) ) && ( true === $override ) ) {
            
                
// Set the given version regardless
                
$this->_method_details'param' ][ 'unzip' ][ 'version' ] = array( 'major' => $major'minor' => $minor );
                return 
$this
            
            }
            
            
// Get the command path for the unzip command - should return a trimmed string
            
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
            
            
// Add the trailing slash if required
            
$command $this->slashify$zippath ) . 'unzip -v';    
            @
exec$command$output$exitcode );
            
            if ( 
=== $exitcode ) {
            
                
// Should be good output to try at least
                
foreach ( $output as $line ) {

                    if ( 
preg_match'/^\s*(unzip)\s+(?P<major>\d)\.(?P<minor>\d+)/i'$line$matches ) ) {
                    
                        
$major = (int)$matches'major' ];
                        
$minor = (int)$matches'minor' ];
                        break;
                    
                    }
                
                }
            
                
// Now create the info string
                // Note: not worth compressing as that gives a larger string after converting
                // from binary to hex format for saving
                
$info implodePHP_EOL$output );
                
$this->_method_details'param' ][ 'unzip' ][ 'info' ] = $info;
                
            }
            
            
// Now use either what we got or what we were given...
            
if ( ( is_int$major) ) && ( $major ) && ( is_int$minor ) ) ) {
            
                
// Set the given version regardless
                
$this->_method_details'param' ][ 'unzip' ][ 'version' ] = array( 'major' => $major'minor' => $minor );
            
            }
            
            return 
$this
        
        }
        
        
/**
         *    get_unzip_version()
         *    
         *    This gets the unzip version as an array of major/minor or returns false if not known
         *    TODO: Pass parameter to specify what format to return in
         *    
         *    @return        array|bool                Returns array(major, minor) or false if not known
         *
         */
        
protected function get_unzip_version() {
        
            
$result $this->_method_details'param' ][ 'unzip' ][ 'version' ];
            
            if ( 
=== $result'major' ] ) {
            
                
$result false;
                
            }
            
            return 
$result;
            
        }
        
        
/**
         *    get_zip_supports_logfile()
         *    
         *    This returns true if the zip in use is able to support logfile usage for
         *    logging progress of zip operation
         *    
         *    @return        bool                True if logfile supported, otherwise false
         *
         */
        
protected function get_zip_supports_log_file() {
        
            
$result false;
            
            
// Currently check based just on the zip major version
            // TODO: decide if better to respond based on the available options
            
if ( <= $this->_method_details'param' ][ 'zip' ][ 'version' ][ 'major' ] ) {
            
                
$result true;
                
            }
            
            return 
$result;
        
        }
        
        
/**
         *    is_available()
         *    
         *    A function that tests for the availability of the specific method and its available modes. Will test for
         *  multiple modes (zip & unzip) and only return false if neither is available. Actual available modes will
         *  be indicated in the method attributes.
         *
         *  Note: in this case as the zip and unzip capabilities are provided by external commands we need to test
         *  for the availability of both of them and set attributes accordingly
         *    
         *    @param        string    $tempdir    Temporary directory to use for any test files (must be writeable)
         *    @return        bool                True if the method is available for at least one mode, false otherwise
         *
         */
        
public function is_available$tempdir ) {
        
            
$result false;
        
            
// This is just a nicety for now until platform handling is fully resolved
            
switch ( $this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->is_available_generic$tempdir );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->is_available_generic$tempdir );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
                          
        }
        
        
/**
         *    is_available_generic()
         *    
         *    A function that tests for the availability of the specific method and its available modes. Will test for
         *  multiple modes (zip & unzip) and only return false if neither is available. Actual available modes will
         *  be indicated in the method attributes.
         *
         *  Note: in this case as the zip and unzip capabilities are provided by external commands we need to test
         *  for the availability of both of them and set attributes accordingly
         *    
         *    @param        string    $tempdir    Temporary directory to use for any test files (must be writeable)
         *    @return        bool                True if the method is available for at least one mode, false otherwise
         *
         */
        
protected function is_available_generic$tempdir ) {
        
            
$result false;
            
$pending_result false;
            
$found_zip false;
            
            
// This is a safety value in case exec() fails - hopefully it will not update this
            
$exec_exit_code 127;
            
            if ( 
function_exists'exec' ) ) {
            
                
$candidate_paths $this->get_executable_paths();
                
                
// We are searching for zip using the list of possible paths
                
while ( ( false == $found_zip ) && ( !empty( $candidate_paths ) ) ) {
                
                    
// Make sure it is clean of leading/trailing whitespace
                    
$path trimarray_shift$candidate_paths ) );
                    
                    
pb_backupbuddy::status'details'__'Exec test (zip) trying executable path:','it-l10n-backupbuddy' ) . ' `' $path '`.' );

                    
$test_file $tempdir 'temp_test_' uniqid() . '.zip';
                    
                    
$command $this->slashify$path ) . 'zip' " '{$test_file}'" " '" __FILE__ .  "'";

                    
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                    
$command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$command ) : $command;
                                    
                    @
exec$command$exec_output$exec_exit_code );
            
                    
// Must have both a file and a success exit code to consider this successful
                    
if ( @file_exists$test_file ) && ( === $exec_exit_code ) ) {
            
                        
// Set the parameter to be remembered (note: path without trailing slash)
                        
$this->_method_details'param' ][ 'zip' ][ 'path' ] = $path;
                        
                        
// Platform independent capabilities
                        
$this->_method_details'attr' ][ 'is_zipper' ] = true;
                        
$this->_method_details'attr' ][ 'is_archiver' ] = true;
                        
                        
// Platform specific capabilities
                        
switch ( $this->get_os_type() ) {
                            case 
self::OS_TYPE_NIX:
                                
$this->_method_details'attr' ][ 'is_commenter' ] = true;
                                break;
                            case 
self::OS_TYPE_WIN:
                                
// None Applicable
                                
break;
                            default:
                                
// There is no default
                        
}
                        
                        
pb_backupbuddy::status'details'__('Exec test (zip) PASSED.','it-l10n-backupbuddy' ) );
                        
$result true;
                
                        
// TODO: Consider parsing zip file to get version of zip that created it. This may seem odd
                        // but pre-v3 zip it's not possible to run "zip -v" through exec() or equivalent as it only
                        // provides the required output if a tty is attached, otherwise it creates a zip file. We
                        // might consider parsing the created zip file but as we have already created one here we
                        // might as well use it
                        
                        // This will break us out of the loop
                        
$found_zip true;
                        
                    } else {
                
                        
// Deal with the possible failure causes
                        
if ( !@file_exists$test_file ) ) {
                        
                            
pb_backupbuddy::status'details'__('Exec test (zip) FAILED: Test zip file not found.','it-l10n-backupbuddy' ) );
                        
                        }
                        
                        if ( 
!== $exec_exit_code ) {
                        
                            
$error_string $exec_exit_code;
                            
pb_backupbuddy::status'details'__('Exec test (zip) FAILED: exec Exit Code: ','it-l10n-backupbuddy' ) . $error_string );
                            
                        }
                        
                        
$result false;
                
                    }
                    
                    
// Remove the test zip file if it was created
                    
if ( @file_exists$test_file ) ) {
                    
                        if ( !@
unlink$test_file ) ) {
                
                            
pb_backupbuddy::status'details'sprintf__('Exec test (zip) unable to delete test file (%s)','it-l10n-backupbuddy' ), $test_file ) );
                    
                        }
                
                    }
                    
                }
                
                
                
// If we didn't find zip anywhere (or maybe found it but it failed) then log it
                
if ( false === $found_zip ) {
                    
                    
pb_backupbuddy::status'details'__('Exec test (zip) FAILED: Unable to find zip executable on any specified path.','it-l10n-backupbuddy' ) );
                    
$result false;
                    
                }
                
                
// Remember zip result and reset for unzip test
                
$pending_result $result;
                
$result false;
                
                
// See if we can determine zip version and possibly available options. This can help us
                // determine how to execute operations such as creating a zip file
                
if ( true === $found_zip ) {
                    
                    
pb_backupbuddy::status'details''Checking zip version...' );

                    
$this->set_zip_version();
                    
                    
$version $this->get_zip_version();
                    if ( 
true === is_array$version ) ) {
            
                        ( ( 
== $version'major' ] ) && ( == $version'minor' ] ) ) ? $version'minor' ] = 'X' true ;
                        
pb_backupbuddy::status'details'sprintf__'Found zip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );
                
                    } else {
            
                        
$version = array( "major" => "X""minor" => "Y" );
                        
pb_backupbuddy::status'details'sprintf__'Found zip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );

                    }

                }
                
                
// Reset the candidate paths for a full search for unzip
                
$candidate_paths $this->_executable_paths;
                          
                
// Reset the safety value in case
                
$exec_exit_code 127;
                
                
// New search
                
$found_zip false;
                
                
// Using a test file
                
$test_file dirname__FILE__ ) . self::ZIP_TEST_FILE;
                
                
// It has to exist and be readable otehrwise we just have to bail on testing for unzip
                
pb_backupbuddy::status'details'sprintf__'Exec test (unzip) checking test file readable: %1$s''it-l10n-backupbuddy' ), $test_file ) );
                if ( 
is_readable$test_file ) ) {
                
                    
// Only proceed if the file looks as expected
                    
pb_backupbuddy::status'details'sprintf__'Exec test (unzip) checking test file intact: %1$s''it-l10n-backupbuddy' ), self::ZIP_TEST_FILE_SIG ) );
                    if ( 
self::ZIP_TEST_FILE_SIG === md5_file$test_file ) ) {
                
                        
// We are searching for unzip using the list of possible paths
                        
while ( ( false === $found_zip ) && ( !empty( $candidate_paths ) ) ) {
                
                            
// Make sure it is clean of leading/trailing whitespace
                            
$path trimarray_shift$candidate_paths ) );
                    
                            
pb_backupbuddy::status'details'__'Exec test (unzip) trying executable path:','it-l10n-backupbuddy' ) . ' `' $path '`.' );

                            
$command $this->slashify$path ) . 'unzip -qt' " '{$test_file}'" " 'test.txt'";
                                    
                            
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                            
$command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$command ) : $command;
                    
                            @
exec$command$exec_output$exec_exit_code );
                    
                            if ( 
$exec_exit_code === ) {
                            
                                
// Set the parameter to be remembered (note: path without trailing slash)
                                
$this->_method_details'param' ][ 'unzip' ][ 'path' ] = $path;
                        
                                
// Platform independent capabilities
                                
$this->_method_details'attr' ][ 'is_unzipper' ] = true;
                                
$this->_method_details'attr' ][ 'is_checker' ] = true;
                                
$this->_method_details'attr' ][ 'is_unarchiver' ] = true;
                                
$this->_method_details'attr' ][ 'is_lister' ] = true;
                                
$this->_method_details'attr' ][ 'is_extractor' ] = true;
                        
                                
// Platform specific capabilities
                                
switch ( $this->get_os_type() ) {
                                    case 
self::OS_TYPE_NIX:
                                
                                        
// This is special - we must have zip also so this will only end up true if we previously found zip
                                        // and speculatively set this attribute to be true. Also we need for exec_dir to not be active - if
                                        // it is the command line is escaped and that is incompatible with the piping we have to use when
                                        // setting a comment. Also we need the escapeshellarg function to be available and that was checked
                                        // when dependencies were checked
                                        
$this->_method_details'attr' ][ 'is_commenter' ] = $this->_method_details'attr' ][ 'is_commenter' ] && true && !$this->get_exec_dir_flag() && self::$_allow_is_commenter;
                                        break;
                                    case 
self::OS_TYPE_WIN:
                                        
// None Applicable
                                        
break;
                                    default:
                                        
// There is no default
                                
}
                        
                                
pb_backupbuddy::status'details'__('Exec test (unzip) PASSED.','it-l10n-backupbuddy' ) );
                                
$result true;
                
                                
// This will break us out of the loop
                                
$found_zip true;
                        
                            } else {
                
                                
$error_string $exec_exit_code;
                                
pb_backupbuddy::status'details'__('Exec test (unzip) FAILED: Test unzip file test failed.','it-l10n-backupbuddy' ) );
                                
pb_backupbuddy::status'details'__('Exec test (unzip) FAILED: exec Exit Code: ','it-l10n-backupbuddy' ) . $error_string );
                                
$result false;
                
                            }
                    
                        }
                    
                    } else {
                
                        
// The test file looked corrupted so warn and bail out
                        
pb_backupbuddy::status'details'sprintf__('Exec test (unzip) FAILED: Test file appears to be corrupted: %1$s','it-l10n-backupbuddy' ), md5_file$test_file ) ) );

                    }
                
                } else {
                
                    
// The test file doesn't seem to exist or be readable so warn and bail out
                    
pb_backupbuddy::status'details'__('Exec test (unzip) FAILED: Test file appears to either not exist or not be readable.','it-l10n-backupbuddy' ) );
                
                }
            
                
// If we didn't find unzip anywhere (or maybe found it but it failed) then log it
                
if ( false === $found_zip ) {
                    
                    
// We speculatively set this true when we found zip but we need both zip and unzip so set if false
                    
$this->_method_details'attr' ][ 'is_commenter' ] = false;

                    
pb_backupbuddy::status'details'__('Exec test (unzip) FAILED: Unable to find unzip executable on any specified path.','it-l10n-backupbuddy' ) );
                    
$result false;
                    
                } else {
                
                    
// See if we can determine unzip version and possibly available options. This can help us
                    // determine how to execute operations such as unzipping a file
                    
                    
pb_backupbuddy::status'details''Checking unzip version...' );

                    
$this->set_unzip_version();
                
                    
$version $this->get_unzip_version();
                    if ( 
true === is_array$version ) ) {
            
                        
pb_backupbuddy::status'details'sprintf__'Found unzip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );
                
                    } else {
            
                        
$version = array( "major" => "X""minor" => "Y" );
                        
pb_backupbuddy::status'details'sprintf__'Found unzip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );

                    }

                }
                
            } else {
            
                
pb_backupbuddy::status'details'__('Exec test (zip/unzip) FAILED: One or more required function do not exist.','it-l10n-backupbuddy' ) );
                
$result false;
          
              }
              
              
// If we found both zip and unzip then compare the paths and if the same then set the common path
              
if ( $pending_result && $result ) {
              
                  if ( 
$this->_method_details'param' ][ 'zip' ][ 'path' ] === $this->_method_details'param' ][ 'unzip' ][ 'path' ] ) {
                  
                      
$this->_method_details'param' ][ 'path' ] = $this->_method_details'param' ][ 'zip' ][ 'path' ];
                      
                  }
                  
              }
              
              
// Our result will be true if we found either or both of zip and unzip
              // The method attributes will tell which is available
              
$result = ( $pending_result || $result );
              
              return 
$result;
              
        }
        
        
/**
         *    create()
         *    
         *    A function that creates an archive file
         *    Always cleans up after itself
         *    
         *    The $excludes will be a list or relative path excludes if the $listmaker object is NULL otehrwise
         *    will be absolute path excludes and relative path excludes can be had from the $listmaker object
         *    
         *    @param        string    $zip            Full path & filename of ZIP Archive file to create
         *    @param        string    $dir            Full path of directory to add to ZIP Archive file
         *    @parame        array    $excludes        List of either absolute path exclusions or relative exclusions
         *    @param        string    $tempdir        Full path of directory for temporary usage
         *    @param        object    $listmaker        The object from which we can get an inclusions list
         *    @return        bool                    True if the creation was successful, false otherwise
         *
         */
        
public function create$zip$dir$excludes$tempdir$listmaker NULL ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->create_generic$zip$dir$excludes$tempdir$listmaker );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->create_generic$zip$dir$excludes$tempdir$listmaker );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
            
        }
            
        
/**
         *    create_generic()
         *    
         *    A function that creates an archive file
         *    
         *    The $excludes will be a list or relative path excludes if the $listmaker object is NULL otehrwise
         *    will be absolute path excludes and relative path excludes can be had from the $listmaker object
         *    
         *    @param        string    $zip            Full path & filename of ZIP Archive file to create
         *    @param        string    $dir            Full path of directory to add to ZIP Archive file
         *    @parame        array    $excludes        List of either absolute path exclusions or relative exclusions
         *    @param        string    $tempdir        [Optional] Full path of directory for temporary usage
         *    @return        bool                    True if the creation was successful, false otherwise
         *
         */
        
protected function create_generic$zip$dir$excludes$tempdir ) {
        
            
$exitcode 255;
            
$output = array();
            
$zippath '';
            
$command '';
            
$temp_zip '';
            
$excluding_additional false;
            
$exclude_count 0;
            
$exclusions = array();
            
$have_zip_errors false;
            
$zip_errors_count 0;
            
$zip_errors = array();
            
$have_zip_warnings false;
            
$zip_warnings_count 0;
            
$zip_warnings = array();
            
$have_zip_additions false;
            
$zip_additions_count 0;
            
$zip_additions = array();
            
$have_zip_debug false;
            
$zip_debug_count 0;
            
$zip_debug = array();
            
$have_zip_other false;
            
$zip_other_count 0;
            
$zip_other = array();
            
$zip_skipped_count 0;
            
$zip_using_log_file false;
            
$logfile_name '';
            
$zip_ignoring_symlinks false;

            
$zh NULL;
            
$lister NULL;
            
$visitor NULL;
            
$total_size 0;
            
$the_list = array();
        
            
// The basedir must have a trailing normalized directory separator
            
$basedir = ( rtrimtrim$dir ), self::DIRECTORY_SEPARATORS ) ) . self::NORM_DIRECTORY_SEPARATOR;
            
            
// Normalize platform specific directory separators in path
            
$basedir str_replaceDIRECTORY_SEPARATORself::NORM_DIRECTORY_SEPARATOR$basedir );

            
// Ensure no stale file information
            
clearstatcache();
            
            
// Create the helper function here so we can use it outside of the post-add
            // function. Using all defaults so includes multi-burst and server tickling
            // for now but with options we can modify this.                
            
$zh = new pb_backupbuddy_exec_helper();
                
            
// Note: could enforce trailing directory separator for robustness
            
if ( empty( $tempdir ) || !file_exists$tempdir ) ) {
            
                
// This breaks the rule of single point of exit (at end) but it's early enough to not be a problem
                
pb_backupbuddy::status'details'__('Temporary working directory must be available.','it-l10n-backupbuddy' ) );                
                return 
false;
                
            }
            
            
pb_backupbuddy::status'message'__('Using Exec Mode.','it-l10n-backupbuddy' ) );
            
            
// Tell which zip version is being used
            
$version $this->get_zip_version();
            
            if ( 
true === is_array$version ) ) {
            
                ( ( 
== $version'major' ] ) && ( == $version'minor' ] ) ) ? $version'minor' ] = 'X' true ;
                
pb_backupbuddy::status'details'sprintf__'Using zip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );
                
            } else {
            
                
$version = array( "major" => "X""minor" => "Y" );
                
pb_backupbuddy::status'details'sprintf__'Using zip version: %1$s.%2$s''it-l10n-backupbuddy' ), $version'major' ], $version'minor' ] ) );

            }
                    
            
// Get the command path for the zip command - should return a trimmed string
            
$zippath $this->get_command_pathself::COMMAND_ZIP_PATH );
            
            
// Determine if we are using an absolute path
            
if ( !empty( $zippath ) ) {
            
                
pb_backupbuddy::status'details'__'Using absolute zip path: ','it-l10n-backupbuddy' ) . $zippath );
                
            }

            
// Add the trailing slash if required
            
$command $this->slashify$zippath ) . 'zip';
            
            
// Let's inform what we are excluding/including
            
if ( count$excludes ) > ) {
            
                
pb_backupbuddy::status'details'__('Calculating directories/files to exclude from backup (relative to site root).','it-l10n-backupbuddy' ) );
                
                foreach ( 
$excludes as $exclude ) {
                
                    if ( !
strstr$exclude'backupbuddy_backups' ) ) {

                        
// Set variable to show we are excluding additional directories besides backup dir.
                        
$excluding_additional true;
                            
                    }
                        
                    
pb_backupbuddy::status'details'__('Excluding','it-l10n-backupbuddy' ) . ': ' $exclude );
                    
                    
$exclude_count++;
                        
                }
                
            }
            
            if ( 
true === $excluding_additional ) {
            
                
pb_backupbuddy::status'message'__'Excluding archives directory and additional directories defined in settings.','it-l10n-backupbuddy' ) . ' ' $exclude_count ' ' __'total','it-l10n-backupbuddy' ) . '.' );
                
            } else {
            
                
pb_backupbuddy::status'message'__'Only excluding archives directory based on settings.','it-l10n-backupbuddy' ) . ' ' $exclude_count ' ' __'total','it-l10n-backupbuddy' ) . '.' );
                
            }

            
pb_backupbuddy::status'message'__'Zip process reported: Determining list of file + directories to be added to the zip archive','it-l10n-backupbuddy' ) );

            
// Now let's create the list of files and empty (vacant) directories to include in the backup.
            // Note: we can only include vacant directories (those that had no content in the first place).
            // An empty directory may have had content that was excluded but if we give this directory to
            // pclzip it automatically recurses down into it (we have no control over that) which would then
            // mess up the exclusions. Make sure the visitor only retains a subset of the fields that we need
            // here so as to keep memory usage down.

            
$visitor = new pluginbuddy_zbdir_visitor_details( array( 'filename''directory''vacant''relative_path''size' ) );
            
            
$options = array( 'exclusions' => $excludes,
                              
'pattern_exclusions' => array(),
                              
'inclusions' => array(),
                              
'pattern_inclusions' => array(),
                              
'keep_tree' => false,
                              
'ignore_symlinks' => $this->get_ignore_symlinks(),
                              
'visitor' => $visitor );
            
            try {
            
                
$lister = new pluginbuddy_zbdir$basedir$options );
                
                
// As we are not keeping the tree we haev already done the visitor pass
                // as the tree was built so our visitor contains all the information we
                // need so we can destroy the lister object
                
unset( $lister );
                
$result true;
                
                
pb_backupbuddy::status'message'__'Zip process reported: Determined list of file + directories to be added to the zip archive','it-l10n-backupbuddy' ) );

            } catch (
Exception $e) {
            
                
// We couldn't build the list as required so need to bail
                
$error_string $e->getMessage();
                
pb_backupbuddy::status'details'sprintf__('Zip process reported: Unable to determine list of files + directories for backup - error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) );

                
// TODO: Should do some cleanup of any temporary directory, visitor, etc. but not for now
                
$result false;
                
            }
                        
            
// In case that took a while use the helper to try and keep the process alive
            // Calling burst_end() here as a kludge for now
            
$zh->burst_end();

            if ( 
true === $result ) {    
                    
                
// Now we have our flat file/directory list from the visitor - remember we didn't
                // keep the tree as we shouldn't need it for anything else as we can get all we need
                // from the visitor. We'll get a list of the subset of things we need from the visitor
                // so we can get rid of the visitor later. We'll use this list later to create our
                // partial inclusion list files to feed to zip for each burst.
                
$the_list $visitor->get_as_array( array( 'filename''directory''vacant''relative_path''size' ) );

                
// Need to remove empty values now so that we don't get misleading values
                // Here "empty value" means there is no actual path that zip would be able to
                // add and so this would have had to have been ignored later and if we counted
                // it as "vaid" now then numebrs would be awry. In this case it is probably
                // _only_ the entry that would be for the / directory which actually has a
                // empty relative path and filename.
                
foreach( $the_list as $key => $value ) {
                    if ( empty( 
$value'relative_path' ] ) && empty( $value'filename' ] ) ) {
                        unset( 
$the_list$key ] );
                    }
                }
                
                
pb_backupbuddy::status'details'sprintf__('Zip process reported: %1$s (directories + files) will be requested to be added to backup zip archive','it-l10n-backupbuddy' ), count$the_list ) ) );
                
//$zh->set_options( array( 'directory_count' => ( $visitor->count( 'directory' => true ), 'file_count' => $visitor->count( array( 'directory' => false ) ) ) );
                
                // Find the sum total size of all non-directory (i.e., file) items
                
$total_size 0;
                foreach ( 
$the_list as $the_item ) {
                    if ( 
false === $the_item'directory' ] ) {
                        
$total_size += (int)$the_item'size' ];
                    }
                }
                
                
pb_backupbuddy::status'details'sprintf__('Zip process reported: %1$s bytes will be requested to be added to backup zip archive','it-l10n-backupbuddy' ), $total_size ) );
                
//$zh->set_options( array( 'content_size' => $total_size ) );

                // Retain this for reference for now
//                 file_put_contents( ( dirname( $tempdir ) . DIRECTORY_SEPARATOR . self::ZIP_CONTENT_FILE_NAME ), print_r( $the_list, true ) );
            
                // Presently we don't need the visitor any longer so we can free up some
                // memory by deleting. We have all we need in $the_list and we will use this
                // to create our burst content lists
                
unset( $visitor );
                                
            }
            
            
// Only continue if we have a valid list
            // This isn't ideal at present but will suffice
            
if ( true === $result ) {            
            
                
// Check if the version of zip in use supports log file (which will help with memory usage for large sites)
                
if ( true === $this->get_zip_supports_log_file() ) {
            
                    
// Choose to use log file so quieten stdout - we'll set up the log file later
                    
$command .= ' -q';
                    
$zip_using_log_file true;
            
                }
            
                
// Check if we need to turn off compression by settings (faster but larger backup)
                
if ( true !== $this->get_compression() ) {
            
                    
$command .= ' -0';
                    
pb_backupbuddy::status'details'__('Zip archive creation compression disabled based on settings.','it-l10n-backupbuddy' ) );
                
                } else {
            
                    
pb_backupbuddy::status'details'__('Zip archive creation compression enabled based on settings.','it-l10n-backupbuddy' ) );
            
                }
            
                
// Check if ignoring (not following) symlinks
                
if ( true === $this->get_ignore_symlinks() ) {
            
                    
// Not all OS support this for command line zip but best to handle it late and just
                    // indicate here it is requested but not supported by OS
                    
switch ( $this->get_os_type() ) {
                        case 
self::OS_TYPE_NIX:
                            
// Want to not follow symlinks so set command option and set flag for later use
                            
$command .= ' -y';
                            
$zip_ignoring_symlinks true;
                            
pb_backupbuddy::status'details'__('Zip archive creation symbolic links will not be followed based on settings.','it-l10n-backupbuddy' ) );
                            break;
                        case 
self::OS_TYPE_WIN:
                            
pb_backupbuddy::status'details'__('Zip archive creation symbolic links requested to not be followed based on settings but this option is not supported on this operating system.','it-l10n-backupbuddy' ) );
                            break;
                        default:
                            
pb_backupbuddy::status'details'__('Zip archive creation symbolic links requested to not be followed based on settings but this option is not supported on this operating system.','it-l10n-backupbuddy' ) );
                    }
                
                } else {
            
                    
pb_backupbuddy::status'details'__('Zip archive creation symbolic links will be followed based on settings.','it-l10n-backupbuddy' ) );

                }
            
                
// Check if we are ignoring warnings - meaning can still get a backup even
                // if, e.g., some files cannot be read
                
if ( true === $this->get_ignore_warnings() ) {
            
                    
// Note: warnings are being ignored but will still be gathered and logged
                    
pb_backupbuddy::status'details'__('Zip archive creation actionable warnings will be ignored based on settings.','it-l10n-backupbuddy' ) );
                
                } else {
            
                    
pb_backupbuddy::status'details'__('Zip archive creation actionable warnings will not be ignored based on settings.','it-l10n-backupbuddy' ) );

                }
                
                
// We want to "grow" a file with each successive "burst" after the first. If the zip
                // file doesn't exist when -g is given it will be created - but the problem is that
                // zip also throws a warning and if we are not ignoring warnings we get caught on this.
                // We could filter out this warning but that would be fiddly - so instead let's we'll
                // need to be able to switch the option off/on somehow. We could have two copies of
                // teh command string, one with and one without, but that is a bit messy. Or we could
                // have the command in two parts that we splice together (also messy). We could append
                // it when we need it but that might not be compatible with the specific form of the
                // command in all cases. We could put it in and then on the first call use a filtered
                // command string without it. We could have a separate command "object" that we use
                // to build the command each time we want it and we can turn the option on/off.
                // All of these are possible but which is simplest?
                
$command .= ' -g';
            
                
// Now we'll set up the logging to file if required - use full logging
                // If using log file we want to append to any existing on each burst.
                // In the case where not using a log file we get the output in any array
                // and we'll simply accumulate the arrays for each burst. When complete
                // we process the whole log file or the aggrgate array - this is simpler
                // than trying to process results as we go.
                
if ( true === $zip_using_log_file ) {
            
                    
$logfile_name $tempdir self::ZIP_LOG_FILE_NAME;
                    
$command .= " -lf '{$logfile_name}' -li -la";
            
                }
                        
                
// Set temporary directory to store ZIP while it's being generated.            
                
$command .= " -b '{$tempdir}'";

                
// Specify where to place the finalized zip archive file
                // If warnings are being ignored we can tell zip to create the zip archive in the final
                // location - otherwise we must put it in a temporary location and move it later only
                // if there are no warnings. This copes with the case where (this) controlling script
                // gets timed out by the server and if the file were created in the final location with
                // warnings that should not be ignored we cannot prevent it being created. The -MM option
                // could be used but this prevents us catching such warnings and being able to report
                // them to the user in the case where the script hasn't been terminated. Additionally the
                // -MM option would bail out on the first encountered problem and so if there were a few
                // problems they would each not be found until the current one is fixed and try again.
                // TODO: This will have to change when we start to use burst modes properly because we
                // have to keep the zip file in the temporary directory after each burst has grown it
                // and we can only move it to teh final location when complete. This is much like pclzip
                // works anyway and this mode for exec was never actually a design feature but just a
                // convenienec in some cases that should not be needed now anyway.
//                 if ( true === $this->get_ignore_warnings() ) {
//             
//                     $temp_zip = $zip;
//             
//                 } else {
//             
//                     $temp_zip = $tempdir . basename( $zip );
//                 
//                 }        
                
                // Temporary zip file is _always_ located in the temp dir now
                
$temp_zip $tempdir basename$zip );

                
$command .= " '{$temp_zip}' .";
            
                
// Now create the inclusions file in the tempdir
                
$ifile $tempdir self::ZIP_INCLUSIONS_FILE_NAME;
                
                
// Now the tricky bit - we have to determine how we are going to give the lisy of files
                // to zip to use. Preferred way would be as a parameter that tells it to include the
                // files listed in the file. Unfortunately there is no such option for zip - a list of
                // files to include in a zip can only be given as discrete file names on the command line
                // or read from stdin. Giving a long list of names on the command line is not
                // feasible so we have to use a stdin based method which is either to cat the file and
                // pipe it in to zip or we can use an stdin file descriptor redirection to fetch the
                // contents of the file. We can only use these methods safely on *nix systems and when
                // exec_dir is not in use.
                // When we cannot use the stdin approach we have to resort to using the -i@file
                // parameter along with the -r recursion option so that zip will match the "patterns"
                // we give it in the file as it recurses the directory tree. This is not an ideal solution
                // because the recursion can be slow on some servers where there is a big directory tree
                // and much of it is irrelevant and does not belong to the site - but we have no other choice.
                // We shouldn't have to use this method very much and it should be ok in many cases
                // where there isn't much that is superfluous in the directory tree.
                // So let's make up the final command to execute based on the operational environment
                // and then we can simply "reuse" the command on each burst, with the addition of the
                // -g option on bursts after the first.
                
if ( ( true === $this->get_exec_dir_flag() ) || ( self::OS_TYPE_WIN === $this->get_os_type() ) ) {
                
                    
// We are running on Windows or using exec_dir so have to use -r and -i@file
                    
$command .= " -r -i@" "'{$ifile}'";
                
                } else {
                
                    
// We aer running under a nice *nix environment so we can use a stdin redirection
                    // approach. Let's just use redirection for now as that avoids having to use cat and
                    // piping.
                
//                     $command .= " -@";
//                     $command = "cat '{$ifile}' | " . $command;
                    
                    
$command .= " -@";
                    
$command .= " <'{$ifile}'";
                    
                }
            
                
// If we can't use a log file but exec_dir isn't in use we can redirect stderr to stdout
                // If exec_dir is in use we cannot redirect because of command line escaping so cannot log errors/warnings
                
if ( false === $zip_using_log_file ) {
            
                    if ( 
false === $this->get_exec_dir_flag() ) {
            
                        
$command .= ' 2>&1';
                
                    } else {
                
                        
pb_backupbuddy::status'details'sprintf__'Zip Errors/Warnings cannot not be logged with this version of zip and exec_dir active''it-l10n-backupbuddy' ), true ) );
                
                    }
                
                } else {
                
                    
// Using log file but need to redirect stderr to null because zip
                    // still seems to send some stuff to stderr as well as to log file.
                    // Note: if exec_dir is in use then we cannot redirect so theer may
                    // be some stuff gets sent to stderr and logged but it's not worth
                    // telling that - if we really need that then we can change the below
                    // into an if/then/else and log the condition.
                    
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                
                }
                
                
// Remember our "master" command
                
$master_command $command;
                
                
// Remember the "master" inclusions list filename
                
$master_ifile $ifile;
                
                
// Use this to memorise the worst exit code we had (where we didn't immediately
                // bail out because it signalled a bad failure)
                
$max_exitcode 0;
                
                
// Do this as close to when we actually want to start monitoring usage
                // Maybe this is redundant as we have already called this in the constructor.
                // If we want to do this then we have to call with true to reset monitoring to
                // start now.
                
$zh->initialize_monitoring_usage();
                
                
// Now we have our command prototype we can start bursting
                // Simply build a burst list based on content size. Currently no
                // look-ahead so the size will always exceed the current size threshold
                // by some amount. May consider using a look-ahead to see if the next
                // item would exceed the threshold in which case don't add it (unless it
                // would be the only content in which case have to add it but also log
                // a warning).
                
while ( !empty( $the_list ) ) {
            
                    
// Populate the content file for zip
                    
$ilist = array();
                    
                    
// Tell helper that we are preparing a new burst
                    
$zh->burst_begin();
                    
                    
pb_backupbuddy::status'details'sprintf__'Zip process reported: Starting burst number: %1$s''it-l10n-backupbuddy' ), $zh->get_burst_count() ) );
                    
pb_backupbuddy::status'details'sprintf__'Zip process reported: Current burst size threshold: %1$s bytes''it-l10n-backupbuddy' ), $zh->get_burst_current_size_threshold() ) );

                    
// Helper keeps track of what is being added to the burst content and will
                    // tell us when the content is sufficient for this burst based on it's
                    // criteria - this can adapt to how each successive burst goes.
                    // The array shifting isn't really very efficient but is functional for now.
                    
$item array_shift$the_list );
                    while ( ( 
NULL !== $item ) && ( false === $zh->burst_content_complete() ) ) {
                    
                        
$file $item'relative_path' ] . $item'filename' ];
                        
                        
// We shouldn't have any empty items here as we should have removed them
                        // earlier, but just in case...
                        
if ( !empty( $file ) ) {
                            
$ilist[] = $file;
                            
                            
// Call the helper event handler as we add each file to the list
                            
$zh->burst_content_added$item );
                            
                        }
                        
                        
// Not reached size threshold yet so get next item
                        
$item array_shift$the_list );
                        
                    }
                    
                    
// Since we would have taken a new element off the array specilatively
                    // we need to put it back if we had already reached burst content completion
                    
NULL !== $item ) ? array_unshift$the_list$item ) : false ;
                
                    
// Retain this for reference for now
                    //file_put_contents( ( dirname( $tempdir ) . DIRECTORY_SEPARATOR . self::ZIP_CONTENT_FILE_NAME ), print_r( $ilist, true ) );

                    // Make sure we expunge any previous version of the inclusions file
                    
if ( file_exists$ifile ) ) {            
                        @
unlink$ifile );            
                    }
                    
                    
// Slight kludge for now to make sure each burst content file is uniquely named
                    
$ifile str_replace".txt""_"$zh->get_burst_count() . ".txt"$master_ifile );
                    
                    
$file_ok = @file_put_contents$ifileimplodePHP_EOL$ilist ) . PHP_EOL );
                    if ( ( 
false === $file_ok ) || ( === $file_ok ) ) {
                    
                        
// The file write failed for some reason, e.g., no disk space? We need to
                        // bail and set exit code so that problem is apparent
                        
pb_backupbuddy::status'details'sprintf__('Zip process reported: Unable to write burst content file: `%1$s`','it-l10n-backupbuddy' ), $ifile ) );
                        
$exitcode 255;
                        break;                    

                    }
                    
                    unset( 
$ilist );
                

                    
// Remember the current directory and change to the directory being added so that "." is valid in command
                    
$working_dir getcwd();
                
                    
chdir$dir );
                
                    
// For first invocation we must not set the grow option so remove it from the command
                    // Bit of a hack for now.
                    
if ( === $zh->get_burst_count() ) {
                        
$command str_replace"-g"""$master_command );
                    } else {
                        
$command $master_command;
                    }
                    
                    
// Make sure we put the correct burst content file name in the command
                    // Slight kludge for now until we build the command line dynamically each burst
                    
$command str_replace$master_ifile$ifile$command );
            
                    
$command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$command ) : $command;
            
                    
pb_backupbuddy::status'details'sprintf__'Zip process reported: Burst requests %1$s (directories + files) items with %2$s bytes of content to be added to backup zip archive''it-l10n-backupbuddy' ), $zh->get_burst_content_count(), $zh->get_burst_content_size() ) );
                    
pb_backupbuddy::status'details'sprintf__'Zip process reported: Using burst content file: `%1$s`''it-l10n-backupbuddy' ), $ifile ) );

                    
pb_backupbuddy::status'details'__'Zip process reported: ') . $this->get_method_tag() . __(' command','it-l10n-backupbuddy' ) . ': ' $command );

                    
// Allow helper to check how the burst goes
                    
$zh->burst_start();

                    
// Successive invocations will append to $output array so we don't have to do anything special
                    // If we are using a log file then we have set that to append as well - so in either case when
                    // we finally exit we will have the sum total of the log output from all invocations.
                    
@exec$command$output$exitcode );
                    
                    
// And now we can analyse what happened and plan for next burst if any
                    
$zh->burst_stop();
                    
                    
// Wrap up the individual burst handling
                    // Note: because we called exec we basically went into a wait condition and so (on Linux)
                    // we didn't consume any max_execution_time so we never really have to bother about
                    // resetting it. However, it is true that time will have elapsed so if this burst _does_
                    // take longer than our current burst threshold period then max_execution_time would be
                    // reset - but what this doesn't cover is a _cumulative_ effect of bursts and so we might
                    // consider reworking the mechanism to monitor this separately from the individual burst
                    // period (the confusion relates to this having originally applied to the time based
                    // burst handling fro pclzip rather than teh size based for exec). It could also be more
                    // relevant for Windows that doesn't stop the clock when exec is called.
                    
$zh->burst_end();
                    
                    
// Keep a running total of the backup file size (this is temporary code)
                    
$temp_zip_stats pluginbuddy_stat::stat$temp_zip );            
                    
// Only log anything if we got some valid file stats
                    
if ( false !== $temp_zip_stats ) {            
                        
pb_backupbuddy::status'details'sprintf__'Zip process reported: Accumulated zip archive file size: %1$s bytes''it-l10n-backupbuddy' ), $temp_zip_stats'dsize' ] ) );            
                    }
                    
                    
pb_backupbuddy::status'details'sprintf__'Zip process reported: Ending burst number: %1$s''it-l10n-backupbuddy' ), $zh->get_burst_count() ) );
                        
                    
// Set current working directory back to where we were
                    
chdir$working_dir );
                    
                    
// We have to check the exit code to decide whether to keep going ot bail out (break).
                    // If we get a 0 exit code ot 18 exit code then keep going and remember we got the 18
                    // so that we can emit that as the final exit code if applicable. If we get any other
                    // exit code then we must break out immediately.                    
                    
if ( ( !== $exitcode ) && ( 18 !== $exitcode ) ) {
                        
// Zip failure of some sort - must bail out with current exit code
                        
break;
                    } else {
                        
// Make sure exit code is always the worst we've had so that when
                        // we've done our last burst we drop out with the correct exit code set
                        // This is really to make sure we drop out with exit code 18 if we had
                        // this in _any_ burst as we would keep going and subsequent burst(s) may
                        // return 0. If we had any other non-zero exit code it would be a "fatal"
                        // error and we would have dropped out immediately anyway.
                        
$exitcode = ( $max_exitcode $exitcode ) ? $max_exitcode : ( $max_exitcode $exitcode ) ;
                    }
                
                }
            
                
// Convenience for handling different scanarios
                
$result false;
            
                
// We can report how many dirs/files added                
                
pb_backupbuddy::status'details'sprintf__('Zip process reported: Accumulated burst requested %1$s (directories + files) items requested to be added to backup zip archive (final)','it-l10n-backupbuddy' ), ( $zh->get_added_dir_count() + $zh->get_added_file_count() ) ) );

                
// If we used a log file then process the log file - else process output
                // Always scan the output/logfile for warnings, etc. and show warnings even if user has chosen to ignore them
                
if ( true === $zip_using_log_file ) {
            
                    try {
                
                        
$logfile = new SplFileObject$logfile_name"rb" );
                    
                        while( !
$logfile->eof() ) {
                    
                            
$line $logfile->current();
                            
$id $logfile->key(); // Use the line number as unique key for later sorting
                            
$logfile->next();
                        
                            if ( 
preg_match'/^\s*(zip warning:)/i'$line ) ) {
                        
                                
// Looking for specific types of warning - in particular want the warning that
                                // indicates a file couldn't be read as we want to treat that as a "skipped"
                                // warning that indicates that zip flagged this as a potential problem but
                                // created the zip file anyway - but it would have generated the non-zero exit
                                // code of 18 and we key off that later. All other warnings are not considered
                                // reasons to return a non-zero exit code whilst still creating a zip file so
                                // we'll follow the lead on that and not have other warning types halt the backup.
                                // So we'll try and look for a warning output that looks like it is file related...
                                
if ( preg_match'/^\s*(zip warning:)\s*([^:]*:)\s*(.*)/i'$line$matches ) ) {
                            
                                    
// Matched to what looks like a file related warning so check particular cases
                                    
switch ( strtolower$matches] ) ) {
                                        case 
"could not open for reading:":                                        
                                            
$zip_warningsself::ZIP_WARNING_SKIPPED ][ $id ] = trim$line );
                                            
$zip_warnings_count++;
                                            break;
                                        case 
"name not matched:":                                        
                                            
$zip_otherself::ZIP_OTHER_GENERIC ][ $id ] = trim$line );
                                            
$zip_other_count++;
                                            break;
                                        default:
                                            
$zip_warningsself::ZIP_WARNING_GENERIC ][ $id ] = trim$line );
                                            
$zip_warnings_count++;
                                    }
                            
                                } else {
                            
                                    
// Didn't match to what would look like a file related warning so count it regardless
                                    
$zip_warningsself::ZIP_WARNING_GENERIC ][ $id ] = trim$line );
                                    
$zip_warnings_count++;
                                
                                }
                            
                            } elseif ( 
preg_match'/^\s*(zip error:)/i'$line ) ) {
                        
                                
$zip_errors$id ] = trim$line );
                                
$zip_errors_count++;
                        
                            } elseif ( 
preg_match'/^\s*(adding:)/i'$line ) ) {
                        
                                
// Currently not processing additions entried
                                //$zip_additions[] = trim( $line );
                                //$zip_additions_count++;
                        
                            
} elseif ( preg_match'/^\s*(sd:)/i'$line ) ) {
                        
                                
$zip_debug$id ] = trim$line );
                                
$zip_debug_count++;
                                
                            } elseif ( 
preg_match'/^.*(skipped:)\s*(?P<skipped>\d+)/i'$line$matches ) ) {
                            
                                if ( isset( 
$matches'skipped' ] ) ) {
                                    
$zip_skipped_count $matches'skipped' ];
                                }
                                
                            } else {
                        
                                
// Currently not processing other entries
                                //$zip_other[] = trim( $line );
                                //$zip_other_count++;
                        
                            
}
                        
                        }
                    
                        unset( 
$logfile );
                    
                        @
unlink$logfile_name );
                    
                    } catch ( 
Exception $e ) {
                
                        
// Something fishy - we should have been able to open the log file...
                        
$error_string $e->getMessage();
                        
pb_backupbuddy::status'details'sprintf__('Log file could not be opened - error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) );
                    
                    }

                } else {
            
                    
// TODO: $output could be large so if we parse it all into separate arrays then may want to shift
                    // out each line and then discard it after copied to another array
                    
$id 0// Create a unique key (like a line number) for later sorting
                    
foreach ( $output as $line ) {
                
                        if ( 
preg_match'/^\s*(zip warning:)/i'$line ) ) {
                    
                            
// Looking for specific types of warning - in particular want the warning that
                            // indicates a file couldn't be read as we want to treat that as a "skipped"
                            // warning that indicates that zip flagged this as a potential problem but
                            // created the zip file anyway - but it would have generated the non-zero exit
                            // code of 18 and we key off that later. All other warnings are not considered
                            // reasons to return a non-zero exit code whilst still creating a zip file so
                            // we'll follow the lead on that and not have other warning types halt the backup.
                            // So we'll try and look for a warning output that looks like it is file related...
                            
if ( preg_match'/^\s*(zip warning:)\s*([^:]*:)\s*(.*)/i'$line$matches ) ) {
                        
                                
// Matched to what looks like a file related warning so check particular cases
                                
switch ( strtolower$matches] ) ) {
                                    case 
"could not open for reading:":                                        
                                        
$zip_warningsself::ZIP_WARNING_SKIPPED ][ $id++ ] = trim$line );
                                        
$zip_warnings_count++;
                                        break;
                                    case 
"name not matched:":                                        
                                        
$zip_otherself::ZIP_OTHER_GENERIC ][ $id++ ] = trim$line );
                                        
$zip_other_count++;
                                        break;
                                    default:
                                        
$zip_warningsself::ZIP_WARNING_GENERIC ][ $id++ ] = trim$line );
                                        
$zip_warnings_count++;
                                }
                        
                            } else {
                        
                                
// Didn't match to what would look like a file related warning so count it regardless
                                
$zip_warningsself::ZIP_WARNING_GENERIC ][ $id++ ] = trim$line );
                                
$zip_warnings_count++;
                            
                            }
                        
                        } elseif ( 
preg_match'/^\s*(zip error:)/i'$line ) ) {
                    
                            
$zip_errors$id++ ] = trim$line );
                            
$zip_errors_count++;
                    
                        } elseif ( 
preg_match'/^\s*(adding:)/i'$line ) ) {
                    
                            
// Currently not processing additions entried
                            //$zip_additions[] = trim( $line );
                            //$zip_additions_count++;
                            
$id++;
                    
                        } elseif ( 
preg_match'/^\s*(sd:)/i'$line ) ) {
                    
                            
$zip_debug$id++ ] = trim$line );
                            
$zip_debug_count++;
                    
                        } elseif ( 
preg_match'/^.*(skipped:)\s*(?P<skipped>\d+)/i'$line$matches ) ) {
                        
                            if ( isset( 
$matches'skipped' ] ) ) {
                                
$zip_skipped_count $matches'skipped' ];
                            }
                                
                        } else {
                    
                            
// Currently not processing other entries
                            //$zip_other[] = trim( $line );
                            //$zip_other_count++;
                            
$id++;
                    
                        }
                    
                    }
    
                    
// Now free up the memory...
                    
unset( $output );
                
                }
            
                
// Set convenience flags            
                
$have_zip_warnings = ( $zip_warnings_count );
                
$have_zip_errors = ( $zip_errors_count );
                
$have_zip_additions = ( $zip_additions_count );
                
$have_zip_debug = ( $zip_debug_count );
                
$have_zip_other = ( $zip_other_count );
            
                
// Always report the exit code regardless of whether we might ignore it or not
                
pb_backupbuddy::status'details'__('Zip process exit code: ','it-l10n-backupbuddy' ) . $exitcode );
            
                
// Always report the number of warnings - even just to confirm that we didn't have any
                
pb_backupbuddy::status'details'sprintf__('Zip process reported: %1$s warning%2$s','it-l10n-backupbuddy' ), $zip_warnings_count, ( ( == $zip_warnings_count ) ? '' 's' ) ) );

                
// Always report warnings regardless of whether user has selected to ignore them
                
if ( true === $have_zip_warnings ) {
            
                    
$this->log_zip_reports$zip_warningsself::$_warning_desc"WARNING"self::MAX_WARNING_LINES_TO_SHOWdirnamedirname$tempdir ) ) . DIRECTORY_SEPARATOR 'pb_backupbuddy' DIRECTORY_SEPARATOR self::ZIP_WARNINGS_FILE_NAME );

                }
            
                
// Always report other reports regardless
                
if ( true === $have_zip_other ) {
            
                    
// Only report number of informationals if we have any as they are not that important
                    
pb_backupbuddy::status'details'sprintf__('Zip process reported: %1$s information%2$s','it-l10n-backupbuddy' ), $zip_other_count, ( ( == $zip_other_count ) ? 'al' 'als' ) ) );

                    
$this->log_zip_reports$zip_otherself::$_other_desc"INFORMATION"self::MAX_OTHER_LINES_TO_SHOWdirnamedirname$tempdir ) ) . DIRECTORY_SEPARATOR 'pb_backupbuddy' DIRECTORY_SEPARATOR self::ZIP_OTHERS_FILE_NAME );

                }
            
                
// See if we can figure out what happened - note that $exitcode could be non-zero for actionable warning(s) or error
                // if ( (no zip file) or (fatal exit code) or (not ignoring warnable exit code) )
                // TODO: Handle condition testing with function calls based on mapping exit codes to exit type (fatal vs non-fatal)
                
if ( ( ! @file_exists$temp_zip ) ) ||
                     ( ( 
!= $exitcode ) && ( 18 != $exitcode ) ) ||
                     ( ( 
18 == $exitcode ) && !$this->get_ignore_warnings() ) ) {
            
                    
// If we have any zip errors reported show them regardless
                    
if ( true === $have_zip_errors ) {
                
                        
pb_backupbuddy::status'details'sprintf__('Zip process reported: %1$s error%2$s','it-l10n-backupbuddy' ), $zip_errors_count, ( ( == $zip_errors_count ) ? '' 's' )  ) );
                    
                        foreach ( 
$zip_errors as $line ) {
                
                            
pb_backupbuddy::status'details'__'Zip process reported: ','it-l10n-backupbuddy' ) . $line );
                
                        }
                    
                    }

                    
// Report whether or not the zip file was created (whether that be in the final or temporary location)            
                    
if ( ! @file_exists$temp_zip ) ) {
                
                        
pb_backupbuddy::status'details'__'Zip Archive file not created - check process exit code.','it-l10n-backupbuddy' ) );
                    
                    } else {
                    
                        
pb_backupbuddy::status'details'__'Zip Archive file created but with errors/actionable-warnings so will be deleted - check process exit code and warnings.','it-l10n-backupbuddy' ) );

                    }
                
                    
// The operation has failed one way or another. Note that as the user didn't choose to ignore errors the zip file
                    // is always created in a temporary location and then only moved to final location on success without error or warnings.
                    // Therefore if there is a zip file (produced but with warnings) it will not be visible and will be deleted when the
                    // temporary directory is deleted below.
                
                    
$result false;
                
                } else {
            
                    
// NOTE: Probably the two paths below can be reduced to one because even if we are
                    // ignoring warnings we are still building the zip in temporary location and finally
                    // moving it because we are growing it.
                    // Got file with no error or warnings _or_ with warnings that the user has chosen to ignore
                    
if ( false === $this->get_ignore_warnings() ) {
                
                        
// Because not ignoring warnings the zip archive was built in temporary location so we need to move it
                        
pb_backupbuddy::status'details'__('Moving Zip Archive file to local archive directory.','it-l10n-backupbuddy' ) );
                
                        
// Make sure no stale file information
                        
clearstatcache();
                    
                        @
rename$temp_zip$zip );
                    
                        if ( @
file_exists$zip ) ) {
                    
                            
pb_backupbuddy::status'details'__('Zip Archive file moved to local archive directory.','it-l10n-backupbuddy' ) );
                            
pb_backupbuddy::status'message'__'Zip Archive file successfully created with no errors or actionable warnings.','it-l10n-backupbuddy' ) );
                        
                            
$this->log_archive_file_stats$zip, array( 'content_size' => $total_size ) );
                            
                            
// Temporary for now - try and incorporate into stats logging (makes the stats logging function part of the zip helper class?)
                            
pb_backupbuddy::status'details'sprintf__('Zip Archive file size: %1$s (directories + files) actually added','it-l10n-backupbuddy' ), ( $zh->get_added_dir_count() + $zh->get_added_file_count() - $zip_skipped_count ) ) );
                    
                            
$result true;
                        
                        } else {
                    
                            
pb_backupbuddy::status'details'__('Zip Archive file could not be moved to local archive directory.','it-l10n-backupbuddy' ) );
                            
$result false;
                        
                        }
                        
                    } else {
                
                        
// With multi-burst we haev to always build the zip in temp location  so always have to move it
                        
pb_backupbuddy::status'details'__('Moving Zip Archive file to local archive directory.','it-l10n-backupbuddy' ) );
                
                        
// Make sure no stale file information
                        
clearstatcache();
                    
                        @
rename$temp_zip$zip );
                        
                        if ( @
file_exists$zip ) ) {
                    
                            
pb_backupbuddy::status'details'__('Zip Archive file moved to local archive directory.','it-l10n-backupbuddy' ) );
                            
pb_backupbuddy::status'message'__'Zip Archive file successfully created with no errors (any actionable warnings ignored by user settings).','it-l10n-backupbuddy' ) );
                        
                            
$this->log_archive_file_stats$zip, array( 'content_size' => $total_size ) );
                            
                            
// Temporary for now - try and incorporate into stats logging (makes the stats logging function part of the zip helper class?)
                            
pb_backupbuddy::status'details'sprintf__('Zip Archive file size: %1$s (directories + files) actually added','it-l10n-backupbuddy' ), ( $zh->get_added_dir_count() + $zh->get_added_file_count() - $zip_skipped_count ) ) );
                            
                            
$result true;
                        
                        } else {
                    
                            
pb_backupbuddy::status'details'__('Zip Archive file could not be moved to local archive directory.','it-l10n-backupbuddy' ) );
                            
$result false;
                        
                        }
                
                    }
                
                }
                
            }        

            
// Cleanup the temporary directory that will have all detritus and maybe incomplete zip file            
            
pb_backupbuddy::status'details'__('Removing temporary directory.','it-l10n-backupbuddy' ) );
            
            if ( !( 
$this->delete_directory_recursive$tempdir ) ) ) {
            
                    
pb_backupbuddy::status'details'__('Temporary directory could not be deleted: ','it-l10n-backupbuddy' ) . $tempdir );
            
            }
            
            return 
$result;
                                                
        }
        
        
/**
         *    extract()
         *
         *    Extracts the contents of a zip file to the specified directory using the best unzip methods possible.
         *    If no specific items given to extract then it's a complete unzip
         *
         *    @param    string        $zip_file                    Full path & filename of ZIP file to extract from.
         *    @param    string        $destination_directory        Full directory path to extract into.
         *    @param    array        $items                        Mapping of what to extract and to what
         *    @return    bool                                    true on success (all extractions successful), false otherwise
         */
        
public function extract$zip_file$destination_directory ''$items = array() ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    if ( empty( 
$items ) ) {
                        
$result $this->extract_generic_full$zip_file$destination_directory );
                    } else {
                        
$result $this->extract_generic_selected$zip_file$destination_directory$items );                    
                    }
                    break;
                case 
self::OS_TYPE_WIN:
                    if ( empty( 
$items ) ) {
                        
$result $this->extract_generic_full$zip_file$destination_directory );
                    } else {
                        
$result $this->extract_generic_selected$zip_file$destination_directory$items );                    
                    }
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
            
        }

        
/**
         *    extract_generic_full()
         *
         *    Extracts the contents of a zip file to the specified directory using the best unzip methods possible.
         *
         *    @param    string        $zip_file                    Full path & filename of ZIP file to extract from.
         *    @param    string        $destination_directory        Full directory path to extract into.
         *    @return    bool                                    true on success, false otherwise
         */
        
protected function extract_generic_full$zip_file$destination_directory '' ) {
        
            
$summary '';
            
$output = array();
            
$exit_code 127;
            
$matches = array();
            
$result false;
            
$zippath '';
            
$command '';
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the unzip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute unzip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'unzip';    
    
                
// We'll try and extract from the backup file to the given directory, very quietly with overwrite
                // If we just did -o we could try and get file count from processing $output but it would be a bit time-consuming
                
$unzip_command $command " -qqo '{$zip_file}' -d '{$destination_directory}' -x 'importbuddy.php'";
                
                
$unzip_command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                
$unzip_command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$unzip_command ) : $unzip_command;
                
                @
exec$unzip_command$output$exit_code);
                
                
// Note: we don't open the file and then do stuff but it's all done in one action
                // so we need to interpret the return code to dedide what to do
                
switch ( (int) $exit_code ) {
                    case 
0:
                        
// Handled archive and apparently no extraction problems
                        
                        // Now we have to do a second run to find out the file count (crazy)
                        
$list_command $command " -ql '{$zip_file}'";
                        
                        
$list_command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                        
$list_command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$list_command ) : $list_command;
                        
                        
//$summary = @exec( $list_command, $output, $exit_code);
                        
$summary = @exec$list_command );

                        
// Currently don't bother to check exit code, if we failed then whatever we got back in
                        // Last output line _should_ have the information we need (and that is returned by exec)
                        // $summary is unlikely to match the pattern so file count will just default to 0
                        
if ( preg_match("|[[:^digit:]]+(?P<byte_count>[[:digit:]]+)[[:^digit:]]+(?P<file_count>[[:digit:]]+)[[:space:]]+(files)|"$summary$matches ) ) {
                        
                            
// Should be able to pull this straight out provided the unzip version stuck to the rules
                            
$file_count $matches'file_count' ];
                            
                        } else {
                        
                            
// Some reason we didn't get good output or the format is odd
                            
$file_count 0;
                        }
                        
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) extracted file contents (%1$s to %2$s)','it-l10n-backupbuddy' ), $zip_file$destination_directory ) );
    
                        
$this->log_archive_file_stats$zip_file );
                        
                        
$result true;
                        break;

                    default:
                        
// For now let's just print the error code and drop through
                        
$error_string $exit_code;
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) failed to open/process file to extract contents (%1$s to %2$s) - Error Info: %3$s.','it-l10n-backupbuddy' ), $zip_file$destination_directory$error_string ) );

                        
// Return an error code and a description - this needs to be handled more generically
                        //$result = array( 1, "Unable to get archive contents" );
                        // Currently as we are returning an array as a valid result we just return false on failure
                        
$result false;
                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                //$result = array( 1, "Class not available to match method" );
                // Currently as we are returning an array as a valid result we just return false on failure
                
$result false;

            }
            
            return 
$result;
                        
        }

        
/**
         *    extract_generic_selected()
         *
         *    Extracts the contents of a zip file to the specified directory using the best unzip methods possible.
         *
         *    @param    string        $zip_file                    Full path & filename of ZIP file to extract from.
         *    @param    string        $destination_directory        Full directory path to extract into.
         *    @param    array        $items                        Mapping of what to extract and to what
         *    @return    bool                                    true on success (all extractions successful), false otherwise
         */
        
protected function extract_generic_selected$zip_file$destination_directory ''$items ) {
        
            
$summary '';
            
$output = array();
            
$exit_code 127;
            
$matches = array();
            
$result false;
            
$zippath '';
            
$command '';
            
$rename_required false;
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the unzip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute unzip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'unzip';    
    
                
// Now we need to take each item and run an unzip for it - unfortunately there is no easy way of combining
                // arbitrary extractions into a single command if some might be to a 
                
foreach ( $items as $what => $where ) {
                
                    
$rename_required false;
                    
$result false;
                
                    
// Decide how to extract based on where
                    
if ( empty( $where) ) {
                    
                        
// Extract direct to destination directory with junked path
                        
$unzip_command $command " -qqoj '{$zip_file}' '{$what}' -d '{$destination_directory}' ";
                    
                    } elseif ( !empty( 
$where ) ) {
                    
                        if ( 
$what === $where ) {
                        
                            
// Extract to same directory structure - don't junk path, no need to add where to destnation as automatic
                            
$unzip_command $command " -qqo '{$zip_file}' '{$what}' -d '{$destination_directory}' ";
                        
                        } else {
                        
                            
// Firt we'll extract and junk the path
                            
$unzip_command $command " -qqoj '{$zip_file}' '{$what}' -d '{$destination_directory}' ";
                            
                            
// Will need to rename if the extract is ok
                            
$rename_required true;
                        
                        }
                    
                    }
                
                    
$unzip_command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                    
$unzip_command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$unzip_command ) : $unzip_command;
                
                    @
exec$unzip_command$output$exit_code);
                
                    
// Note: we don't open the file and then do stuff but it's all done in one action
                    // so we need to interpret the return code to dedide what to do
                    
switch ( (int) $exit_code ) {
                        case 
0:
                            
// Handled archive and apparently no extraction problems                        
                            
pb_backupbuddy::status'details'sprintf__('exec (unzip) extracted file contents (%1$s from %2$s to %3$s%4$s)','it-l10n-backupbuddy' ), $what$zip_file$destination_directory$where ) );
                        
                            
$result true;
                            
                            
// Rename if we have to
                            
if ( true === $rename_required) {
                            
                                
// Note: we junked the path on the extraction so just the filename of $what is the source but
                                // $where could be a simple file name or a file path 
                                
$result $result && rename$destination_directory DIRECTORY_SEPARATOR basename$what ),
                                                             
$destination_directory DIRECTORY_SEPARATOR $where );
                                
                            }
                            break;

                        default:
                            
// For now let's just print the error code and drop through
                            
$error_string $exit_code;
                            
pb_backupbuddy::status'details'sprintf__('exec (unzip) failed to open/process file to extract contents (%1$s from %2$s to %3$s%4$s) - Error Info: %5$s.','it-l10n-backupbuddy' ), $what$zip_file$destination_directory$where$error_string ) );

                            
// Return an error code and a description - this needs to be handled more generically
                            //$result = array( 1, "Unable to get archive contents" );
                            // Currently as we are returning an array as a valid result we just return false on failure
                            
$result false;
                    }
                    
                    
// If the extraction failed (or rename after extraction) then break out of the foreach and simply return false
                    
if ( false === $result ) {
                    
                        break;
                        
                    }
                    
                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                //$result = array( 1, "Class not available to match method" );
                // Currently as we are returning an array as a valid result we just return false on failure
                
$result false;

            }
            
            return 
$result;
                        
        }

        
/**
         *    file_exists()
         *    
         *    Tests whether a file (with path) exists in the given zip file
         *    If leave_open is true then the zip object will be left open for faster checking for subsequent files within this zip
         *  Note: this is ignored here because it has no meaning in the use of the unzip command
         *    
         *    @param        string    $zip_file        The zip file to check
         *    @param        string    $locate_file    The file to test for
         *    @param        bool    $leave_open        Optional: True if the zip file should be left open
         *    @return        bool/array                True if the file is found in the zip and false if not, array for other problem
         *
         */
        
public function file_exists$zip_file$locate_file$leave_open false ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->file_exists_generic$zip_file$locate_file );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->file_exists_generic$zip_file$locate_file );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
                                      
        }

        
/**
         *    file_exists_generic()
         *    
         *    Tests whether a file (with path) exists in the given zip file
         *    
         *    @param        string    $zip_file        The zip file to check
         *    @param        string    $locate_file    The file to test for
         *    @return        bool/array                True if the file is found in the zip and false if not, array for other problem
         *
         */
        
public function file_exists_generic$zip_file$locate_file ) {
        
            
$result = array( 1"Generic failure indication" );
            
$zippath '';
            
$command '';
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the unzip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute unzip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'unzip';    
    
                
// Try an archive test on the file and we'll just look at the return code
                
$command .= " -qt '{$zip_file}' '{$locate_file}'";
                
                
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                
$command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$command ) : $command;

                @
exec$command$output$exit_code);
                
                
// Note: we don't open the file and then do stuff but it's all done in one action
                // so we need to interpret the return code to dedide what to indicate
                
switch ( (int) $exit_code ) {
                    case 
0:
                        
// Handled archive and file found and checked out ok so return success
                        
pb_backupbuddy::status'details'__('File found (exec)','it-l10n-backupbuddy' ) . ': ' $locate_file );
                        
$result true;
                        break;
                    case 
11:
                        
// No problem handling archive but file simply not found so return failure
                        
pb_backupbuddy::status'details'__('File not found (exec)','it-l10n-backupbuddy' ) . ': ' $locate_file );
                        
$result false;
                        break;
                    default:
                        
// For now let's just print the error code and drop through
                        
$error_string $exit_code;
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) failed to open/process file to check if file exists (looking for %1$s in %2$s) - Error Info: %3$s.','it-l10n-backupbuddy' ), $locate_file $zip_file$error_string ) );

                        
// Return an error code and a description - this needs to be handled more generically
                        
$result = array( 1"Failed to open/process file" );

                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                
$result = array( 1"Function not available to match method" );

            }
            
            return 
$result;

        }
        
        
/*    get_file_list()
         *    
         *    Get an array of all files in a zip file with some file properties.
         *    
         *    @param        string        $zip_file    The file to list the content of
         *    @return        bool|array                false on failure, otherwise array of file properties (may be empty)
         */
        
public function get_file_list$zip_file ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->get_file_list_generic$zip_file );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->get_file_list_generic$zip_file );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
            
        }
        
        
/*    get_file_list_generic()
         *    
         *    Get an array of all files in a zip file with some file properties.
         *    
         *    @param        string        $zip_file    The file to list the content of
         *    @return        bool|array                false on failure, otherwise array of file properties (may be empty)
         */
        
public function get_file_list_generic$zip_file ) {
        
            
$file_list = array();
            
$stat_keys = array( 'permissions''zip_version''zip_os''size''type_attr''compressed_size''compression_method''mdate''filename' );
            
$output = array();
            
$result false;
            
$zippath '';
            
$command '';
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the unzip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute unzip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'unzip';    

                
// We'll try and get a *nix style directory listing output and process it
                // Note: we'll ignore stderr output for now as it might interfere
                // Note: the file date given is the stored local time (not UTC which may be stored as well)
                
                // Output format should be like:
                // -rwxr-xr-x  2.3 unx     2729 tx    1099 defN 20120220.231956 file/path/name.ext
                
$command .= " -Z --h --t -lT '{$zip_file}'";
                
                
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                
$command = ( self::OS_TYPE_WIN === $this->get_os_type() ) ? str_replace'\'''"'$command ) : $command;

                @
exec$command$output$exit_code);
                
                
// Note: we don't open the file and then do stuff but it's all done in one action
                // so we need to interpret the return code to dedide what to do
                
switch ( (int) $exit_code ) {
                    case 
0:
                        
// Handled archive and apparently got a list so try and process it
                        
                        // Should be one file per line, no more no less
                        
$file_count sizeof$output );
                        
                        foreach ( 
$output as $line ) {
                        
                            
// Break up the output based on whitespace for max of 9 fields (last will be filename)
                            
$stat array_combine(  $stat_keys preg_split"/[\s,]+/"$line) );
                            
                            
// Convert screwy date format to a common notation (choose MySQL format)
                            
$translated_mdate preg_replace'/(\d{4})(\d{2})(\d{2}).(\d{2})(\d{2})(\d{2})/','$1-$2-$3 $4:$5:$6' $stat'mdate' ] );

                            
// Must convert to a timestamp (using current timezone)
                            
$stat'mtime' ] = strtotime$translated_mdate );
                            
                            
$file_list[] = array(
                                
$stat'filename' ],
                                
$stat'size' ],
                                
$stat'compressed_size' ],
                                
$stat'mtime' ]
                            );
                            
                        }
                        
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) listed file contents (%1$s)','it-l10n-backupbuddy' ), $zip_file ) );
    
                        
$this->log_archive_file_stats$zip_file );
                        
                        
$result = &$file_list;
                        break;

                    default:
                        
// For now let's just print the error code and drop through
                        
$error_string $exit_code;
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) failed to open/process file to list contents (%1$s) - Error Info: %2$s.','it-l10n-backupbuddy' ), $zip_file$error_string ) );

                        
// Return an error code and a description - this needs to be handled more generically
                        //$result = array( 1, "Unable to get archive contents" );
                        // Currently as we are returning an array as a valid result we just return false on failure
                        
$result false;
                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                //$result = array( 1, "Class not available to match method" );
                // Currently as we are returning an array as a valid result we just return false on failure
                
$result false;

            }

            return 
$result;
                                  
        }
        
        
/*    set_comment()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string            $zip_file        Filename of archive to set comment on.
         *    @param        string            $comment        Comment to apply to archive.
         *    @return        bool                            true on success, otherwise false.
         */
        
public function set_comment$zip_file$comment ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->set_comment_linux$zip_file$comment );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->set_comment_windows$zip_file$comment );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
            
        }

        
/*    set_comment_windows()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string            $zip_file        Filename of archive to set comment on.
         *    @param        string            $comment        Comment to apply to archive.
         *    @return        bool                            true on success, otherwise false.
         */
        
public function set_comment_windows$zip_file$comment ) {
        
            
// This should never be called but just in case return false silently
            
return false;
            
        }

        
/*    set_comment_linux()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string            $zip_file        Filename of archive to set comment on.
         *    @param        string            $comment        Comment to apply to archive.
         *    @return        bool                            true on success, otherwise false.
         */
        
public function set_comment_linux$zip_file$comment ) {
        
            
$output = array();
            
$result false;
            
$zippath '';
            
$command '';
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the zip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_ZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute zip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'zip';    

                
// We have to feed the comment in - trying by pipe here
                // We need to prepend the comment input
                
$command .= " -z '{$zip_file}'";
                
                
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                
// Note that we escape the comment arg for the shell...
                
$command  'echo ' escapeshellarg$comment ) . ' | ' $command;
                
                @
exec$command$output$exit_code);
                
                
// Note: we don't open the file and then do stuff but it's all done in one action
                // so we need to interpret the return code to dedide what to do
                
switch ( (int) $exit_code ) {
                    case 
0:
                        
// Handled archive and apparently set the comment - no further action required
                                                                        
                        
pb_backupbuddy::status'details'sprintf__('exec (zip) set comment in file %1$s','it-l10n-backupbuddy' ), $zip_file ) );
                            
                        
$result true;
                        break;

                    default:
                        
// For now let's just print the error code and drop through
                        
$error_string $exit_code;
                        
pb_backupbuddy::status'details'sprintf__('exec (zip) failed to open/process file to set comment in file %1$s - Error Info: %2$s.','it-l10n-backupbuddy' ), $zip_file$error_string ) );

                        
// Return an error code and a description - this needs to be handled more generically
                        //$result = array( 1, "Unable to get archive contents" );
                        // Currently as we are returning a string as a valid result we just return false on failure
                        
$result false;
                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                //$result = array( 1, "Class not available to match method" );
                // Currently as we are returning a string as a valid result we just return false on failure
                
$result false;

            }
            
            return 
$result;
                        
        }

        
/*    get_comment()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string        $zip_file        Filename of archive to retrieve comment from.
         *    @return        bool|string                    false on failure, Zip comment otherwise.
         */
        
public function get_comment$zip_file ) {
        
            
$result false;
        
            switch ( 
$this->get_os_type() ) {
                case 
self::OS_TYPE_NIX:
                    
$result $this->get_comment_linux$zip_file );
                    break;
                case 
self::OS_TYPE_WIN:
                    
$result $this->get_comment_windows$zip_file );
                    break;
                default:
                    
$result false;
            }
            
            return 
$result;
            
        }
        
        
/*    get_comment_windows()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string        $zip_file        Filename of archive to retrieve comment from.
         *    @return        bool|string                    false on failure, Zip comment otherwise.
         */
        
public function get_comment_windows$zip_file ) {
        
            
// This should never be called but just in case return false silently
            
return false;
            
        }
    
        
/*    get_comment_linux()
         *    
         *    Retrieve archive comment.
         *    
         *    @param        string        $zip_file        Filename of archive to retrieve comment from.
         *    @return        bool|string                    false on failure, Zip comment otherwise.
         */
        
public function get_comment_linux$zip_file ) {

            
$output = array();
            
$result false;
            
$comment "";
            
$zippath '';
            
$command '';
            
            if ( 
function_exists'exec' ) ) {
            
                
// Get the command path for the unzip command - should return a trimmed string
                
$zippath $this->get_command_pathself::COMMAND_UNZIP_PATH );
                
                
// Determine if we are using an absolute path
                
if ( !empty ( $zippath ) ) {
                
                    
pb_backupbuddy::status'details'__'Using absolute unzip path: ','it-l10n-backupbuddy' ) . $zippath );
                    
                }
                
                
// Add the trailing slash if required
                
$command $this->slashify$zippath ) . 'unzip';    

                
// We expect two lines of output - the first shpuld be the archive name and the second comment if present
                
$command .= " -z '{$zip_file}'";
                
                
$command .= ( ( $this->get_exec_dir_flag() ) ? "" " 2>" $this->get_null_device() );
                    
                @
exec$command$output$exit_code);
                
                
// Note: we don't open the file and then do stuff but it's all done in one action
                // so we need to interpret the return code to dedide what to do
                
switch ( (int) $exit_code ) {
                    case 
0:
                        
// Handled archive and apparently got a comment so try and process it
                        
                        // Should be one file per line, no more no less
                        
$line_count sizeof$output );
                        
                        
// Must have at least 2 lines for there to be a non-empty comment
                        
if ( $line_count ) {
                        
                            
// Simple criteria for now - just take the final line
                            // Note that if there is no comment this is still valid as an empty comment
                            // so we don't treat this as an error
                            //$comment = $output[ $line_count - 1];
                            
unset( $output[0] );
                            
$comment implode''$output );
                        
                        }
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) retrieved comment in file %1$s','it-l10n-backupbuddy' ), $zip_file ) );
                            
                        
$result $comment;
                        break;

                    default:
                        
// For now let's just print the error code and drop through
                        
$error_string $exit_code;
                        
pb_backupbuddy::status'details'sprintf__('exec (unzip) failed to open/process get comment in file %1$s - Error Info: %2$s.','it-l10n-backupbuddy' ), $zip_file$error_string ) );

                        
// Return an error code and a description - this needs to be handled more generically
                        //$result = array( 1, "Unable to get archive contents" );
                        // Currently as we are returning a string as a valid result we just return false on failure
                        
$result false;
                }
                
            } else {
            
                
// Something fishy - the methods indicated exec but we couldn't find the function
                
pb_backupbuddy::status'details'__('exec indicated as available method but exec function non-existent','it-l10n-backupbuddy' ) );

                
// Return an error code and a description - this needs to be handled more generically
                //$result = array( 1, "Class not available to match method" );
                // Currently as we are returning a string as a valid result we just return false on failure
                
$result false;

            }
            
            return 
$result;
            
        }
        
    } 
// end pluginbuddy_zbzipexec class.    
    
}