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
|
<?php /** * pluginbuddy_zbzippclzip Class * * Extends the zip capability core class with pclzip 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_zbzippclzip" ) ) {
/** * pluginbuddy_PclZip Class * * Wrapper for PclZip to encapsulate the process of loading the PclZip library (if not * already loaded, which it shouldn't be generally) and also surrounding method calls * with the unpleasant workaround for the mbstring issue where things may fail because * PclZip is using string functions to process binary data and if the string functions * are overloaded with the multi-byte versions the processing can (probably will) fail. * * @param string $zip_filename The name of the zip file that will be managed * @return null * */ class pluginbuddy_PclZip {
/** * The created PclZip object if it can be created * * @var $_za object */ private $_za = NULL; /** * __construct() * * Default constructor. * This is used to try and load the PclZip library and then create an instance of * an archive with that. If the library cannot be made available then an exception * is thrown and that is handled by the caller. * TODO: Consider having a "suppress warnings" parameter to determine whether methods * should be invoked with warnings suppressed or not. For is_available() usage we would * want to so as not to potentially flood the PHP error log. For other functions that * are not called frequently we might not want to suppress the warnings. * * @param string $zip_filename The name of the zip file that will be managed * @return null * */ public function __construct( $zip_filename ) { // The PclZip class has to be available for us so let's have a go // Note: it is not required because nothing will break without it but the method will // simply not be available // This may seem laborious but it's robust against include_once not playing nice if the // class is already included and trying to include it again if ( !@class_exists( 'PclZip', false ) ) { $possibles = array( ABSPATH . 'wp-admin/includes/class-pclzip.php', pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php' ); foreach ( $possibles as $possible) { if ( @is_readable( $possible ) ) { // Found one that should be loadable so try it and then break out pb_backupbuddy::status( 'details', 'PCLZip class not found. Attempting to load from `' . $possible . '`.' ); @include_once( $possible ); break; } }
} // By now PclZip _should_ be available so let's see... if ( @class_exists( 'PclZip', false ) ) { // It's available so create the private instance $this->_za = new PclZip( $zip_filename ); } else { // Not available so throw the exception for the caller to handle throw new Exception( 'PclZip class does not exist.' ); } return; } /** * __destruct() * * Default destructor. * * @return null * */ public function __destruct() { if ( NULL != $this->_za ) { unset ( $this->_za ); } return; } /** * __call() * * Magic method intercepting calls to unknown methods. This allows us to intercept * all method calls and add additional processing * * @param string $method The name of the intercepted method * @param array $arguments Array of the arguments associated with the method call * @return mixed $result Whatever the invoked wrapper method call returns * */ public function __call( $method, $arguments ) { $result = false; // See #15789 - PclZip uses string functions on binary data // If it's overloaded with Multibyte safe functions the results are incorrect. if ( @ini_get( 'mbstring.func_overload' ) && @function_exists( 'mb_internal_encoding' ) ) { $previous_encoding = @mb_internal_encoding(); @mb_internal_encoding( 'ISO-8859-1' ); } $result = @call_user_func_array( array( $this->_za, $method ), $arguments ); // Now undo any change we may have made to the encoding if ( isset( $previous_encoding ) ) { @mb_internal_encoding( $previous_encoding ); unset( $previous_encoding );
} return $result; } } /** * pb_backupbuddy_pclzip_helper Class * * Extends the parent pb_backupbuddy_zip_helper class for the pclzip method. * We need a single instance of this class with a static method to get the * instance that can be called in the pclzip callbacks and then from within * the callbacks the non-static class methods can be called on the instance. * So conventional usage would be to do a new to get an instance of the * class and then the callback can call the static function to get that instance * and the object can also be called as usual. Equally the static function could * be called and have it actually create the instance and if we need it later * outside of pclzip we can call the static function to get the instance. * */ class pb_backupbuddy_pclzip_helper extends pb_backupbuddy_zip_helper { /** * 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(); } /** * __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; } /** * * event_handler() * * Callback function from pclzip to call appropriate event handler function. * * @param int $event The callback event identifier * @param reference &$header The element header array * @return bool True|False based on handler function result * */ public function event_handler( $event, &$header ) { $result = true; switch ( $event ) { case PCLZIP_CB_POST_ADD: $result = $this->element_added( $header ); break; default: pb_backupbuddy::status( 'details', sprintf( __("Unknown PclZip Callback Event: %1$s",'it-l10n-backupbuddy' ), $event ) ); } return $result; } /** * * element_added() * * Callback function handler for after an element has been added. * Only process the element if it has been added (header status is 'ok') * Invoke periodic functions for usage minitoring, etc. * * @param reference &$header The element header array * @return bool True always * */ private function element_added( &$header ) { $result = true; // Only if the dir/file was added ok if ( 'ok' === $header[ 'status' ] ) { // Increment the appropriate count and decide if we need to log progress ( true === $header[ 'folder' ] ) ? $this->incr_added_dir_count() : $this->incr_added_file_count() ; // Keep up with what's happening $this->monitor_activity(); } // Just return based on whether what we tried to do worked or not return $result; } /** * * monitor_activity() * * Keep track of and log progress. * Keep track of and log usage data - in particular the user space time used * which relates to what is counted against execution time. * Optionally handle multi-burst processing by an execution time reset. * Optionally handle server tickling by dummy flush to server. * * @return none * */ public function monitor_activity() { // Used to make sure we do not report items multiple times // Bit of a kludge for now $this->_reported = false; $this->monitor_progress(); $this->monitor_usage(); $this->handle_burst_mode(); $this->tickle_server(); } }
class pluginbuddy_zbzippclzip extends pluginbuddy_zbzipcore { // Constants for file handling const ZIP_ERRORS_FILE_NAME = 'last_pclzip_errors.txt'; const ZIP_WARNINGS_FILE_NAME = 'last_pclzip_warnings.txt'; const ZIP_OTHERS_FILE_NAME = 'last_pclzip_others.txt'; const ZIP_CONTENT_FILE_NAME = 'last_pclzip_list.txt'; /** * 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 = 'pclzip'; /** * This tells us whether this method is regarded as a "compatibility" method * * @var bool */ public static $_is_compatibility_method = true; /** * This tells us the dependencies of this method so they can be check to see if the method can be supported * Note: PclZip constructor checks for gzopen function and dies on failure so we may as well pre-empt that * * @var array */ public static $_method_dependencies = array( 'classes' => array(), 'functions' => array( 'gzopen' ), 'extensions' => array( ), 'files' => array(), 'check_func' => 'check_method_dependencies_static' ); /** * * 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 = false; // Need to verify that at least PclZip should be available to be loaded (but we // don't actually want to load it here) $possibles = array( ABSPATH . 'wp-admin/includes/class-pclzip.php', pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php' ); foreach ( $possibles as $possible) { if ( @is_readable( $possible ) ) { // Found one that should be loadable so break out $result = true; break; } } return $result; }
/** * __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 ); // Override some of parent defaults $this->_method_details[ 'attr' ] = array_merge( $this->_method_details[ 'attr' ], array( 'name' => 'PclZip Method', 'compatibility' => pluginbuddy_zbzippclzip::$_is_compatibility_method ) );
// No relevant parameters for this method $this->_method_details[ 'param' ] = array(); } /** * __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_zbzippclzip::$_method_tag; } /** * get_is_compatibility_method() * * Returns the (static) is_compatibility_method boolean * * @return bool * */ public function get_is_compatibility_method() { return pluginbuddy_zbzippclzip::$_is_compatibility_method; } /** * 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 all wrapped up in the same class then if we * can zip then we'll assume (for now) that we can unzip as well so attributes are set 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; $za = NULL; $test_file = $tempdir . 'temp_test_' . uniqid() . '.zip'; // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $test_file ); $result = true; } catch ( Exception $e ) { $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('PclZip test FAILED: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false;
} // Only continue if we have a valid archive object if ( true === $result ) { if ( $za->create( __FILE__ , PCLZIP_OPT_REMOVE_PATH, dirname( __FILE__) ) !== 0 ) { if ( @file_exists( $test_file ) ) { if ( !@unlink( $test_file ) ) { pb_backupbuddy::status( 'details', sprintf( __('Error #564634. Unable to delete test file (%s)!','it-l10n-backupbuddy' ), $test_file ) ); } // The zip operation was successful - implies can zip and unzip and hence archive, check and list $this->_method_details[ 'attr' ][ 'is_zipper' ] = true; $this->_method_details[ 'attr' ][ 'is_unzipper' ] = true; $this->_method_details[ 'attr' ][ 'is_archiver' ] = true; $this->_method_details[ 'attr' ][ 'is_checker' ] = true; $this->_method_details[ 'attr' ][ 'is_lister' ] = true; $this->_method_details[ 'attr' ][ 'is_commenter' ] = true; $this->_method_details[ 'attr' ][ 'is_unarchiver' ] = true; $this->_method_details[ 'attr' ][ 'is_extractor' ] = true; pb_backupbuddy::status( 'details', __('PclZip test PASSED.','it-l10n-backupbuddy' ) ); $result = true; } else { pb_backupbuddy::status( 'details', __('PclZip test FAILED: Zip file not found.','it-l10n-backupbuddy' ) ); $result = false; } } else { $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', __('PclZip test FAILED: Unable to create/open zip file.','it-l10n-backupbuddy' ) ); pb_backupbuddy::status( 'details', __('PclZip Error: ','it-l10n-backupbuddy' ) . $error_string ); $result = false; } } if ( NULL != $za ) { unset( $za ); } return $result; } /** * create() * * A function that creates an archive file * * The $excludes will be a list or relative path excludes * * @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 * @return bool True if the creation was successful, false otherwise * */ public function create( $zip, $dir, $excludes, $tempdir, $listmaker = NULL ) { $za = NULL; $result = false; $exitcode = 255; $zip_output = array(); $temp_zip = ''; $excluding_additional = false; $exclude_count = 0; $exclusions = array(); $temp_file_compression_threshold = 5; $pre_add_func = ''; $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_ignoring_symlinks = false; $symlinks_found = array(); $zh = NULL;
$lister = NULL; $visitor = NULL; $total_size = 0; $the_list = array(); $saved_ignored_symdirs = array(); // The basedir must have a trailing normalized directory separator $basedir = ( rtrim( trim( $dir ), self::DIRECTORY_SEPARATORS ) ) . self::NORM_DIRECTORY_SEPARATOR; // Normalize platform specific directory separators in path $basedir = str_replace( DIRECTORY_SEPARATOR, self::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_pclzip_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 Compatibility Mode.','it-l10n-backupbuddy' ) ); pb_backupbuddy::status( 'message', __('If your backup times out in Compatibility Mode try disabling zip compression in Settings.','it-l10n-backupbuddy' ) ); // Check if pclzip temporary directory is already defined - if it is and // PclZip has already been loaded then this may caue a problem with where // temporary files are created if ( defined( 'PCLZIP_TEMPORARY_DIR' ) ) { pb_backupbuddy::status( 'details', __('PCLZIP_TEMPORARY_DIR already defined - may cause problems if PclZip library already loaded by another plugin','it-l10n-backupbuddy' ) . ': ' . PCLZIP_TEMPORARY_DIR ); } // Define in any case so that it is used if possible define( 'PCLZIP_TEMPORARY_DIR', $tempdir ); // Let's inform what we are excluding/including if ( count( $excludes ) > 0 ) { 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. $visitor = new pluginbuddy_zbdir_visitor_details( array( 'filename', 'directory', 'vacant', 'absolute_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 monitor_activity() here $zh->monitor_activity();
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. First create our list. We have to do this first because we need to // know if we are bypassing ignored symdirs (not including them in the list) so we can // add the number of these to the total number of items from our simple (vacant) directory // and file count total so that the final stats of what was actually added and the details // of what we didn't add will all add up - sounds convoluted, well that's because it is... $backup_list = $visitor->get_as_array( array( 'filename', 'directory', 'vacant', 'absolute_path', 'size' ) ); foreach ( $backup_list as $backup_item ) { if ( false === $backup_item[ 'directory' ] ) { // Not a directory so must be a file (whether symlink or not) so always ass $the_list[] = $backup_item[ 'absolute_path' ] . $backup_item[ 'filename' ]; } elseif ( ( true === $backup_item[ 'directory' ] ) && ( isset( $backup_item[ 'vacant' ] ) && ( true === $backup_item[ 'vacant' ] ) ) ) { // It's a directory and has the vacant attribute and it is vacant so we can // safely add it. // We cannot add non-vacant directories because pclzip will recurse into them. // If the directory does not have the vacant attribute that is because it is // a symlink dir that wasn't followed so we neither know whether it is vacant // not empty and so we cannot risk adding it in case it is not empty $the_list[] = $backup_item[ 'absolute_path' ] . $backup_item[ 'filename' ]; } elseif ( ( true === $backup_item[ 'directory' ] ) && !( isset( $backup_item[ 'vacant' ] ) ) ) { // It's s directory but vacant attribute isn't set then must be an ignored // symlink directory so we'll remember it so we can add it as an informational // at the end of the process $saved_ignored_symdirs[] = $backup_item[ 'absolute_path' ] . $backup_item[ 'filename' ]; } }
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) + count( $saved_ignored_symdirs ) ) ) ); //$zh->set_options( array( 'directory_count' => ( $visitor->count( 'directory' => true, 'vacant' => true ) + count( $saved_ignored_symdirs ), 'file_count' => $visitor->count( array( 'directory' => false ) ) ) ); $total_size = 0; foreach ( $backup_list as $backup_item ) { if ( false === $backup_item[ 'directory' ] ) { $total_size += (int)$backup_item[ 'size' ]; } } // We don't need the backup list array any more unset( $backup_list ); 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 unset( $visitor ); // Get started with out zip object // Put our final zip file in the temporary directory - it will be moved later $temp_zip = $tempdir . basename( $zip ); // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $temp_zip ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } } // Only continue if we have a valid list and archive object // This isn't ideal at present but will suffice if ( true === $result ) { // Basic argument list $arguments = array(); array_push( $arguments, $the_list ); array_push( $arguments, PCLZIP_OPT_REMOVE_PATH, $dir );
if ( true !== $this->get_compression() ) { // Note: don't need to force use of temporary files for compression pb_backupbuddy::status( 'details', __('Zip archive creation compression disabled based on settings.','it-l10n-backupbuddy' ) ); array_push( $arguments, PCLZIP_OPT_NO_COMPRESSION ); } else { // Note: force the use of temporary files for compression when file size exceeds given value. // This over-rides the "auto-sense" which is based on memory_limit and this _may_ indicate a // memory availability that is higher than reality leading to memory allocation failure if // trying to compress large files. Set the threshold low enough (specify in MB) so that except in // The tightest memory situations we should be ok. Could have option to force use of temporary // files regardless. pb_backupbuddy::status( 'details', __('Zip archive creation compression enabled based on settings.','it-l10n-backupbuddy' ) ); array_push( $arguments, PCLZIP_OPT_TEMP_FILE_THRESHOLD, $temp_file_compression_threshold ); } // Check if ignoring (not following) symlinks if ( true === $this->get_ignore_symlinks() ) { // Want to not follow symlinks so set flag for later use $zip_ignoring_symlinks = true; pb_backupbuddy::status( 'details', __('Zip archive creation symbolic links will be ignored based on settings.','it-l10n-backupbuddy' ) );
} else { pb_backupbuddy::status( 'details', __('Zip archive creation symbolic links will not be ignored 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' ) );
} // Use anonymous function to weed out the unreadable and non-existent files (common reason for failure) // and possibly symlinks based on user settings. // PclZip will record these files as 'skipped' in the file status and we can post-process to determine // if we had any of these and hence either stop the backup or continue dependent on whether the user // has chosen to ignore warnings or not and/or ignore symlinks or not. // Unfortunately we cannot directly tag the file with the reason why it has been skipped so when we // have to process the skipped items we have to try and work out why it was skipped - but shouldn't // be too hard. // TODO: Consider moving this into the PclZip wrapper and have a method to set the various pre/post // functions or select predefined functions (such as this). if ( true ) { // Note: This could be simplified - it's written to be extensible but may not need to be $args = '$event, &$header'; $code = ''; $code .= 'static $symlinks = array(); '; $code .= '$result = true; '; // Handle symlinks - keep the two cases of ignoring/not-ignoring separate for now to make logic more // apparent - but could be merged with different conditional handling // For a valid symlink: is_link() -> true; is_file()/is_dir() -> true; file_exists() -> true // For a broken symlink: is_link() -> true; is_file()/is_dir() -> false; file_exists() -> false // Note: pclzip first tests every file using file_exists() before ever trying to add the file so // for a broken symlink it will _always_ error out immediately it discovers a broken symlink so // we never have a chance to filter these out at this stage. if ( true === $zip_ignoring_symlinks ) { // If it's a symlink or it's neither a file nor a directory then ignore it. A broken symlink // will never get this far because pclzip will have choked on it $code .= 'if ( ( true === $result ) && !( @is_link( $header[\'filename\'] ) ) ) { '; $code .= ' if ( @is_file( $header[\'filename\'] ) || @is_dir( $header[\'filename\'] ) ) { '; $code .= ' $result = true; '; $code .= ' foreach ( $symlinks as $prefix ) { '; $code .= ' if ( !( false === strpos( $header[\'filename\'], $prefix ) ) ) { '; $code .= ' $result = false; '; $code .= ' break; '; $code .= ' } '; $code .= ' } '; $code .= ' } else { '; // $code .= ' error_log( "Neither a file nor a directory (ignoring): \'" . $header[\'filename\'] . "\'" ); '; $code .= ' $result = false; '; $code .= ' } '; $code .= '} else { '; // $code .= ' error_log( "File is a symlink (ignoring): \'" . $header[\'filename\'] . "\'" ); '; $code .= ' $symlinks[] = $header[\'filename\']; '; // $code .= ' error_log( "Symlinks Array: \'" . print_r( $symlinks, true ) . "\'" ); '; $code .= ' $result = false; '; $code .= '} '; } else { // If it's neither a file nor directory then ignore it - a valid symlink will register as a file // or directory dependent on what it is pointing at. A broken symlink will never get this far. $code .= 'if ( ( true === $result ) && ( @is_file( $header[\'filename\'] ) || @is_dir( $header[\'filename\'] ) ) ) { '; $code .= ' $result = true; '; $code .= '} else { '; // $code .= ' error_log( "Neither a file nor a directory (ignoring): \'" . $header[\'filename\'] . "\'" ); '; $code .= ' $result = false; '; $code .= '} '; } // Add the code block for ignoring unreadable files if ( true ) { $code .= 'if ( ( true === $result ) && ( @is_readable( $header[\'filename\'] ) ) ) { '; $code .= ' $result = true; '; $code .= '} else { '; // $code .= ' error_log( "File not readable: \'" . $header[\'filename\'] . "\'" ); '; $code .= ' $result = false; '; $code .= '} '; } // Return true (to include file) if file passes conditions otherwise false (to skip file) if not $code .= 'return ( ( true === $result ) ? 1 : 0 ); ';
$pre_add_func = create_function( $args, $code ); } // If we had cause to create a pre add function then add it to the argument list here if ( !empty( $pre_add_func ) ) { array_push( $arguments, PCLZIP_CB_PRE_ADD, $pre_add_func ); } // Add a post-add function for progress monitoring, usage data monitoring, // burst handling and server tickling - using the zip helper object // we created earlier $post_add_func = ''; if (true) { $args = '$event, &$header'; $code = ''; $code .= '$result = true; '; $code .= '$zh = pb_backupbuddy_pclzip_helper::get_instance();'; $code .= '$result = $zh->event_handler( $event, $header );'; $code .= 'return $result;'; $post_add_func = create_function( $args, $code ); }
// If we had cause to create a pre add function then add it to the argument list here if ( !empty( $post_add_func ) ) { array_push( $arguments, PCLZIP_CB_POST_ADD, $post_add_func ); }
if ( @file_exists( $zip ) ) { pb_backupbuddy::status( 'details', __('Existing ZIP Archive file will be replaced.','it-l10n-backupbuddy' ) ); @unlink( $zip ); } // Now actually create the zip archive file // First implode any embedded array in the argument list and truncate the result if too long // Assume no arrays embedded in arrays - currently no reason for that // TODO: Make the summary length configurable so that can see more if required // TODO: Consider mapping pclzip argument identifiers to string representations for clarity $args = '$item'; $code = 'if ( is_array( $item ) ) { $string_item = implode( ",", $item); return ( ( strlen( $string_item ) <= 50 ) ? $string_item : "List: " . substr( $string_item, 0, 50 ) . "..." ); } else { return $item; }; '; $imploder_func = create_function( $args, $code ); $imploded_arguments = array_map( $imploder_func, $arguments ); pb_backupbuddy::status( 'details', $this->get_method_tag() . __( ' command arguments','it-l10n-backupbuddy' ) . ': ' . implode( ';', $imploded_arguments ) ); // Do this as close to when we actually want to start monitoring usage $zh->initialize_monitoring_usage(); $output = call_user_func_array( array( &$za, 'create' ), $arguments ); // Work out whether we have a problem or not if ( is_array( $output ) ) { // It's an array so at least we produced a zip archive $exitcode = 0;
// We can report how many dirs/files added according to pclzip pb_backupbuddy::status( 'details', sprintf( __('Zip process reported: %1$s (directories + files) added to backup zip archive (final)','it-l10n-backupbuddy' ), ( $zh->get_added_dir_count() + $zh->get_added_file_count() ) ) );
// Process the array for any "warnings" or other reportable conditions $id = 0; // Create a unique key (like a line number) for later sorting foreach( $output as $file ) { switch ( $file[ 'status' ] ) { case "skipped": // First need to filter out any files skipped because under a symlink dir foreach ( $symlinks_found as $prefix ) { if ( !( false === strpos( $file[ 'filename' ], $prefix ) ) ) { $id++; // break out of the foreach and the switch break 2; } } // For skipped files need to determine why it was skipped if ( ( true === $zip_ignoring_symlinks ) && @is_link( $file[ 'filename' ] ) ) { // Remember this for filtering other files skipped because in symlink directory $symlinks_found[] = $file[ 'filename' ]; // Skipped because we are ignoring symlinks and this is a symlink $zip_other[ self::ZIP_OTHER_IGNORED_SYMLINK ][ $id++ ] = $file[ 'filename' ]; $zip_other_count++; } else { //Skipped because probably unreadable or non-existent (catch-all for now) $zip_warnings[ self::ZIP_WARNING_SKIPPED ][ $id++ ] = $file[ 'filename' ]; $zip_warnings_count++; } break; case "filtered": $zip_warnings[ self::ZIP_OTHER_FILTERED ][ $id++ ] = $file[ 'filename' ]; $zip_warnings_count++; break; case "filename_too_long": $zip_warnings[ self::ZIP_OTHER_LONGPATH ][ $id++ ] = $file[ 'filename' ]; $zip_warnings_count++; break; default: // Currently not processing "ok" entries $id++; } } // Now also add in INFORMATIONALs for any ignored symdirs because these would not have // been included in the build list. They were not included because pclzip would have attempted // to follow them and then we would have had to "filter" them and all entries that pclzip // would have created under them which is just a wster of time - best to not include at all // at tell the user now that we didnt include them foreach ( $saved_ignored_symdirs as $ignored_symdir ) { $zip_other[ self::ZIP_OTHER_IGNORED_SYMLINK ][ $id++ ] = $ignored_symdir; $zip_other_count++; } // Now free up the memory... unset( $output ); // Set convenience flags $have_zip_warnings = ( 0 < $zip_warnings_count ); $have_zip_other = ( 0 < $zip_other_count ); } else { // Not an array so a bad error code, something we didn't or couldn't catch $exitcode = $za->errorCode(); // Put the error information into an array for consistency $zip_errors[] = $za->errorInfo( true ); $zip_errors_count = sizeof( $zip_errors ); $have_zip_errors = ( 0 < $zip_errors_count ); } // Convenience for handling different scanarios $result = false; // 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, ( ( 1 == $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_warnings, self::$_warning_desc, "WARNING", self::MAX_WARNING_LINES_TO_SHOW, dirname( dirname( $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, ( ( 1 == $zip_other_count ) ? 'al' : 'als' ) ) );
$this->log_zip_reports( $zip_other, self::$_other_desc, "INFORMATION", self::MAX_OTHER_LINES_TO_SHOW, dirname( dirname( $tempdir ) ) . DIRECTORY_SEPARATOR . 'pb_backupbuddy' . DIRECTORY_SEPARATOR . self::ZIP_OTHERS_FILE_NAME );
} // See if we can figure out what happened // Note: only expect exitcode to be non-zero for an error we couldn't pre-empt // Note: warnings will cause the operation to be stopped if user hasn't chosen to ignore regardless // of whether we got a zip file (which we most likely did). // Note: a non-zero exitcode and presence of warnings are mutually exclusive if ( ( ! @file_exists( $temp_zip ) ) || ( 0 != $exitcode ) || ( ( true == $have_zip_warnings ) && !$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, ( ( 1 == $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 (this will always be in the 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 for pclzip the zip file is always created in the temporary // location regardless of whether the user selected to ignore errors or not (we can never guarantee to create a valid // zip file because the script might be terminated by the server so we must wait to produce a valid file and then // move it to the final location if it is valid). // 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 { // Got file with no error or warnings _or_ with warnings that the user has chosen to ignore // File always built in temporary location so always 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(); // Relocate the temporary zip file to final location @rename( $temp_zip, $zip ); // Check that we moved the file ok 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() ) ) ); $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 ); } if ( NULL != $za ) { unset( $za ); } 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 = '' ) { $result = false; $za = NULL; // Update the definition before it is used by loading the library // This will not wok if perchance the file has already been loaded :-( // TODO: Need a temporary directory that we can use for this //define( 'PCLZIP_TEMPORARY_DIR', $tempdir ); // This should give us a new archive object, if not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and it has content if ( ( $content_list = $za->extract( PCLZIP_OPT_PATH, $destination_directory ) ) !== 0 ) { // How many files - must be >0 to have got here $file_count = sizeof( $content_list ); pb_backupbuddy::status( 'details', sprintf( __('pclzip extracted file contents (%1$s to %2$s)','it-l10n-backupbuddy' ), $zip_file, $destination_directory ) );
$this->log_archive_file_stats( $zip_file ); $result = true; } else { // Couldn't open archive - will return for maybe another method to try $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', sprintf( __('pclzip failed to open 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;
} } if ( NULL != $za ) { unset( $za ); } 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 ) { $result = false; $za = NULL; $stat = array(); // This should give us a new archive object, if not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated ziparchive but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and it has content if ( ( $content_list = $za->listContent() ) !== 0 ) { // 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) ) { // First we'll extract and junk the path // Note: For some odd reason when we have a $what file that is a hidden (dot) file // the file_exists() test in pclzip for the filepath to extract to returns true even // though only the parent directory exists and not the file itself. No idea why at // present. Because of that we have to use the PCL_ZIP_OPT_REPLACE_NEWER option // so the fact the test returns true is ignored. $extract_list = $za->extract( PCLZIP_OPT_PATH, $destination_directory, PCLZIP_OPT_BY_NAME, $what, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_REPLACE_NEWER ); // Check whether we succeeded or not (would only be no list array for a zip file problem) // but extraction of the file itself may still have failed $result = ( $extract_list !== 0 && ( $extract_list[ 0 ][ 'status' ] == 'ok' ) ); } elseif ( !empty( $where ) ) { if ( $what === $where ) { // Check for wildcard directory extraction like dir/* => dir/* if ( "*" == substr( trim( $what ), -1 ) ) {
// Turn this into a preg_match pattern $whatmatch = "|^" . $what . "|";
// First we'll extract but we're not junking the paths // Note: For some odd reason when we have a $what file that is a hidden (dot) file // the file_exists() test in pclzip for the filepath to extract to returns true even // though only the parent directory exists and not the file itself. No idea why at // present. Because of that we have to use the PCL_ZIP_OPT_REPLACE_NEWER option // so the fact the test returns true is ignored. $extract_list = $za->extract( PCLZIP_OPT_PATH, $destination_directory, PCLZIP_OPT_BY_PREG, $whatmatch, PCLZIP_OPT_REPLACE_NEWER );
// Check whether we succeeded or not (would only be no list array for a zip file problem) // but extraction of individual files themselves may still have failed if ( 0 !== $extract_list ) { // So far so good - assume everything will be ok $result = true; // At least we got no major failure so check the extracted files foreach ( $extract_list as $file ) { if ( 'ok' !== $file[ 'status' ] ) { // Oops - we found a file that didn't extract ok so bail out with false $result = false; break; } } } } else { // It's just a single file extraction - breath a sign of relief // Extract to same directory structure - don't junk path, no need to add where to destnation as automatic // Note: For some odd reason when we have a $what file that is a hidden (dot) file // the file_exists() test in pclzip for the filepath to extract to returns true even // though only the parent directory exists and not the file itself. No idea why at // present. Because of that we have to use the PCL_ZIP_OPT_REPLACE_NEWER option // so the fact the test returns true is ignored. $extract_list = $za->extract( PCLZIP_OPT_PATH, $destination_directory, PCLZIP_OPT_BY_NAME, $what, PCLZIP_OPT_REPLACE_NEWER ); // Check whether we succeeded or not (would only be no list array for a zip file problem) // but extraction of the file itself may still have failed $result = ( $extract_list !== 0 && ( $extract_list[ 0 ][ 'status' ] == 'ok' ) );
} } else {
// First we'll extract and junk the path // Note: For some odd reason when we have a $what file that is a hidden (dot) file // the file_exists() test in pclzip for the filepath to extract to returns true even // though only the parent directory exists and not the file itself. No idea why at // present. Because of that we have to use the PCL_ZIP_OPT_REPLACE_NEWER option // so the fact the test returns true is ignored. $extract_list = $za->extract( PCLZIP_OPT_PATH, $destination_directory, PCLZIP_OPT_BY_NAME, $what, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_REPLACE_NEWER ); // Check whether we succeeded or not (would only be no list array for a zip file problem) // but extraction of the file itself may still have failed $result = ( $extract_list !== 0 && ( $extract_list[ 0 ][ 'status' ] == 'ok' ) );
// Will need to rename if the extract is ok $rename_required = true; } } // 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 // Currently we can only distinguish between success and failure but no finer grain if ( true === $result ) { pb_backupbuddy::status( 'details', sprintf( __('pclzip extracted file contents (%1$s from %2$s to %3$s%4$s)','it-l10n-backupbuddy' ), $what, $zip_file, $destination_directory, $where ) );
// 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 ); }
} else { // For now let's just print the error code and drop through $error_string = $za->errorInfo(); pb_backupbuddy::status( 'details', sprintf( __('pclzip failed to open/process file to extract file 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 ) ); // May seem redundant but belt'n'braces $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 { // Couldn't open archive - will return for maybe another method to try $error_string = $za->errorInfo( $result ); pb_backupbuddy::status( 'details', sprintf( __('pclzip failed to open 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;
} $za->close(); } if ( NULL != $za ) { unset( $za ); } 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 * * @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 = array( 1, "Generic failure indication" ); $za = NULL; $stat = array(); // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) );
// Return an error code and a description - this needs to be handled more generically $result = array( 1, "Class not available to match method" ); } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and it has content if ( ( $content_list = $za->listContent() ) !== 0 ) { // Assume failure $result = false; // Get each file in sequence by index and get the properties for ( $i = 0; $i < sizeof( $content_list ); $i++ ) { $stat = $content_list[ $i ]; // Assume the key exists (consider testing) if ( $stat[ 'filename' ] == $locate_file ) { // File found so we can note that pb_backupbuddy::status( 'details', __('File found (pclzip)','it-l10n-backupbuddy' ) . ': ' . $locate_file ); $result = true; // Need to exit the for loop break; } } if ( false === $result ) { // Only get here if the file wasn't found pb_backupbuddy::status( 'details', __('File not found (pclzip)','it-l10n-backupbuddy' ) . ': ' . $locate_file ); }
} else { // Couldn't open archive - will return for maybe another method to try $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', sprintf( __('pclzip failed to open 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" );
} } if ( NULL != $za ) { unset( $za ); } 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 ) { $file_list = array(); $result = false; $za = NULL; $stat = array(); // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and it has content if ( 0 !== ( $content_list = $za->listContent() ) ) { // How many files - must be >0 to have got here $file_count = sizeof( $content_list ); // Get each file in sequence by index and get the properties for ( $i = 0; $i < $file_count; $i++ ) { $stat = $content_list[ $i ]; // Assume all these keys do exist (consider testing) $file_list[] = array( $stat[ 'filename' ], $stat[ 'size' ], $stat[ 'compressed_size' ], $stat[ 'mtime' ] ); } pb_backupbuddy::status( 'details', sprintf( __('pclzip listed file contents (%1$s)','it-l10n-backupbuddy' ), $zip_file ) );
$this->log_archive_file_stats( $zip_file ); $result = &$file_list; } else { // Couldn't open archive - will return for maybe another method to try $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', sprintf( __('pclzip failed to open 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;
} } if ( NULL != $za ) { unset( $za ); } 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; $za = NULL; // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and we added the comment ok // Note: using empty array as we don't actually want to add any files if ( 0 !== ( $list = $za->add( array(), PCLZIP_OPT_COMMENT, $comment ) ) ) { // We got a list back so adding comment should have been successful pb_backupbuddy::status( 'details', sprintf( __('PclZip set comment in file %1$s','it-l10n-backupbuddy' ), $zip_file ) ); $result = true; } else { // If we failed to set the commnent then log it (?) and drop through $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', sprintf( __('PclZip failed to set comment in file %1$s - Error Info: %2$s','it-l10n-backupbuddy' ), $zip_file, $error_string ) ); $result = false; } } if ( NULL != $za ) { unset( $za ); } 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; $za = NULL; // This should give us a new archive object, of not catch it and bail out try { $za = new pluginbuddy_PclZip( $zip_file ); $result = true; } catch ( Exception $e ) { // Something fishy - the methods indicated pclzip but we couldn't find the class $error_string = $e->getMessage(); pb_backupbuddy::status( 'details', sprintf( __('pclzip indicated as available method but error reported: %1$s','it-l10n-backupbuddy' ), $error_string ) ); $result = false; } // Only continue if we have a valid archive object if ( true === $result ) { // Make sure we opened the zip ok and it has properties if ( 0 !== ( $properties = $za->properties() ) ) { // We got properties so should have a comment to return, even if empty pb_backupbuddy::status( 'details', sprintf( __('PclZip retrieved comment in file %1$s','it-l10n-backupbuddy' ), $zip_file ) ); $result = $properties[ 'comment' ]; } else { // If we failed to get the commnent then log it (?) and drop through $error_string = $za->errorInfo( true ); pb_backupbuddy::status( 'details', sprintf( __('PclZip failed to retrieve comment in file %1$s - Error Info: %2$s','it-l10n-backupbuddy' ), $zip_file, $error_string ) ); $result = false; } } if ( NULL != $za ) { unset( $za ); } return $result; } } // end pluginbuddy_zbzippclzip class. } ?>
|