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
|
<?php // Helper functions for BackupBuddy. // TODO: Eventually break out of a lot of these from BB core. Migrating from old framework to new resulted in this mid-way transition but it's a bit messy...
class backupbuddy_core {
const MAX_SECONDS_TO_KEEP_ORPHANED_FILEOPTIONS_FILES = 2592000; // 30 days - Once this time has passed then the housekeeping cleanup function will be given the go-ahead to delete fileoptions files that have no local backup zip file that matches their serial. We keep these for a while so the Recent Backups page will keep them in its list. private static $_cachedLogDirectory = ''; // Cached log dir for getLogDirectory() to prevent having to call WP to retrieve. public static $warn_plugins = array( 'w3-total-cache.php' => 'W3 Total Cache', 'wp-cache.php' => 'WP Super Cache', );
public static function prettyFunctionTitle( $function, $args = '' ) {
if ( $function == 'backup_create_database_dump' ) { $functionTitle = 'Backing up database'; if ( '' != $args ) { $subFunctionTitle = 'Tables: ' . implode( ', ', $args[0] ); } } elseif ( $function == 'backup_zip_files' ) { $functionTitle = 'Zipping up files'; } elseif ( $function == 'integrity_check' ) { $functionTitle = 'Verifying backup file integrity'; } elseif ( $function == 'post_backup' ) { $functionTitle = 'Cleaning up'; } elseif ( $function == 'ms_download_extract_wordpress' ) { $functionTitle = 'Downloading WordPress core files from wordpress.org'; } elseif ( $function == 'ms_create_wp_config' ) { $functionTitle = 'Generating standard wp-config.php for export'; } elseif ( $function == 'ms_copy_plugins' ) { $functionTitle = 'Copying plugins'; } elseif ( $function == 'ms_copy_themes' ) { $functionTitle = 'Copying themes'; } elseif ( $function == 'ms_copy_media' ) { $functionTitle = 'Copying media'; } elseif ( $function == 'ms_copy_users_table' ) { $functionTitle = 'Copying users'; } elseif ( $function == 'ms_cleanup' ) { $functionTitle = 'Cleaning up Multisite-specific temporary data'; } else { $functionTitle = $function; }
return $functionTitle; } // end prettyFunctionTitle().
/* is_network_activated() * * Returns a boolean indicating whether a plugin is network activated or not. * * @return boolean True if plugin is network activated, else false. */ public static function is_network_activated() {
if ( !function_exists( 'is_plugin_active_for_network' ) ) { // Function is not available on all WordPress pages for some reason according to codex. require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } if ( is_plugin_active_for_network( basename( pb_backupbuddy::plugin_path() ) . '/' . pb_backupbuddy::settings( 'init' ) ) ) { // Path relative to wp-content\plugins\ directory. return true; } else { return false; }
} // End is_network_activated().
/* backup_integrity_check() * * Scans a backup file and saves the result in data structure. Checks for key files & that .zip can be read properly. Stores results with details in data structure. * * @param string $file Full pathname & filename to backup file to check. * @param obj $fileoptions fileoptions object currently holding the fileoptions file open, if any. * @param array $options Array of options. * @return array Returns integrity data array. */ public static function backup_integrity_check( $file, $fileoptions = '', $options = array(), $skipLogRedirect = false ) { return include( '_integrityCheck.php'); } // End backup_integrity_check().
/* get_serial_from_file() * * Returns the backup serial based on the filename. * * @param string $file Filename containing a serial to extract. * @return string Serial found. Empty string if unable to find serial. */ public static function get_serial_from_file( $file ) { if ( false === ( $dashpos = strrpos( $file, '-' ) ) ) { return ''; } $serial = $dashpos + 1; $serial = substr( $file, $serial, ( strlen( $file ) - $serial - 4 ) ); return $serial; } // End get_serial_from_file().
/** * versions_confirm() * * Check the version of an item and compare it to the minimum requirements BackupBuddy requires. * * @param string $type Optional. If left blank '' then all tests will be performed. Valid values: wordpress, php, ''. * @param boolean $notify Optional. Whether or not to alert to the screen (and throw error to log) of a version issue.\ * @return boolean True if the selected type is a bad version */ public static function versions_confirm( $type = '', $notify = false ) {
$bad_version = false;
if ( ( $type == 'wordpress' ) || ( $type == '' ) ) { global $wp_version; if ( version_compare( $wp_version, pb_backupbuddy::settings( 'wp_minimum' ), '<=' ) ) { if ( $notify === true ) { pb_backupbuddy::alert( sprintf( __('ERROR: BackupBuddy requires WordPress version %1$s or higher. You may experience unexpected behavior or complete failure in this environment. Please consider upgrading WordPress.', 'it-l10n-backupbuddy' ), self::_wp_minimum) ); pb_backupbuddy::log( 'Unsupported WordPress Version: ' . $wp_version , 'error' ); } $bad_version = true; } } if ( ( $type == 'php' ) || ( $type == '' ) ) { if ( version_compare( PHP_VERSION, pb_backupbuddy::settings( 'php_minimum' ), '<=' ) ) { if ( $notify === true ) { pb_backupbuddy::alert( sprintf( __('ERROR: BackupBuddy requires PHP version %1$s or higher. You may experience unexpected behavior or complete failure in this environment. Please consider upgrading PHP.', 'it-l10n-backupbuddy' ), PHP_VERSION ) ); pb_backupbuddy::log( 'Unsupported PHP Version: ' . PHP_VERSION , 'error' ); } $bad_version = true; } }
return $bad_version;
} // End versions_confirm().
/* getBackupDirectory() backupbuddy_core::getBackupDirectory() * * Retrieve directory for storing backups within. * * @return string Full path to directory, including trailing slash. * */ public static function getBackupDirectory() { if ( '' == pb_backupbuddy::$options['backup_directory'] ) { $dir = self::_getBackupDirectoryDefault(); } else { $dir = pb_backupbuddy::$options['backup_directory']; } return $dir; }
/* getLogDirectory() backupbuddy_core::getLogDirectory() * * Retrieve directory for storing logs within. Caches * * @return string Full path to directory, including trailing slash. * */ public static function getLogDirectory() { if ( '' != self::$_cachedLogDirectory ) { return self::$_cachedLogDirectory; } if ( defined( 'PB_STANDALONE' ) && ( true === PB_STANDALONE ) ) { return ABSPATH . 'importbuddy/'; } $uploads_dirs = wp_upload_dir(); self::$_cachedLogDirectory = $uploads_dirs['basedir'] . '/pb_backupbuddy/'; return self::$_cachedLogDirectory; } // End getLogDirectory().
/* getTempDirectory() backupbuddy_core::getTempDirectory() * * Retrieve temporary directory for storing temporary files within. * * @return string Full path to directory, including trailing slash. * */ // backupbuddy_core::getTempDirectory() public static function getTempDirectory() { return ABSPATH . 'wp-content/uploads/backupbuddy_temp/'; } // End getTempDirectory().
/* _getBackupDirectoryDefault() * * Default directory backups will be stored in. getBackupDirectory() uses this as the default if no path is specifically set. * * @return string Full path to directory, including trailing slash. * */ public static function _getBackupDirectoryDefault() { if ( defined( 'PB_IMPORTBUDDY' ) && ( true === PB_IMPORTBUDDY ) ) { return ABSPATH; } $uploads_dirs = wp_upload_dir(); return $uploads_dirs['basedir'] . '/backupbuddy_backups/'; } // End _getBackupDirectoryDefault().
/* get_directory_exclusions() * * Get sanitized directory exclusions. Exclusions are relative to site root (ABSPATH). See important note below! * IMPORTANT NOTE: Cannot exclude the temp directory here as this is where SQL and DAT files are stored for inclusion in the backup archive. * * @param array $profile Profile array of data. * @param bool $trim_suffix True (default) if trailing slash should be trimmed from directories * @param string $serial Optional serial of current backup. By default all subdirectories within the backupbuddy_temp dir are explicitly excluded. Specifying allows this serial subdirectory to not be excluded. * @return array Array of directories to exclude. */ public static function get_directory_exclusions( $profile, $trim_suffix = true, $serial = '' ) { $profile = array_merge( pb_backupbuddy::settings( 'profile_defaults' ), $profile ); // Get initial array. $exclusions = trim( $profile['excludes'] ); // Trim string. $exclusions = preg_split('/\n|\r|\r\n/', $exclusions ); // Break into array on any type of line ending. // Backup dir can be custom set and even migrated over to have weird slash mismatch issues. Sanitize it. $backupDir = '/' . ltrim( str_replace( ABSPATH, '', self::getBackupDirectory() ), '\\/' ); // BackupBuddy backup storage directory. Normally this should be all good. pb_backupbuddy::status( 'details', 'Initially calculated relative backup storage directory: `' . $backupDir . '.' ); $normedBackupDir = str_replace( '\\', '/', $backupDir ); $normedABSPATH = str_replace( '\\', '/', ABSPATH ); if ( FALSE !== ( stristr( $normedBackupDir, $normedABSPATH ) ) ) { // ABSPATH still exists in the path due to some weird slash direction mismatch. Try to yank it out. pb_backupbuddy::status( 'details', 'ABSPATH `' . ABSPATH . '` still found backup directory path `' . $normedBackupDir . '` so it is still not relative. Using normalized ABSPATH `' . $normedABSPATH . '` and normalized backup directory `' . $normedBackupDir . '` to make relative.' ); $backupDir = str_replace( $normedABSPATH, $normedBackupDir, $backupDir ); } $exclusions[] = $backupDir; $exclusions[] = '/' . ltrim( str_replace( ABSPATH, '', self::getLogDirectory() ), '\\/' ); // BackupBuddy logs & fileoptions data. $exclusions[] = '/importbuddy/'; // Exclude importbuddy directory in root. $exclusions[] = '/importbuddy.php'; // Exclude importbuddy.php script in root. // Exclude all temp directories within backupbuddy_temp, except any subdirectories containing the serial specified (if any). $tempDirs = glob( self::getTempDirectory() . '*', GLOB_ONLYDIR ); if ( ! is_array( $tempDirs ) ) { $tempDirs = array(); } foreach( $tempDirs as $tempDir ) { if ( ( '' == $serial ) || ( false === strstr( $tempDir, $serial ) ) ) { // If no specific serial supplied OR this dir does not contain the serial, exclude it. pb_backupbuddy::status( 'details', 'Excluding additional temp directory subdir: `' . $tempDir . '`.' ); $exclusions[] = '/' . trim( str_replace( ABSPATH, '', $tempDir ), '\\/' ) . '/'; } } // Clean up & sanitize array. if ( $trim_suffix ) { array_walk( $exclusions, create_function( '&$val', '$val = rtrim( trim( $val ), \'/\' );' ) ); // Apply trim to all items within. } else { array_walk( $exclusions, create_function( '&$val', '$val = trim( $val );' ) ); // Apply (whitespace-only) trim to all items within. } $exclusions = array_filter( $exclusions, 'strlen' ); // Remove any empty / blank lines. $exclusions = apply_filters( 'backupbuddy_zip_exclusions', $exclusions ); pb_backupbuddy::status( 'details', 'Initial zip exclusions (after filter): `' . implode( '; ', $exclusions ) . '`.' ); return $exclusions; } // End get_directory_exclusions().
/* mail_error() * * Sends an error email to the defined email address(es) on settings page. * * @param string $message Message to be included in the body of the email. * @param string $override_recipient Email address(es) to send to instead of the normal recipient. * @param string|array String or array of filename(s) to send as email attachments. * @return null */ public static function mail_error( $message, $override_recipient = '', $attachments = array() ) {
if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); }
$subject = pb_backupbuddy::$options['email_notify_error_subject']; $body = pb_backupbuddy::$options['email_notify_error_body'];
$replacements = array( '{site_url}' => site_url(), '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ), '{current_datetime}' => date(DATE_RFC822), '{message}' => $message );
foreach( $replacements as $replace_key => $replacement ) { $subject = str_replace( $replace_key, $replacement, $subject ); $body = str_replace( $replace_key, $replacement, $body ); }
$email = pb_backupbuddy::$options['email_notify_error']; if ( $override_recipient != '' ) { $email = $override_recipient; pb_backupbuddy::status( 'details', 'Overriding email recipient to: `' . $override_recipient . '`.' ); } pb_backupbuddy::status( 'details', 'Sending email error notification with subject `' . $subject . '` to recipient(s): `' . $email . '`.' ); if ( !empty( $email ) ) { if ( pb_backupbuddy::$options['email_return'] != '' ) { $email_return = pb_backupbuddy::$options['email_return']; } else { $email_return = get_option('admin_email'); }
$result = wp_mail( $email, $subject, $body, 'From: BackupBuddy <' . $email_return . ">\r\n".'Reply-To: '.get_option('admin_email')."\r\n", $attachments ); if ( false === $result ) { pb_backupbuddy::status( 'error', 'Error #45443554: Unable to send error email with WordPress wp_mail(). Verify WordPress & Server settings.' ); } }
} // End mail_error().
/* mail_notify_scheduled() * * Sends a message email to the defined email address(es) on settings page. * * @param string $start_or_complete Whether this is the notifcation for starting or completing. Valid values: start, complete * @param string $message Message to be included in the body of the email. * @return null */ public static function mail_notify_scheduled( $serial, $start_or_complete, $message ) {
if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); }
if ( $start_or_complete == 'start' ) { $email = pb_backupbuddy::$options['email_notify_scheduled_start'];
$subject = pb_backupbuddy::$options['email_notify_scheduled_start_subject']; $body = pb_backupbuddy::$options['email_notify_scheduled_start_body'];
$replacements = array( '{site_url}' => site_url(), '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ), '{current_datetime}' => date(DATE_RFC822), '{message}' => $message ); } elseif ( $start_or_complete == 'complete' ) { $email = pb_backupbuddy::$options['email_notify_scheduled_complete'];
$subject = pb_backupbuddy::$options['email_notify_scheduled_complete_subject']; $body = pb_backupbuddy::$options['email_notify_scheduled_complete_body'];
$archive_file = ''; require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #37.' ); $backup_options = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = true, $ignore_lock = true ); if ( true !== ( $result = $backup_options->is_ok() ) ) { pb_backupbuddy::status( 'error', 'Error retrieving fileoptions file `' . backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' . '`. Err 35564332.' ); $archive_file = '[file_unknown]'; $backup_size = '[size_unknown]'; $backup_type = '[type_unknown]'; } else { $archive_file = $backup_options->options['archive_file']; $backup_size = $backup_options->options['archive_size']; $backup_type = $backup_options->options['type']; }
$replacements = array( '{site_url}' => site_url(), '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ), '{current_datetime}' => date(DATE_RFC822), '{message}' => $message,
'{backup_serial}' => $serial, '{download_link}' => pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . basename( $archive_file ), '{backup_file}' => basename( $archive_file ), '{backup_size}' => $backup_size, '{backup_type}' => $backup_type, ); } else { pb_backupbuddy::status( 'error', 'ERROR #54857845785: Fatally halted. Invalid schedule type. Expected `start` or `complete`. Got `' . $start_or_complete . '`.' ); }
foreach( $replacements as $replace_key => $replacement ) { $subject = str_replace( $replace_key, $replacement, $subject ); $body = str_replace( $replace_key, $replacement, $body ); }
if ( pb_backupbuddy::$options['email_return'] != '' ) { $email_return = pb_backupbuddy::$options['email_return']; } else { $email_return = get_option('admin_email'); } pb_backupbuddy::status( 'details', 'Sending email schedule notification. Subject: `' . $subject . '`; body: `' . $body . '`; recipient(s): `' . $email . '`.' ); if ( !empty( $email ) ) { wp_mail( $email, $subject, $body, 'From: BackupBuddy <' . $email_return . ">\r\n".'Reply-To: '.get_option('admin_email')."\r\n"); } } // End mail_notify_scheduled().
/* backup_prefix() * * Strips all non-file-friendly characters from the site URL. Used in making backup zip filename. * * @return string The filename friendly converted site URL. */ public static function backup_prefix() {
$siteurl = site_url(); $siteurl = str_replace( 'http://', '', $siteurl ); $siteurl = str_replace( 'https://', '', $siteurl ); $siteurl = str_replace( '/', '_', $siteurl ); $siteurl = str_replace( '\\', '_', $siteurl ); $siteurl = str_replace( '.', '_', $siteurl ); $siteurl = str_replace( ':', '_', $siteurl ); // Alternative port from 80 is stored in the site url. $siteurl = str_replace( '~', '_', $siteurl ); // Strip ~. return $siteurl;
} // End backup_prefix().
/* get_remote_send_defaults() * * Get default array values for the remote_sends fileoptions files. * @return array * */ public static function get_remote_send_defaults() { return array( 'destination' => 0, 'file' => '', 'file_size' => 0, 'trigger' => '', // What triggered this backup. Valid values: scheduled, manual. 'send_importbuddy' => false, 'start_time' => time(), 'finish_time' => 0, 'status' => 'timeout', // success, failure, timeout (default assumption if this is not updated in this PHP load) 'write_speed' => 0, ); } // End get_remote_send_defaults();
/* send_remote_destination() * * function description * * @param int $destination_id ID number (index of the destinations array) to send it. * @param string $file Full file path of file to send. * @param string $trigger What triggered this backup. Valid values: scheduled, manual. * @param bool $send_importbuddy Whether or not importbuddy.php should also be sent with the file to destination. * @param bool $delete_after Whether or not to delete after send success after THIS send. * @param array $destination_settings If passed then this array is used instead of grabbing from settings. * @return bool Send status. true success, false failed. */ public static function send_remote_destination( $destination_id, $file, $trigger = '', $send_importbuddy = false, $delete_after = false, $identifier = '', $destination_settings = '' ) {
if ( defined( 'PB_DEMO_MODE' ) ) { return false; }
if ( ! file_exists( $file ) ) { pb_backupbuddy::status( 'error', 'Error #8583489734: Unable to send file `' . $file . '` to remote destination as it no longer exists. It may have been deleted or permissions are invalid.' ); return false; }
$migrationkey_transient_time = 60*60*24;
if ( '' == $file ) { $backup_file_size = 50000; // not sure why anything current would be sending importbuddy but NOT sending a backup but just in case... } else { $backup_file_size = filesize( $file ); }
// Generate remote send ID for reference and add it as a new logging serial for better recording details. if ( '' == $identifier ) { $identifier = pb_backupbuddy::random_string( 12 ); }
// Set migration key for later determining last initiated migration. if ( 'migration' == $trigger ) { set_transient( 'pb_backupbuddy_migrationkey', $identifier, $migrationkey_transient_time ); }
pb_backupbuddy::status( 'details', 'Sending file `' . $file . '` to remote destination `' . $destination_id . '` triggered by `' . $trigger . '`.' );
//pb_backupbuddy::status( 'details', 'About to create initial fileoptions data.' ); require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #35.' ); $fileoptions_obj = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $identifier . '.txt', $read_only = false, $ignore_lock = true, $create_file = true ); if ( true !== ( $result = $fileoptions_obj->is_ok() ) ) { pb_backupbuddy::status( 'error', __('Fatal Error #9034 A. Unable to access fileoptions data.', 'it-l10n-backupbuddy' ) . ' Error: ' . $result ); return false; } //pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' ); $fileoptions = &$fileoptions_obj->options; // Set reference.
// Record some statistics. $fileoptions = array_merge( self::get_remote_send_defaults(), array( 'destination' => $destination_id, 'file' => $file, 'file_size' => $backup_file_size, 'trigger' => $trigger, // What triggered this backup. Valid values: scheduled, manual. 'send_importbuddy' => $send_importbuddy, 'start_time' => time(), 'finish_time' => 0, 'status' => 'timeout', // success, failure, timeout (default assumption if this is not updated in this PHP load) 'write_speed' => 0, ) ); pb_backupbuddy::save();
// Prepare variables to pass to remote destination handler. if ( '' == $file ) { // No file to send (blank string file typically happens when just sending importbuddy). $files = array(); } else { $files = array( $file ); } // Destination settings were not passed so get them based on the destination ID provided. if ( ! is_array( $destination_settings ) ) { $destination_settings = &pb_backupbuddy::$options['remote_destinations'][$destination_id]; }
// For Stash we will check the quota prior to initiating send. if ( pb_backupbuddy::$options['remote_destinations'][$destination_id]['type'] == 'stash' ) { // Pass off to destination handler. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' ); $send_result = pb_backupbuddy_destinations::get_info( 'stash' ); // Used to kick the Stash destination into life. $stash_quota = pb_backupbuddy_destination_stash::get_quota( pb_backupbuddy::$options['remote_destinations'][$destination_id], true );
if ( $file != '' ) { $backup_file_size = filesize( $file ); } else { $backup_file_size = 50000; } if ( ( $backup_file_size + $stash_quota['quota_used'] ) > $stash_quota['quota_total'] ) { $message = ''; $message .= "You do not have enough Stash storage space to send this file. Please upgrade your Stash storage at http://ithemes.com/member/panel/stash.php or delete files to make space.\n\n";
$message .= 'Attempting to send file of size ' . pb_backupbuddy::$format->file_size( $backup_file_size ) . ' but you only have ' . $stash_quota['quota_available_nice'] . ' available. '; $message .= 'Currently using ' . $stash_quota['quota_used_nice'] . ' of ' . $stash_quota['quota_total_nice'] . ' (' . $stash_quota['quota_used_percent'] . '%).';
pb_backupbuddy::status( 'error', $message ); backupbuddy_core::mail_error( $message );
$fileoptions['status'] = 'Failure. Insufficient destination space.'; $fileoptions_obj->save();
return false; } else { if ( isset( $stash_quota['quota_warning'] ) && ( $stash_quota['quota_warning'] != '' ) ) {
// We log warning of usage but dont send error email. $message = ''; $message .= 'WARNING: ' . $stash_quota['quota_warning'] . "\n\nPlease upgrade your Stash storage at http://ithemes.com/member/panel/stash.php or delete files to make space.\n\n"; $message .= 'Currently using ' . $stash_quota['quota_used_nice'] . ' of ' . $stash_quota['quota_total_nice'] . ' (' . $stash_quota['quota_used_percent'] . '%).';
pb_backupbuddy::status( 'details', $message ); //backupbuddy_core::mail_error( $message );
} }
}
if ( $send_importbuddy === true ) { pb_backupbuddy::status( 'details', 'Generating temporary importbuddy.php file for remote send.' ); pb_backupbuddy::anti_directory_browsing( backupbuddy_core::getTempDirectory(), $die = false ); $importbuddy_temp = backupbuddy_core::getTempDirectory() . 'importbuddy.php'; // Full path & filename to temporary importbuddy self::importbuddy( $importbuddy_temp ); // Create temporary importbuddy. pb_backupbuddy::status( 'details', 'Generated temporary importbuddy.' ); $files[] = $importbuddy_temp; // Add importbuddy file to the list of files to send. $send_importbuddy = true; // Track to delete after finished. } else { pb_backupbuddy::status( 'details', 'Not sending importbuddy.' ); }
// Clear fileoptions so other stuff can access it if needed. $fileoptions_obj->save(); $fileoptions_obj->unlock(); unset( $fileoptions_obj );
// Pass off to destination handler. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' ); $send_result = pb_backupbuddy_destinations::send( $destination_settings, $files, $identifier, $delete_after ); self::kick_db(); // Kick the database to make sure it didn't go away, preventing options saving.
// Reload fileoptions. pb_backupbuddy::status( 'details', 'About to load fileoptions data for saving send status.' ); require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #34.' ); $fileoptions_obj = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $identifier . '.txt', $read_only = false, $ignore_lock = false, $create_file = false ); if ( true !== ( $result = $fileoptions_obj->is_ok() ) ) { pb_backupbuddy::status( 'error', __('Fatal Error #9034 G. Unable to access fileoptions data.', 'it-l10n-backupbuddy' ) . ' Error: ' . $result ); return false; } pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' ); $fileoptions = &$fileoptions_obj->options; // Set reference.
// Update stats. $fileoptions[$identifier]['finish_time'] = time(); if ( $send_result === true ) { // succeeded. $fileoptions['status'] = 'success'; $fileoptions['finish_time'] = time(); pb_backupbuddy::status( 'details', 'Remote send SUCCESS.' ); } elseif ( $send_result === false ) { // failed. $fileoptions['status'] = 'failure'; pb_backupbuddy::status( 'details', 'Remote send FAILURE.' ); } elseif ( is_array( $send_result ) ) { // Array so multipart. $fileoptions['status'] = 'multipart'; $fileoptions['finish_time'] = 0; $fileoptions['_multipart_id'] = $send_result[0]; $fileoptions['_multipart_status'] = $send_result[1]; pb_backupbuddy::status( 'details', 'Multipart send in progress.' ); } else { pb_backupbuddy::status( 'error', 'Error #5485785576463. Invalid status send result: `' . $send_result . '`.' ); } $fileoptions_obj->save();
// If we sent importbuddy then delete the local copy to clean up. if ( $send_importbuddy !== false ) { @unlink( $importbuddy_temp ); // Delete temporary importbuddy. } // As of v5.0: Post-send deletion now handled within destinations/bootstrap.php send() to support chunked sends. return $send_result;
} // End send_remote_destination().
/* destination_send() * * Send file(s) to a destination. Pass full array of destination settings. * * @param array $destination_settings All settings for this destination for this action. * @param array $files Array of files to send (full path). * @return bool|array Bool true = success, bool false = fail, array = multipart transfer. */ public static function destination_send( $destination_settings, $files, $send_id = '', $delete_after = false ) { // Pass off to destination handler. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' ); $send_result = pb_backupbuddy_destinations::send( $destination_settings, $files, $send_id, $delete_after ); return $send_result; } // End destination_send().
/* backups_list() * * function description * * @param string $type Valid options: default, migrate * @param boolean $subsite_mode When in subsite mode only backups for that specific subsite will be listed. * @return */ public static function backups_list( $type = 'default', $subsite_mode = false ) {
if ( ( pb_backupbuddy::_POST( 'bulk_action' ) == 'delete_backup' ) && ( is_array( pb_backupbuddy::_POST( 'items' ) ) ) ) { $needs_save = false; pb_backupbuddy::verify_nonce( pb_backupbuddy::_POST( '_wpnonce' ) ); // Security check to prevent unauthorized deletions by posting from a remote place. $deleted_files = array(); foreach( pb_backupbuddy::_POST( 'items' ) as $item ) { if ( file_exists( backupbuddy_core::getBackupDirectory() . $item ) ) { if ( @unlink( backupbuddy_core::getBackupDirectory() . $item ) === true ) { $deleted_files[] = $item;
// Cleanup any related fileoptions files. $serial = backupbuddy_core::get_serial_from_file( $item );
$backup_files = glob( backupbuddy_core::getBackupDirectory() . '*.zip' ); if ( ! is_array( $backup_files ) ) { $backup_files = array(); } if ( count( $backup_files ) > 5 ) { // Keep a minimum number of backups in array for stats. $this_serial = self::get_serial_from_file( $item ); $fileoptions_file = backupbuddy_core::getLogDirectory() . 'fileoptions/' . $this_serial . '.txt'; if ( file_exists( $fileoptions_file ) ) { @unlink( $fileoptions_file ); } if ( file_exists( $fileoptions_file . '.lock' ) ) { @unlink( $fileoptions_file . '.lock' ); } $needs_save = true; } } else { pb_backupbuddy::alert( 'Error: Unable to delete backup file `' . $item . '`. Please verify permissions.', true ); } } // End if file exists. } // End foreach. if ( $needs_save === true ) { pb_backupbuddy::save(); }
pb_backupbuddy::alert( __( 'Deleted:', 'it-l10n-backupbuddy' ) . ' ' . implode( ', ', $deleted_files ) ); } // End if deleting backup(s).
$backups = array(); $backup_sort_dates = array(); $files = glob( backupbuddy_core::getBackupDirectory() . 'backup*.zip' ); if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
$backup_prefix = self::backup_prefix(); // Backup prefix for this site. Used for MS checking that this user can see this backup. foreach( $files as $file_id => $file ) {
if ( ( $subsite_mode === true ) && is_multisite() ) { // If a Network and NOT the superadmin must make sure they can only see the specific subsite backups for security purposes.
// Only allow viewing of their own backups. if ( !strstr( $file, $backup_prefix ) ) { unset( $files[$file_id] ); // Remove this backup from the list. This user does not have access to it. continue; // Skip processing to next file. } }
$serial = backupbuddy_core::get_serial_from_file( $file ); $options = array(); if ( file_exists( backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt' ) ) { require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #33.' ); $backup_options = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = false, $ignore_lock = false, $create_file = true ); // Will create file to hold integrity data if nothing exists. } else { $backup_options = ''; } $backup_integrity = backupbuddy_core::backup_integrity_check( $file, $backup_options, $options );
// Backup status. $pretty_status = array( true => '<span class="pb_label pb_label-success">Good</span>', // v4.0+ Good. 'pass' => '<span class="pb_label pb_label-success">Good</span>', // Pre-v4.0 Good. false => '<span class="pb_label pb_label-important">Bad</span>', // v4.0+ Bad. 'fail' => '<span class="pb_label pb_label-important">Bad</span>', // Pre-v4.0 Bad. );
// Backup type. $pretty_type = array( 'full' => 'Full', 'db' => 'Database', 'files' => 'Files', );
// Defaults... $detected_type = ''; $file_size = ''; $modified = ''; $modified_time = 0; $integrity = '';
$main_string = 'Warn#284.'; if ( is_array( $backup_integrity ) ) { // Data intact... put it all together. // Calculate time ago. $time_ago = ''; if ( isset( $backup_integrity['modified'] ) ) { $time_ago = pb_backupbuddy::$format->time_ago( $backup_integrity['modified'] ) . ' ago'; }
$detected_type = pb_backupbuddy::$format->prettify( $backup_integrity['detected_type'], $pretty_type ); if ( $detected_type == '' ) { $detected_type = 'Unknown'; } else { if ( isset( $backup_options->options['profile'] ) ) { $detected_type = ' <div> <span style="color: #AAA; float: left;">' . $detected_type . '</span> <span style="display: inline-block; float: left; height: 15px; border-right: 1px solid #EBEBEB; margin-left: 6px; margin-right: 6px;"></span> ' . htmlentities( $backup_options->options['profile']['title'] ) . ' </div> ' ; } }
$file_size = pb_backupbuddy::$format->file_size( $backup_integrity['size'] ); $modified = pb_backupbuddy::$format->date( pb_backupbuddy::$format->localize_time( $backup_integrity['modified'] ), 'l, F j, Y - g:i:s a' ); $modified_time = $backup_integrity['modified']; if ( isset( $backup_integrity['status'] ) ) { // Pre-v4.0. $status = $backup_integrity['status']; } else { // v4.0+ $status = $backup_integrity['is_ok']; }
// Calculate main row string. if ( $type == 'default' ) { // Default backup listing. $main_string = '<a href="' . pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . basename( $file ) . '" class="backupbuddyFileTitle" title="' . basename( $file ) . '">' . $modified . ' (' . $time_ago . ')</a>'; } elseif ( $type == 'migrate' ) { // Migration backup listing. $main_string = '<a class="pb_backupbuddy_hoveraction_migrate backupbuddyFileTitle" rel="' . basename( $file ) . '" href="' . pb_backupbuddy::page_url() . '&migrate=' . basename( $file ) . '&value=' . basename( $file ) . '" title="' . basename( $file ) . '">' . $modified . ' (' . $time_ago . ')</a>'; } else { $main_string = '{Unknown type.}'; } // Add comment to main row string if applicable. if ( isset( $backup_integrity['comment'] ) && ( $backup_integrity['comment'] !== false ) && ( $backup_integrity['comment'] !== '' ) ) { $main_string .= '<br><span class="description">Note: <span class="pb_backupbuddy_notetext">' . htmlentities( $backup_integrity['comment'] ) . '</span></span>'; }
$integrity = pb_backupbuddy::$format->prettify( $status, $pretty_status ) . ' '; if ( isset( $backup_integrity['scan_notes'] ) && count( (array)$backup_integrity['scan_notes'] ) > 0 ) { foreach( (array)$backup_integrity['scan_notes'] as $scan_note ) { $integrity .= $scan_note . ' '; } } $integrity .= '<a href="' . pb_backupbuddy::page_url() . '&reset_integrity=' . $serial . '" title="Rescan integrity. Last checked ' . pb_backupbuddy::$format->date( $backup_integrity['scan_time'] ) . '."><img src="' . pb_backupbuddy::plugin_url() . '/images/refresh_gray.gif" style="vertical-align: -1px;"></a>'; $integrity .= '<div class="row-actions"><a title="' . __( 'Backup Status', 'it-l10n-backupbuddy' ) . '" href="' . pb_backupbuddy::ajax_url( 'integrity_status' ) . '&serial=' . $serial . '&TB_iframe=1&width=640&height=600" class="thickbox">' . __( 'View Details', 'it-l10n-backupbuddy' ) . '</a></div>'; $sumLogFile = backupbuddy_core::getLogDirectory() . 'status-' . $serial . '_sum_' . pb_backupbuddy::$options['log_serial'] . '.txt'; if ( file_exists( $sumLogFile ) ) { $integrity .= '<div class="row-actions"><a title="' . __( 'View Backup Log', 'it-l10n-backupbuddy' ) . '" href="' . pb_backupbuddy::ajax_url( 'view_log' ) . '&serial=' . $serial . '&TB_iframe=1&width=640&height=600" class="thickbox">' . __( 'View Log', 'it-l10n-backupbuddy' ) . '</a></div>'; } } // end if is_array( $backup_options ).
$backups[basename( $file )] = array( array( basename( $file ), $main_string . '<br><span class="description" style="color: #AAA; display: inline-block; margin-top: 5px;">' . basename( $file ) . '</span>' ), $detected_type, $file_size, $integrity, );
$backup_sort_dates[basename( $file)] = $modified_time;
} // End foreach().
} // End if.
// Sort backup by date. arsort( $backup_sort_dates ); // Re-arrange backups based on sort dates. $sorted_backups = array(); foreach( $backup_sort_dates as $backup_file => $backup_sort_date ) { $sorted_backups[$backup_file] = $backups[$backup_file]; unset( $backups[$backup_file] ); } unset( $backups );
return $sorted_backups;
} // End backups_list().
// 1128 public static function getDatArrayFromZip( $file ) { require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' ); $zipbuddy = new pluginbuddy_zipbuddy( backupbuddy_core::getBackupDirectory() ); $serial = self::get_serial_from_file( $file ); if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, $find = 'wp-content/uploads/backupbuddy_temp/' . $serial . '/backupbuddy_dat.php' ) === true ) { // Post 2.0 full backup } elseif ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, $find = 'wp-content/uploads/temp_' . $serial . '/backupbuddy_dat.php' ) === true ) { // Pre 2.0 full backup } elseif ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, $find = 'backupbuddy_dat.php' ) === true ) { // DB backup } else { // Could not find DAt file. return false; } // Calculate temp directory & lock it down. $temp_dir = get_temp_dir(); $destination = $temp_dir; if ( ( ( ! file_exists( $destination ) ) && ( false === mkdir( $destination ) ) ) ) { $error = 'Error #458485945b: Unable to create temporary location.'; pb_backupbuddy::status( 'error', $error ); die( $error ); }
// If temp directory is within webroot then lock it down. $temp_dir = str_replace( '\\', '/', $temp_dir ); // Normalize for Windows. $temp_dir = rtrim( $temp_dir, '/\\' ) . '/'; // Enforce single trailing slash. if ( FALSE !== stristr( $temp_dir, ABSPATH ) ) { // Temp dir is within webroot. pb_backupbuddy::anti_directory_browsing( $destination ); } unset( $temp_dir ); $extractions = array( $find => 'temp_dat_read-' . $serial . '.php' ); $extract_result = $zipbuddy->extract( $file, $destination, $extractions ); if ( false === $extract_result ) { // failed. return array(); } else { $datArray = self::get_dat_file_array( $destination . 'temp_dat_read-' . $serial . '.php' ); if ( is_array( $datArray ) ) { return $datArray; } else { return array(); } } } // End getDatContentsFromZip().
// If output file not specified then outputs to browser as download. // IMPORTANT: If outputting to browser (no output file) must die() after outputting content if using AJAX. Do not output to browser anything after this function in this case. public static function importbuddy( $output_file = '', $importbuddy_pass_hash = '', $return_not_echo = false ) {
pb_backupbuddy::set_greedy_script_limits(); // Some people run out of PHP memory.
if ( $importbuddy_pass_hash == '' ) { if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); } $importbuddy_pass_hash = pb_backupbuddy::$options['importbuddy_pass_hash']; }
if ( $importbuddy_pass_hash == '' ) { $message = 'Warning #9032 - You have not set an ImportBuddy password on the BackupBuddy Settings page. Once this password is set a copy of the importbuddy.php file needed to restore your backup will be included in Full backup zip files for convenience. It may manually be downloaded from the Restore / Migrate page.'; pb_backupbuddy::status( 'warning', $message ); return false; }
pb_backupbuddy::status( 'details', 'Loading importbuddy core file into memory.' ); $output = file_get_contents( pb_backupbuddy::plugin_path() . '/_importbuddy/_importbuddy.php' ); if ( $importbuddy_pass_hash != '' ) { $output = preg_replace('/#PASSWORD#/', $importbuddy_pass_hash, $output, 1 ); // Only replaces first instance. }
$version_string = pb_backupbuddy::settings( 'version' ) . ' (downloaded ' . date( DATE_W3C ) . ')';
// If on DEV system (.git dir exists) then append some details on current. if ( defined( 'BACKUPBUDDY_DEV' ) && ( true === BACKUPBUDDY_DEV ) ) { if ( @file_exists( pb_backupbuddy::plugin_path() . '/.git/logs/HEAD' ) ) { $commit_log = escapeshellarg( pb_backupbuddy::plugin_path() . '/.git/logs/HEAD' ); $commit_line = exec( "tail -n 1 {$commit_log}" ); $version_string .= ' <span style="font-size: 8px;">[DEV: ' . $commit_line . ']</span>'; } }
$output = preg_replace('/#VERSION#/', $version_string, $output, 1 ); // Only replaces first instance.
// PACK IMPORTBUDDY $_packdata = array( // NO TRAILING OR PRECEEDING SLASHES!
'_importbuddy/importbuddy' => 'importbuddy', 'classes/_migrate_database.php' => 'importbuddy/classes/_migrate_database.php', 'classes/core.php' => 'importbuddy/classes/core.php', 'classes/import.php' => 'importbuddy/classes/import.php', 'classes/restore.php' => 'importbuddy/classes/restore.php', 'classes/_restoreFiles.php' => 'importbuddy/classes/_restoreFiles.php', 'classes/remote_api.php' => 'importbuddy/classes/remote_api.php', 'js/jquery.leanModal.min.js' => 'importbuddy/js/jquery.leanModal.min.js', 'js/jquery.joyride-2.0.3.js' => 'importbuddy/js/jquery.joyride-2.0.3.js', 'js/modernizr.mq.js' => 'importbuddy/js/modernizr.mq.js', 'css/joyride.css' => 'importbuddy/css/joyride.css',
'images/working.gif' => 'importbuddy/images/working.gif', 'images/bullet_go.png' => 'importbuddy/images/bullet_go.png', 'images/favicon.png' => 'importbuddy/images/favicon.png', 'images/sort_down.png' => 'importbuddy/images/sort_down.png', 'images/icon_menu_32x32.png' => 'importbuddy/images/icon_menu_32x32.png',
'lib/dbreplace' => 'importbuddy/lib/dbreplace', 'lib/dbimport' => 'importbuddy/lib/dbimport', 'lib/commandbuddy' => 'importbuddy/lib/commandbuddy', 'lib/zipbuddy' => 'importbuddy/lib/zipbuddy', 'lib/mysqlbuddy' => 'importbuddy/lib/mysqlbuddy', 'lib/textreplacebuddy' => 'importbuddy/lib/textreplacebuddy', 'lib/cpanel' => 'importbuddy/lib/cpanel',
'pluginbuddy' => 'importbuddy/pluginbuddy',
'controllers/pages/server_info' => 'importbuddy/controllers/pages/server_info', 'controllers/pages/server_tools.php' => 'importbuddy/controllers/pages/server_tools.php',
// Stash 'destinations/stash/lib/class.itx_helper.php' => 'importbuddy/classes/class.itx_helper.php', 'destinations/_s3lib/aws-sdk/lib/requestcore' => 'importbuddy/lib/requestcore',
);
pb_backupbuddy::status( 'details', 'Loading each file into memory for writing master importbuddy file.' );
$output .= "\n<?php /*\n###PACKDATA,BEGIN\n"; foreach( $_packdata as $pack_source => $pack_destination ) { $pack_source = '/' . $pack_source; if ( is_dir( pb_backupbuddy::plugin_path() . $pack_source ) ) { $files = pb_backupbuddy::$filesystem->deepglob( pb_backupbuddy::plugin_path() . $pack_source ); } else { $files = array( pb_backupbuddy::plugin_path() . $pack_source ); } foreach( $files as $file ) { if ( is_file( $file ) ) { $source = str_replace( pb_backupbuddy::plugin_path(), '', $file ); $destination = $pack_destination . substr( $source, strlen( $pack_source ) ); $output .= "###PACKDATA,FILE_START,{$source},{$destination}\n"; $output .= base64_encode( file_get_contents( $file ) ); $output .= "\n"; $output .= "###PACKDATA,FILE_END,{$source},{$destination}\n"; } } } $output .= "###PACKDATA,END\n*/"; $output .= "\n\n\n\n\n\n\n\n\n\n";
if ( true === $return_not_echo ) { return $output; }
if ( $output_file == '' ) { // No file so output to browser. header( 'Content-Description: File Transfer' ); header( 'Content-Type: text/plain; name=importbuddy.php' ); header( 'Content-Disposition: attachment; filename=importbuddy.php' ); header( 'Expires: 0' ); header( 'Content-Length: ' . strlen( $output ) );
pb_backupbuddy::flush(); echo $output; pb_backupbuddy::flush();
// BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER! } else { // Write to file. pb_backupbuddy::status( 'details', 'Writing importbuddy master file to disk.' ); if ( false === file_put_contents( $output_file, $output ) ) { pb_backupbuddy::status( 'error', 'Error #483894: Unable to write to file `' . $output_file . '`.' ); } }
} // End importbuddy().
// If output file not specified then outputs to browser as download. // IMPORTANT: If outputting to browser (no output file) must die() after outputting content if using AJAX. Do not output to browser anything after this function in this case. public static function serverbuddy( $output_file = '', $serverbuddy_pass_hash = '' ) { if ( defined( 'PB_DEMO_MODE' ) ) { echo 'Access denied in demo mode.'; return; }
pb_backupbuddy::set_greedy_script_limits(); // Some people run out of PHP memory.
if ( $serverbuddy_pass_hash == '' ) { if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); } $serverbuddy_pass_hash = pb_backupbuddy::$options['importbuddy_pass_hash']; }
if ( $serverbuddy_pass_hash == '' ) { $message = 'Error #9032c: Warning only - You have not set a password to generate the ServerBuddy script yet on the BackupBuddy Settings page. If you were trying to download ServerBuddy then you may have a plugin confict preventing the page from prompting you to enter a password.'; pb_backupbuddy::status( 'warning', $message ); return false; }
$output = file_get_contents( pb_backupbuddy::plugin_path() . '/_serverbuddy/_serverbuddy.php' ); if ( $serverbuddy_pass_hash != '' ) { $output = preg_replace('/#PASSWORD#/', $serverbuddy_pass_hash, $output, 1 ); // Only replaces first instance. } $output = preg_replace('/#VERSION#/', pb_backupbuddy::settings( 'version' ), $output, 1 ); // Only replaces first instance.
// PACK SERVERBUDDY $_packdata = array( // NO TRAILING OR PRECEEDING SLASHES!
'_serverbuddy/serverbuddy' => 'serverbuddy', 'classes/_migrate_database.php' => 'serverbuddy/classes/_migrate_database.php', 'classes/core.php' => 'serverbuddy/classes/core.php',
'images/working.gif' => 'serverbuddy/images/working.gif', 'images/bullet_go.png' => 'serverbuddy/images/bullet_go.png', 'images/favicon.png' => 'serverbuddy/images/favicon.png', 'images/sort_down.png' => 'serverbuddy/images/sort_down.png',
'lib/dbreplace' => 'serverbuddy/lib/dbreplace', 'lib/commandbuddy' => 'serverbuddy/lib/commandbuddy', 'lib/zipbuddy' => 'serverbuddy/lib/zipbuddy', 'lib/mysqlbuddy' => 'serverbuddyy/lib/mysqlbuddy', 'lib/textreplacebuddy' => 'serverbuddy/lib/textreplacebuddy',
'pluginbuddy' => 'serverbuddy/pluginbuddy',
'controllers/pages/server_info' => 'serverbuddy/controllers/pages/server_info', 'controllers/pages/server_tools.php' => 'serverbuddy/controllers/pages/server_tools.php',
);
$output .= "\n<?php /*\n###PACKDATA,BEGIN\n"; foreach( $_packdata as $pack_source => $pack_destination ) { $pack_source = '/' . $pack_source; if ( is_dir( pb_backupbuddy::plugin_path() . $pack_source ) ) { $files = pb_backupbuddy::$filesystem->deepglob( pb_backupbuddy::plugin_path() . $pack_source ); } else { $files = array( pb_backupbuddy::plugin_path() . $pack_source ); } foreach( $files as $file ) { if ( is_file( $file ) ) { $source = str_replace( pb_backupbuddy::plugin_path(), '', $file ); $destination = $pack_destination . substr( $source, strlen( $pack_source ) ); $output .= "###PACKDATA,FILE_START,{$source},{$destination}\n"; $output .= base64_encode( file_get_contents( $file ) ); $output .= "\n"; $output .= "###PACKDATA,FILE_END,{$source},{$destination}\n"; } } } $output .= "###PACKDATA,END\n*/"; $output .= "\n\n\n\n\n\n\n\n\n\n";
if ( $output_file == '' ) { // No file so output to browser. header( 'Content-Description: File Transfer' ); header( 'Content-Type: text/plain; name=importbuddy.php' ); header( 'Content-Disposition: attachment; filename=importbuddy.php' ); header( 'Expires: 0' ); header( 'Content-Length: ' . strlen( $output ) );
pb_backupbuddy::flush(); echo $output; pb_backupbuddy::flush();
// BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER! } else { // Write to file. file_put_contents( $output_file, $output ); }
} // End serverbuddy().
// TODO: RepairBuddy is not yet converted into new framework so just using pre-BB3.0 version for now. public static function repairbuddy( $output_file = '' ) { if ( defined( 'PB_DEMO_MODE' ) ) { echo 'Access denied in demo mode.'; return; }
if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); } $output = file_get_contents( pb_backupbuddy::plugin_path() . '/_repairbuddy.php' ); if ( pb_backupbuddy::$options['importbuddy_pass_hash'] != '' ) { $output = preg_replace('/#PASSWORD#/', pb_backupbuddy::$options['importbuddy_pass_hash'], $output, 1 ); // Only replaces first instance. } $output = preg_replace('/#VERSION#/', pb_backupbuddy::settings( 'version' ), $output, 1 ); // Only replaces first instance.
if ( $output_file == '' ) { // No file so output to browser. header( 'Content-Description: File Transfer' ); header( 'Content-Type: text/plain; name=repairbuddy.php' ); header( 'Content-Disposition: attachment; filename=repairbuddy.php' ); header( 'Expires: 0' ); header( 'Content-Length: ' . strlen( $output ) );
pb_backupbuddy::flush(); echo $output; pb_backupbuddy::flush();
// BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER! } else { // Write to file. file_put_contents( $output_file, $output ); }
} // End repairbuddy().
/* pretty_destination_type() * * Take a destination type slug and change it into a user-friendly display of the destination type. * * @param string Internal destination slug. Eg: s3 * @return string Friendly destination title. Eg: Amazon S3 * */ public static function pretty_destination_type( $type ) { if ( $type == 'rackspace' ) { return 'Rackspace'; } elseif ( $type == 'email' ) { return 'Email'; } elseif ( $type == 's3' ) { return 'Amazon S3'; } elseif ( $type == 'ftp' ) { return 'FTP'; } elseif ( $type == 'dropbox' ) { return 'Dropbox'; } else { return $type; } } // End pretty_destination_type().
/* build_icicle() * * Build directory tree for use with the "icicle" javascript library for the graphical directory display on Server Tools page. * * @param string $dir * @param ? $base * @param ? $icicle_json * @param int $max_depth Maximum depth of tree to display. Note that deeper depths are still traversed for size calculations. Default: 10 * @param int $depth_count Default: 0 * @param bool $is_root Default: true * */ public static function build_icicle( $dir, $base, $icicle_json, $max_depth = 10, $depth_count = 0, $is_root = true ) { $bg_color = '005282';
$depth_count++; $bg_color = dechex( hexdec( $bg_color ) - ( $depth_count * 15 ) );
$icicle_json = '{' . "\n";
$dir_name = $dir; $dir_name = str_replace( ABSPATH, '', $dir ); $dir_name = str_replace( '\\', '/', $dir_name );
$dir_size = 0; $sub = opendir( $dir ); $has_children = false; while( $file = readdir( $sub ) ) { if ( ( $file == '.' ) || ( $file == '..' ) ) { continue; // Next loop. } elseif ( is_dir( $dir . '/' . $file ) ) {
$dir_array = ''; $response = self::build_icicle( $dir . '/' . $file, $base, $dir_array, $max_depth, $depth_count, false ); if ( ( $max_depth-1 > 0 ) || ( $max_depth == -1 ) ) { // Only adds to the visual tree if depth isnt exceeded. if ( $max_depth > 0 ) { $max_depth = $max_depth - 1; }
if ( $has_children === false ) { // first loop add children section $icicle_json .= '"children": [' . "\n"; } else { $icicle_json .= ','; } $icicle_json .= $response[0];
$has_children = true; } $dir_size += $response[1]; unset( $response ); unset( $file );
} else { $stats = stat( $dir . '/' . $file ); $dir_size += $stats['size']; unset( $file ); } } closedir( $sub ); unset( $sub );
if ( $has_children === true ) { $icicle_json .= ' ]' . "\n"; }
if ( $has_children === true ) { $icicle_json .= ','; }
$icicle_json .= '"id": "node_' . str_replace( '/', ':', $dir_name ) . ': ^' . str_replace( ' ', '~', pb_backupbuddy::$format->file_size( $dir_size ) ) . '"' . "\n";
$dir_name = str_replace( '/', '', strrchr( $dir_name, '/' ) ); if ( $dir_name == '' ) { // Set root to be /. $dir_name = '/'; } $icicle_json .= ', "name": "' . $dir_name . ' (' . pb_backupbuddy::$format->file_size( $dir_size ) . ')"' . "\n";
$icicle_json .= ',"data": { "$dim": ' . ( $dir_size + 10 ) . ', "$color": "#' . str_pad( $bg_color, 6, '0', STR_PAD_LEFT ) . '" }' . "\n"; $icicle_json .= '}';
if ( $is_root !== true ) { //$icicle_json .= ',x'; }
return array( $icicle_json, $dir_size ); } // End build_icicle().
// return array of tests and their results. public static function preflight_check() { $tests = array();
// MULTISITE BETA WARNING. if ( is_multisite() && backupbuddy_core::is_network_activated() && !defined( 'PB_DEMO_MODE' ) ) { // Multisite installation. $tests[] = array( 'test' => 'multisite_beta', 'success' => false, 'message' => 'WARNING: BackupBuddy Multisite functionality is EXPERIMENTAL and NOT officially supported. Multiple issues are known. Usage of it is at your own risk and should not be relied upon. Standalone WordPress sites are suggested. You may use the "Export" feature to export your subsites into standalone WordPress sites. To enable experimental BackupBuddy Multisite functionality you must add the following line to your wp-config.php file: <b>define( \'PB_BACKUPBUDDY_MULTISITE_EXPERIMENT\', true );</b> ' ); } // end network-activated multisite.
// LOOPBACKS TEST. if ( ( $loopback_response = self::loopback_test() ) === true ) { $success = true; $message = ''; } else { // failed $success = false; if ( defined( 'ALTERNATE_WP_CRON' ) && ( ALTERNATE_WP_CRON == true ) ) { $message = __('Running in Alternate WordPress Cron mode. HTTP Loopback Connections are not enabled on this server but you have overridden this in the wp-config.php file (this is a good thing).', 'it-l10n-backupbuddy' ) . ' <a href="http://ithemes.com/codex/page/BackupBuddy:_Frequent_Support_Issues#HTTP_Loopback_Connections_Disabled" target="_new">' . __('Additional Information Here', 'it-l10n-backupbuddy' ) . '</a>.'; } else { $message = __('HTTP Loopback Connections are not enabled on this server or are not functioning properly. You may encounter stalled, significantly delayed backups, or other difficulties. See details in the box below. This may be caused by a conflicting plugin such as a caching plugin.', 'it-l10n-backupbuddy' ) . ' <a href="http://ithemes.com/codex/page/BackupBuddy:_Frequent_Support_Issues#HTTP_Loopback_Connections_Disabled" target="_new">' . __('Click for instructions on how to resolve this issue.', 'it-l10n-backupbuddy' ) . '</a>'; $message .= ' <b>Details:</b> <textarea style="height: 50px; width: 100%;">' . $loopback_response . '</textarea>'; } } $tests[] = array( 'test' => 'loopbacks', 'success' => $success, 'message' => $message, );
// POSSIBLE CACHING PLUGIN CONFLICT WARNING. $success = true; $message = ''; $found_plugins = array(); if ( ! is_multisite() ) { $active_plugins = serialize( get_option( 'active_plugins' ) ); foreach( self::$warn_plugins as $warn_plugin => $warn_plugin_title ) { if ( FALSE !== strpos( $active_plugins, $warn_plugin ) ) { // Plugin active. $found_plugins[] = $warn_plugin_title; $success = false; } } } if ( count( $found_plugins ) > 0 ) { $message = __( 'One or more caching plugins were detected as activated. Some caching plugin configurations may possibly cache & interfere with backup processes or WordPress cron. If you encounter problems clear the caching plugin\'s cache (deactivating the plugin may help) to troubleshoot.', 'it-l10n-backupbuddy' ) . ' '; $message .= __( 'Activated caching plugins detected:', 'it-l10n-backupbuddy' ) . ' '; $message .= implode( ', ', $found_plugins ); $message .= '.'; } $tests[] = array( 'test' => 'loopbacks', 'success' => $success, 'message' => $message, );
// WORDPRESS IN SUBDIRECTORIES TEST. $wordpress_locations = self::get_wordpress_locations(); if ( count( $wordpress_locations ) > 0 ) { $success = false; $message = __( 'WordPress may have been detected in one or more subdirectories. Backing up multiple instances of WordPress may result in server timeouts due to increased backup time. You may exclude WordPress directories via the Settings page. Detected non-excluded locations:', 'it-l10n-backupbuddy' ) . ' ' . implode( ', ', $wordpress_locations ); } else { $success = true; $message = ''; } $tests[] = array( 'test' => 'wordpress_subdirectories', 'success' => $success, 'message' => $message, );
// Log file directory writable for status logging. $status_directory = backupbuddy_core::getLogDirectory(); if ( ! file_exists( $status_directory ) ) { if ( false === pb_backupbuddy::anti_directory_browsing( $status_directory, $die = false ) ) { $success = false; $message = 'The status log file directory `' . $status_directory . '` is not creatable or permissions prevent access. Verify permissions of it and/or its parent directory. Backup status information will be unavailable until this is resolved.'; } } if ( ! is_writable( $status_directory ) ) { $success = false; $message = 'The status log file directory `' . $status_directory . '` is not writable. Please verify permissions before creating a backup. Backup status information will be unavailable until this is resolved.'; } else { $success = true; $message = ''; } $tests[] = array( 'test' => 'status_directory_writable', 'success' => $success, 'message' => $message, );
// CHECK ZIP AVAILABILITY. require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' );
if ( !isset( pb_backupbuddy::$classes['zipbuddy'] ) ) { pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy( backupbuddy_core::getBackupDirectory() ); }
/***** BEGIN LOOKING FOR UNFINISHED RECENT BACKUPS *****/ if ( '' != pb_backupbuddy::$options['last_backup_serial'] ) { $lastBackupFileoptions = backupbuddy_core::getLogDirectory() . 'fileoptions/' . pb_backupbuddy::$options['last_backup_serial'] . '.txt'; if ( file_exists( $lastBackupFileoptions ) ) { require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #32.' ); $backup_options = new pb_backupbuddy_fileoptions( $lastBackupFileoptions, $read_only = true ); if ( true !== ( $result = $backup_options->is_ok() ) || ( ! isset( $backup_options->options['updated_time'] ) ) ) { // NOTE: If this files during a backup it may try to read the fileoptions file too early due to the last_backup_serial being set. Suppressing errors for now. pb_backupbuddy::status( 'details', 'Unable to retrieve fileoptions file (this is normal if a backup is currently in process & may be ignored) `' . backupbuddy_core::getLogDirectory() . 'fileoptions/' . pb_backupbuddy::$options['last_backup_serial'] . '.txt' . '`. Err 54478236765. Details: `' . $result . '`.' ); } else { if ( $backup_options->options['updated_time'] < 180 ) { // Been less than 3min since last backup.
if ( !empty( $backup_options->options['steps'] ) ) { // Look for incomplete steps. $found_unfinished = false; foreach( $backup_options->options['steps'] as $step ) { if ( $step['finish_time'] == '0' ) { // Found an unfinished step. $found_unfinished = true; break; } } // end foreach.
if ( $found_unfinished === true ) { $tests[] = array( 'test' => 'recent_backup', 'success' => false, 'message' => __('A backup was recently started and reports unfinished steps. You should wait unless you are sure the previous backup has completed or failed to avoid placing a heavy load on your server.', 'it-l10n-backupbuddy' ) . ' Last updated: ' . pb_backupbuddy::$format->date( $backup_options->options['updated_time'] ) . '; '. ' Serial: ' . pb_backupbuddy::$options['last_backup_serial'] , ); } // end $found_unfinished === true.
} // end if.
} } } } /***** END LOOKING FOR UNFINISHED RECENT BACKUPS *****/
/***** BEGIN LOOKING FOR BACKUP FILES IN SITE ROOT *****/ $files = glob( ABSPATH . 'backup-*.zip' ); if ( !is_array( $files ) || empty( $files ) ) { $files = array(); } foreach( $files as &$file ) { $file = basename( $file ); } if ( count( $files ) > 0 ) { $files_string = implode( ', ', $files ); $tests[] = array( 'test' => 'root_backups-' . $files_string, 'success' => false, 'message' => 'One or more backup files, `' . $files_string . '` was found in the root directory of this site. This may be leftover from a recent restore. You should usually remove backup files from the site root for security.', ); } /***** END LOOKING FOR BACKUP FILES IN SITE ROOT *****/
return $tests;
} // End preflight_check().
// returns true on success, error message otherwise. /* loopback_test() * * Connects back to same site via AJAX call to an AJAX slug that has NOT been registered. * WordPress AJAX returns a -1 (or 0 in newer version?) for these. Also not logged into * admin when connecting back. Checks to see if body contains -1 / 0. If loopbacks are not * enabled then will fail connecting or do something else. * * * @param * @return boolean True on success, string error message otherwise. */ public static function loopback_test() { $loopback_url = admin_url('admin-ajax.php'); pb_backupbuddy::status( 'details', 'Testing loopback connections by connecting back to site at the URL: `' . $loopback_url . '`. It should display simply "0" or "-1" in the body.' );
$response = wp_remote_get( $loopback_url, array( 'method' => 'GET', 'timeout' => 8, // X second delay. A loopback should be very fast. 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array() ) );
if( is_wp_error( $response ) ) { // Loopback failed. Some kind of error. $error = $response->get_error_message(); pb_backupbuddy::status( 'error', 'Loopback test error: `' . $error . '`. URL: `' . $loopback_url . '`.' ); return 'Error: ' . $error; } else { if ( ( $response['body'] == '-1' ) || ( $response['body'] == '0' ) ) { // Loopback succeeded. pb_backupbuddy::status( 'details', 'HTTP Loopback test success. Returned `' . $response['body'] . '`.' ); return true; } else { // Loopback failed. $error = 'Connected to server but unexpected output: ' . htmlentities( $response['body'] ); pb_backupbuddy::status( 'error', $error ); return $error; } } } // End loopback_test().
/* get_wordpress_locations() * * Get an array of subdirectories where potential WordPress installations have been detected. * * @return array Array of full paths, WITHOUT trailing slashes. * */ public static function get_wordpress_locations() { $wordpress_locations = array();
$files = glob( ABSPATH . '*/' ); if ( !is_array( $files ) || empty( $files ) ) { $files = array(); }
foreach( $files as $file ) { if ( file_exists( $file . 'wp-config.php' ) ) { $wordpress_locations[] = rtrim( '/' . str_replace( ABSPATH, '', $file ), '/\\' ); } }
// Remove any excluded directories from showing up in this. $directory_exclusions = self::get_directory_exclusions( pb_backupbuddy::$options['profiles'][0] ); // default profile. $wordpress_locations = array_diff( $wordpress_locations, $directory_exclusions );
return $wordpress_locations; } // End get_wordpress_locations().
/* periodic_cleanup() * * Periodic housekeeping cleanup function to clean up after BackupBuddy. Clean up orphaned files, data structure, * old log files, etc. Also verifies anti-directory browsing files exist in expected locations and any potential * problems are handled. * * @param int $backup_age_limit Maximum age (in seconds) to allow logs or other transient files/structures to exist after no longer needed. Default: 172800 (48 hours). * @param bool $die_on_fail Whether or not to die fatally if something goes wrong (such as unable to make anti-directory browsing files). * */ public static function periodic_cleanup( $backup_age_limit = 172800, $die_on_fail = true ) {
include( '_periodicCleanup.php' );
} // End periodic_cleanup().
/* final_cleanup() * * Final cleanup scheduled by each backup for cleaning up in the future. Helps catch failed backups. * * @param string $serial Unique backup serial which we will be cleaning up for. * @return null * */ public static function final_cleanup( $serial ) {
if ( !isset( pb_backupbuddy::$options ) ) { pb_backupbuddy::load(); } pb_backupbuddy::status( 'details', 'cron_final_cleanup started' );
require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' ); pb_backupbuddy::status( 'details', 'Fileoptions instance #31.' ); $backup_options = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/' . $serial . '.txt', $read_only = true ); if ( true !== ( $result = $backup_options->is_ok() ) ) { pb_backupbuddy::status( 'error', 'Unable to open fileoptions file.' ); }
// Delete temporary data directory. if ( isset( $backup_options->options['temp_directory'] ) && file_exists( $backup_options->options['temp_directory'] ) ) { pb_backupbuddy::$filesystem->unlink_recursive( $backup_options->options['temp_directory'] ); }
// Delete temporary zip directory. if ( isset( $backup_options->options['temporary_zip_directory'] ) && file_exists( $backup_options->options['temporary_zip_directory'] ) ) { pb_backupbuddy::$filesystem->unlink_recursive( $backup_options->options['temporary_zip_directory'] ); }
// Delete status log text file. if ( file_exists( backupbuddy_core::getBackupDirectory() . 'temp_status_' . $serial . '.txt' ) ) { unlink( backupbuddy_core::getBackupDirectory() . 'temp_status_' . $serial. '.txt' ); }
} // End final_cleanup().
/* trim_remote_send_stats() * * Handles trimming the number of remote sends to the most recent ones. * Recent transfer logs are kept for TRIPLE the max age as they are important for troubleshooting. * * @return null */ public static function trim_remote_send_stats() {
$limit = (int)pb_backupbuddy::$options['max_send_stats_count']; // Maximum number of remote sends to keep track of. $max_age = (int)pb_backupbuddy::$options['max_send_stats_days'] * 60 * 60 * 24;
$send_fileoptions = pb_backupbuddy::$filesystem->glob_by_date( backupbuddy_core::getLogDirectory() . 'fileoptions/send-*.txt' ); if ( ! is_array( $send_fileoptions ) ) { $send_fileoptions = array(); } // Return if limit not yet met. if ( count( $send_fileoptions ) <= $limit ) { return; }
$i = 0; foreach( $send_fileoptions as $send_fileoption ) { $i++; if ( $i > $limit ) { $modified = filemtime( $send_fileoption ); if ( ( time() - $modified ) > $max_age ) { if ( false === @unlink( $send_fileoption ) ) { pb_backupbuddy::status( 'error', 'Unable to delete old remote send log file `' . $send_fileoption . '`. You may manually delete it. Check directory permissions for future cleanup.' ); } } } }
return;
} // End trim_remote_send_stats().
/* get_site_size() * * Returns an array with the site size and the site size sans exclusions. Saves updates stats in options. * * @return array Index 0: site size; Index 1: site size sans excluded files/dirs.; Index 2: Total number of objects (files+folders); Index 3: Total objects sans excluded files/folders. */ public static function get_site_size() { $exclusions = backupbuddy_core::get_directory_exclusions( pb_backupbuddy::$options['profiles'][0] ); $dir_array = array(); $result = pb_backupbuddy::$filesystem->dir_size_map( ABSPATH, ABSPATH, $exclusions, $dir_array ); unset( $dir_array ); // Free this large chunk of memory.
$total_size = pb_backupbuddy::$options['stats']['site_size'] = $result[0]; $total_size_excluded = pb_backupbuddy::$options['stats']['site_size_excluded'] = $result[1]; $total_objects = pb_backupbuddy::$options['stats']['site_objects'] = $result[2]; $total_objects_excluded = pb_backupbuddy::$options['stats']['site_objects_excluded'] = $result[3]; pb_backupbuddy::$options['stats']['site_size_updated'] = time(); pb_backupbuddy::save();
return array( $total_size, $total_size_excluded, $total_objects, $total_objects_excluded ); } // End get_site_size().
/* get_database_size() * * Return array of database size, database sans exclusions. * * @return array Index 0: db size, Index 1: db size sans exclusions. */ public static function get_database_size( $profile_id = 0 ) { global $wpdb; $prefix = $wpdb->prefix; $prefix_length = strlen( $wpdb->prefix );
$additional_includes = explode( "\n", pb_backupbuddy::$options['profiles'][$profile_id]['mysqldump_additional_includes'] ); array_walk( $additional_includes, create_function('&$val', '$val = trim($val);')); $additional_excludes = explode( "\n", pb_backupbuddy::$options['profiles'][$profile_id]['mysqldump_additional_excludes'] ); array_walk( $additional_excludes, create_function('&$val', '$val = trim($val);'));
$total_size = 0; $total_size_with_exclusions = 0; $rows = $wpdb->get_results( "SHOW TABLE STATUS", ARRAY_A ); foreach( $rows as $row ) { $excluded = true; // Default.
// TABLE STATUS. $rowsb = $wpdb->get_results( "CHECK TABLE `{$row['Name']}`", ARRAY_A ); foreach( $rowsb as $rowb ) { if ( $rowb['Msg_type'] == 'status' ) { $status = $rowb['Msg_text']; } } unset( $rowsb );
// TABLE SIZE. $size = ( $row['Data_length'] + $row['Index_length'] ); $total_size += $size;
// HANDLE EXCLUSIONS. if ( pb_backupbuddy::$options['profiles'][$profile_id]['backup_nonwp_tables'] == 0 ) { // Only matching prefix. if ( ( substr( $row['Name'], 0, $prefix_length ) == $prefix ) OR ( in_array( $row['Name'], $additional_includes ) ) ) { if ( !in_array( $row['Name'], $additional_excludes ) ) { $total_size_with_exclusions += $size; $excluded = false; } } } else { // All tables. if ( !in_array( $row['Name'], $additional_excludes ) ) { $total_size_with_exclusions += $size; $excluded = false; } }
}
pb_backupbuddy::$options['stats']['db_size'] = $total_size; pb_backupbuddy::$options['stats']['db_size_excluded'] = $total_size_with_exclusions; pb_backupbuddy::$options['stats']['db_size_updated'] = time(); pb_backupbuddy::save();
unset( $rows );
return array( $total_size, $total_size_with_exclusions ); } // End get_database_size().
/* kick_db() * * Attempt to verify the database server is still alive and functioning. If not, try to re-establish connection. * */ public static function kick_db() {
$kick_db = true; // Change true to false for debugging purposes to disable kicker.
// Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh. // This is not essential so use include and not require (suppress any warning) if ( $kick_db === true ) { @include_once( pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php' ); if ( class_exists( 'pluginbuddy_wpdbutils' ) ) { // This is the database object we want to use global $wpdb;
// Get our helper object and let it use us to output status messages $dbhelper = new pluginbuddy_wpdbutils( $wpdb );
// If we cannot kick the database into life then signal the error and return false which will stop the backup // Otherwise all is ok and we can just fall through and let the function return true if ( !$dbhelper->kick() ) { pb_backupbuddy::status( 'error', __('Database Server has gone away, unable to update remote destination transfer status. This is most often caused by mysql running out of memory or timing out far too early. Please contact your host.', 'it-l10n-backupbuddy' ) ); } } else { // Utils not available so cannot verify database connection status - just notify pb_backupbuddy::status( 'details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy' ) ); } }
} // End kick_db().
/* verify_directories() * * Verify existance and security of key directories. Result available via global $pb_backupbuddy_directory_verification with return value. * * @return bool true on success creating / verifying, else false. * */ public static function verify_directories( $skipTempGeneration = false ) { $success = true;
// Update backup directory if unable to write to the defined one. if ( ! @is_writable( backupbuddy_core::getBackupDirectory() ) ) { pb_backupbuddy::status( 'details', 'Backup directory invalid. Updating from `' . backupbuddy_core::getBackupDirectory() . '` to default.' ); pb_backupbuddy::$options['backup_directory'] = ''; // Reset to default (blank). pb_backupbuddy::save(); } $response = pb_backupbuddy::anti_directory_browsing( backupbuddy_core::getBackupDirectory(), $die = false ); if ( false === $response ) { $success = false; }
// Update log directory if unable to write to the defined one. if ( ! @is_writable( backupbuddy_core::getLogDirectory() ) ) { pb_backupbuddy::status( 'details', 'Log directory invalid. Updating from `' . backupbuddy_core::getLogDirectory() . '` to default.' ); pb_backupbuddy::$options['log_directory'] = ''; // Reset to default (blank). pb_backupbuddy::save(); } pb_backupbuddy::anti_directory_browsing( backupbuddy_core::getLogDirectory(), $die = false ); if ( false === $response ) { $success = false; }
// Update temp directory if unable to write to the defined one. if ( true !== $skipTempGeneration ) { if ( ! @is_writable( backupbuddy_core::getTempDirectory() ) ) { pb_backupbuddy::status( 'details', 'Temporary directory invalid. Updating from `' . backupbuddy_core::getTempDirectory() . '` to default.' ); pb_backupbuddy::$options['temp_directory'] = ''; pb_backupbuddy::save(); } pb_backupbuddy::anti_directory_browsing( backupbuddy_core::getTempDirectory(), $die = false ); if ( false === $response ) { $success = false; } }
global $pb_backupbuddy_directory_verification; $pb_backupbuddy_directory_verification = $success; return $success;
} // End verify_directories().
/* schedule_single_event() * * API to wp_schedule_single_event() that also verifies that the schedule actually got created in WordPRess. * Sometimes the database rejects this update so we need to do actual verification. * * @return boolean True on verified schedule success, else false. */ public static function schedule_single_event( $time, $tag, $args ) { $schedule_result = wp_schedule_single_event( $time, $tag, $args ); // Schedule. $next_scheduled = wp_next_scheduled( $tag, $args ); // Retrieve schedule to verify it stuck. if ( FALSE === $schedule_result ) { pb_backupbuddy::status( 'error', 'Unable to create schedule as wp_schedule_single_event() returned false. A plugin may have prevented it.' ); return false; } if ( FALSE === $next_scheduled ) { pb_backupbuddy::status( 'error', 'WordPress reported success scheduling BUT wp_next_scheduled() could NOT confirm schedule existance. The database may have rejected the update.' ); return false; }
return true; } // End schedule_single_event().
/* schedule_event() * * API to wp_schedule_event() that also verifies that the schedule actually got created in WordPRess. * Sometimes the database rejects this update so we need to do actual verification. * * @return boolean True on verified schedule success, else false. */ public static function schedule_event( $time, $period, $tag, $args ) { $schedule_result = wp_schedule_event( $time, $period, $tag, $args ); $next_scheduled = wp_next_scheduled( $tag, $args ); if ( FALSE === $schedule_result ) { pb_backupbuddy::status( 'error', 'Unable to create schedule as wp_schedule_event() returned false. A plugin may have prevented it.' ); return false; } if ( FALSE === $next_scheduled ) { pb_backupbuddy::status( 'error', 'WordPress reported success scheduling BUT wp_next_scheduled() could NOT confirm schedule existance. The database may have rejected the update.' ); return false; }
return true; } // End schedule_event().
/* unschedule_event() * * API to wp_unschedule_event() that also verifies that the schedule actually got removed WordPRess. * Sometimes the database rejects this update so we need to do actual verification. * * @return boolean True on verified schedule deletion success, else false. */ public static function unschedule_event( $time, $tag, $args ) { $unschedule_result = wp_unschedule_event( $time, $tag, $args ); $next_scheduled = wp_next_scheduled( $tag, $args ); if ( FALSE === $unschedule_result ) { pb_backupbuddy::status( 'error', 'Unable to remove schedule as wp_unschedule_event() returned false. A plugin may have prevented it.' ); return false; } if ( FALSE !== $next_scheduled ) { pb_backupbuddy::status( 'error', 'WordPress reported success unscheduling BUT wp_next_scheduled() confirmed schedule existance. The database may have rejected the removal.' ); return false; }
return true; } // End unschedule_event().
/* normalize_comment_data() * * Handle normalizing zip comment data, defaults, etc. * * @param array $comment Array of meta data to normalize & apply defaults to. * @return array Normalized array. */ public static function normalize_comment_data( $comment ) {
$defaults = array( 'serial' => '', 'siteurl' => '', 'type' => '', 'profile' => '', 'created' => '', 'db_prefix' => '', 'bb_version' => '', 'wp_version' => '', 'posts' => '', 'pages' => '', 'comments' => '', 'users' => '', 'dat_path' => '', 'note' => '', );
if ( ! is_array( $comment ) ) { // Plain text; place in note field. if ( is_string( $comment ) ) { $defaults['note'] = $comment; } return $defaults; } else { // Array. Merge defaults and return. return array_merge( $defaults, $comment ); }
} // End normalize_comment_data(). /* cleanTempDir() * * Cleans out any old temp files. Called by periodic cleanup function and post_backup in backup.php. * */ public static function cleanTempDir( $backup_age_limit = 172800 ) { // Remove any old temporary directories in wp-content/uploads/backupbuddy_temp/. Logs any directories it cannot delete. pb_backupbuddy::status( 'details', 'Cleaning up any old temporary zip directories in: wp-content/uploads/backupbuddy_temp/. If no recent backups then the temp directory will also be purged.' ); $recentBackupFound = false; $temp_directory = backupbuddy_core::getTempDirectory(); $files = glob( $temp_directory . '*' ); if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match. foreach( $files as $file ) { if ( ( strpos( $file, 'index.' ) !== false ) || ( strpos( $file, '.htaccess' ) !== false ) ) { // Index file or htaccess dont get deleted so go to next file. continue; } $file_stats = stat( $file ); if ( ( 0 == $backup_age_limit ) || ( ( time() - $file_stats['mtime'] ) > $backup_age_limit ) ) { // If older than 12 hours, delete the log. if ( @pb_backupbuddy::$filesystem->unlink_recursive( $file ) === false ) { pb_backupbuddy::status( 'error', 'Unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it or check permissions.' ); } } else { // Not very old. $recentBackupFound = true; } } if ( false === $recentBackupFound ) { pb_backupbuddy::$filesystem->unlink_recursive( $temp_directory ); // Delete temp directory (as of BB v5.0). This is not critical but nice. The backup cleanup step should purge these so if all is going well this probably will not find anything. } } unset( $recentBackupFound ); } // End cleanTempDir(). /* pretty_meta_info() * * Translates meta information field names and values into nice readable forms. * * @param string $comment_line_name Meta field name. * @param string $comment_line_value Value of meta item. * @return array|false Array with two entries: the updates comment line name and updated comment line value. false if empty. * */ public static function pretty_meta_info( $comment_line_name, $comment_line_value ) {
if ( $comment_line_name == 'serial' ) { $comment_line_name = 'Unique serial identifier'; } elseif ( $comment_line_name == 'siteurl' ) { $comment_line_name = 'Site URL'; } elseif ( $comment_line_name == 'type' ) { $comment_line_name = 'Backup Type'; if ( $comment_line_value == 'db' ) { $comment_line_value = 'Database'; } elseif ( $comment_line_value == 'full' ) { $comment_line_value = 'Full'; } elseif ( $comment_line_value == 'export' ) { $comment_line_value = 'Multisite Subsite Export'; } } elseif ( $comment_line_name == 'profile' ) { $comment_line_name = 'Backup Profile'; } elseif ( $comment_line_name == 'created' ) { $comment_line_name = 'Creation Date'; if ( $comment_line_value != '' ) { $comment_line_value = pb_backupbuddy::$format->date( pb_backupbuddy::$format->localize_time( $comment_line_value ) ); } } elseif ( $comment_line_name == 'bb_version' ) { $comment_line_name = 'BackupBuddy version at creation'; } elseif ( $comment_line_name == 'wp_version' ) { $comment_line_name = 'WordPress version at creation'; } elseif ( $comment_line_name == 'dat_path' ) { $comment_line_name = 'BackupBuddy data file (relative)'; } elseif ( $comment_line_name == 'posts' ) { $comment_line_name = 'Total Posts'; } elseif ( $comment_line_name == 'pages' ) { $comment_line_name = 'Total Pages'; } elseif ( $comment_line_name == 'comments' ) { $comment_line_name = 'Total Comments'; } elseif ( $comment_line_name == 'users' ) { $comment_line_name = 'Total Users'; } elseif ( $comment_line_name == 'note' ) { $comment_line_name = 'User-specified note'; if ( $comment_line_value != '' ) { $comment_line_value = '"' . htmlentities( $comment_line_value ) . '"'; } } else { $comment_line_name = $comment_line_name; }
if ( $comment_line_value != '' ) { return array( $comment_line_name, $comment_line_value ); } else { return array( $comment_line_name, '-Empty-' ); }
} // End pretty_meta_info().
/* alert_core_table_excludes() * * Outputs an alert warning if a core db table is excluded. * * @param array $excludes Array of tables excluded from the backup. * @return array Array of message warnings about potential issues found with these exclusions, if any. Index = unique identifer, Value = message. * */ public static function alert_core_table_excludes( $excludes ) { global $wpdb; $prefix = $wpdb->prefix;
// If these tables are found excluded then warn that may be a bad idea. $warn_tables = array( $prefix . 'comments', $prefix . 'posts', $prefix . 'users', $prefix . 'commentmeta', $prefix . 'postmeta', $prefix . 'term_relationships', $prefix . 'options', $prefix . 'term_taxonomy', $prefix . 'links', $prefix . 'terms', );
$return_array = array(); foreach( $warn_tables as $warn_table ) { if ( in_array( $warn_table, $excludes ) ) { $return_array['excluding_coretable-' . md5( $warn_table )] = 'Warning: You are excluding one or more core WordPress tables `' . $warn_table . '` which may result in an incomplete backup. Remove exclusions or backup with another profile or method.'; } }
return $return_array; } // End alert_core_tables_excludes().
/* alert_core_file_excludes() * * Outputs an alert warning if a core db table is excluded. * * @param array $excludes Array of paths excluded from the backup. * @return array Array of message warnings about potential issues found with these exclusions, if any. Index = unique identifer, Value = message. * */ public static function alert_core_file_excludes( $excludes ) {
// If these paths are found excluded then warn that may be a bad idea. $warn_dirs = array( // No trailing slash. '/wp-content', '/wp-content/uploads', '/wp-content/uploads/backupbuddy_temp', '/' . ltrim( str_replace( ABSPATH, '', backupbuddy_core::getBackupDirectory() ), '\\/' ), );
foreach( $excludes as &$exclude ) { // Strip trailing slash(es). $exclude = rtrim( $exclude, '\\/' ); }
$return_array = array(); foreach( $warn_dirs as $warn_dir ) { if ( in_array( $warn_dir, $excludes ) ) { $return_array['excluding_corefile-' . md5( $warn_dir )] = 'Warning: You are excluding one or more WordPress core or BackupBuddy directories `' . $warn_dir . '` which may result in an incomplete or malfunctioning backup. Remove exclusions or backup with another profile or method to avoid problems.'; } }
return $return_array; } // End alert_core_file_excludes().
/* getZipMeta() * * Output meta info in a table. * * @param string $file Backup file to get comment meta data from. * @return array|false Array of meta data or false on failure to retrieve. * */ public static function getZipMeta( $file ) { if ( !isset( pb_backupbuddy::$classes['zipbuddy'] ) ) { require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' ); pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy( backupbuddy_core::getBackupDirectory() ); } $comment_meta = array(); if ( isset( $file ) ) { $comment = pb_backupbuddy::$classes['zipbuddy']->get_comment( $file ); $comment = backupbuddy_core::normalize_comment_data( $comment );
$comment_meta = array(); foreach( $comment as $comment_line_name => $comment_line_value ) { // Loop through all meta fields in the comment array to display.
if ( false !== ( $response = backupbuddy_core::pretty_meta_info( $comment_line_name, $comment_line_value ) ) ) { $response[0] = '<span title="' . $comment_line_name . '">' . $response[0] . '</span>'; $comment_meta[$comment_line_name] = $response; }
} }
if ( count( $comment_meta ) > 0 ) { return $comment_meta; } else { return false; } } // End getZipMeta().
/* get_dat_file_array() * * Get the DAT file contents as an array. * * @param string $dat_file Full path to DAT file to decode and parse. * @return array|false Array of DAT content. Bool false when unable to read. * */ public static function get_dat_file_array( $dat_file ) { pb_backupbuddy::status( 'details', 'Loading backup dat file.' );
if ( file_exists( $dat_file ) ) { $backupdata = file_get_contents( $dat_file ); } else { // Missing. pb_backupbuddy::status( 'error', 'Error #9003: BackupBuddy data file (backupbuddy_dat.php) missing or unreadable. There may be a problem with the backup file, the files could not be extracted (you may manually extract the zip file in this directory to manually do this portion of restore), or the files were deleted before this portion of the restore was reached. Start the import process over or try manually extracting (unzipping) the files then starting over. Restore will not continue to protect integrity of any existing data.' ); //die( ' Halted.' ); return false; }
// Unserialize data; If it fails it then decodes the obscufated data then unserializes it. (new dat file method starting at 2.0). if ( !is_serialized( $backupdata ) || ( false === ( $return = unserialize( $backupdata ) ) ) ) { // Skip first line. $second_line_pos = strpos( $backupdata, "\n" ) + 1; $backupdata = substr( $backupdata, $second_line_pos );
// Decode back into an array. $return = unserialize( base64_decode( $backupdata ) ); }
if ( ! is_array( $return ) ) { // Invalid DAT content. pb_backupbuddy::status( 'error', 'Error #545545. Unable to read/decode DAT file.' ); return false; }
pb_backupbuddy::status( 'details', 'Successfully loaded backup dat file `' . $dat_file . '`.' ); $return_censored = $return; $return_censored['db_password'] = '*HIDDEN*'; $return_censored = print_r( $return_censored, true ); $return_censored = str_replace( array( "\n", "\r" ), '; ', $return_censored ); pb_backupbuddy::status( 'details', 'DAT contents: ' . $return_censored ); return $return; } // End get_dat_file_array().
/* determineLatestVersion() * * Latest version info. Array of latest major,minor. False on fail to get. * */ public static function determineLatestVersion() { $latest_backupbuddy_version_cache_minutes = 60*12; // Define how many minutes to cache the latest backupbuddy version number.
function pb_backupbuddy_split2( $string,$needle,$nth ) { $max = strlen($string); $n = 0; for($i=0;$i<$max;$i++){ if ($string[$i]==$needle){ $n++; if($n>=$nth){ break; } } } $arr[] = substr($string,0,$i); $arr[] = substr($string,$i+1,$max); return $arr; } $latest_backupbuddy_version = get_transient( 'pb_backupbuddy_latest_version' ); if ( ( false === $latest_backupbuddy_version ) || ( ! is_array( $latest_backupbuddy_version ) ) ) { $response = wp_remote_get( 'http://api.ithemes.com/product/version?apikey=ixho7dk0p244n0ob&package=backupbuddy&channel=stable', array( 'method' => 'GET', 'timeout' => 7, 'redirection' => 3, 'httpversion' => '1.0', //'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array() ) ); if( is_wp_error( $response ) ) { $latest_backupbuddy_version = array( 0, 0 ); // Set to 0 for transient to prevent hitting server again for a bit since something went wrong. } else { $minorVersion = $response['body']; $majorVersion = pb_backupbuddy_split2( $minorVersion, '.', 3 ); $majorVersion = $majorVersion[0]; $latest_backupbuddy_version = array( $minorVersion, $majorVersion ); } set_transient( 'pb_backupbuddy_latest_version', $latest_backupbuddy_version, 60* $latest_backupbuddy_version_cache_minutes ); } // end not cached.
if ( ( 0 == $latest_backupbuddy_version[0] ) && ( 0 == $latest_backupbuddy_version[1] ) ) { // Server not responding. return false; }
return $latest_backupbuddy_version;
} // End determineLatestVersion().
/* detectMaxExecutionTime() * * Attempt to detect the max execution time allowed by PHP. Defaults to 30 if unable to detect or a suspicious value is detected. * IMPORTANT: This does NOT take into account user-specified override via settings page. For that, use adjustedMaxExecutionTime(). */ public static function detectMaxExecutionTime() { $detected_max_execution_time = str_ireplace( 's', '', ini_get( 'max_execution_time' ) ); if ( is_numeric( $detected_max_execution_time ) ) { $detected_max_execution_time = $detected_max_execution_time; } else { $detected_max_execution_time = 30; } if ( $detected_max_execution_time == '0' ) { $detected_max_execution_time = 30; } return $detected_max_execution_time; } // End detectMaxExecutionTime(). // Same as detectedMaxExecutionTime EXCEPT takes into account user overrided value in settings (if any). public static function adjustedMaxExecutionTime() { $detected = self::detectMaxExecutionTime(); if ( ( '' != pb_backupbuddy::$options['max_execution_time'] ) && ( is_numeric( pb_backupbuddy::$options['max_execution_time'] ) ) ) { // If set and a number, use user-specified runtime. return pb_backupbuddy::$options['max_execution_time']; } else { // Nothing user-specified so user detected value. return $detected; } } // End adjustedMaxExecutionTime(). /* dbEscape() * * Escape SQL using either mysql or mysqli based on whichever WordPress is using. * WP 3.9 introducing mysqli support. */ public static function dbEscape( $sql ) { global $wpdb; if ( isset( $wpdb->use_mysqli ) && ( true === $wpdb->use_mysqli ) ) { // Possible post WP 3.9 return mysqli_real_escape_string( $wpdb->dbh, $sql ); } else { return mysql_real_escape_string( $sql ); } } // End dbEscape(). } // End class backupbuddy_core.
|