WordPress Backup and Migrate Plugin – Backup Guard - Version 1.6.0

Version Description

  • Bug fixed related to security issues
Download this release

Release Info

Developer BackupGuard
Plugin Icon 128x128 WordPress Backup and Migrate Plugin – Backup Guard
Version 1.6.0
Comparing to
See all releases

Code changes from version 1.5.8 to 1.6.0

BackupGuard.php CHANGED
@@ -1,1081 +1,1081 @@
1
- <?php
2
-
3
- // hook to wordpres widget
4
- function backup_guard_register_widget()
5
- {
6
- if (!class_exists('SGWordPressWidget')) {
7
- @include_once(SG_WIDGET_PATH.'SGWordPressWidget.php');
8
- }
9
-
10
- register_widget('SGWordPressWidget');
11
- }
12
- add_action('widgets_init', 'backup_guard_register_widget');
13
-
14
- //The code that runs during plugin activation.
15
- function activate_backup_guard()
16
- {
17
- //check if database should be updated
18
- if (backupGuardShouldUpdate()) {
19
- SGBoot::install();
20
- SGBoot::didInstallForFirstTime();
21
- }
22
- }
23
-
24
- // The code that runs during plugin deactivation.
25
- function uninstall_backup_guard()
26
- {
27
- SGBoot::uninstall();
28
- }
29
-
30
- function deactivate_backup_guard()
31
- {
32
- $pluginCapabilities = backupGuardGetCapabilities();
33
- if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
34
- require_once(SG_LIB_PATH.'SGAuthClient.php');
35
- $res = SGAuthClient::getInstance()->logout();
36
- SGConfig::set('SG_LICENSE_CHECK_TS', 0, true);
37
- SGConfig::set('SG_LOGGED_USER', '', true);
38
- }
39
- }
40
-
41
- function backupGuardMaybeShortenEddFilename($return, $package)
42
- {
43
- if (strpos($package, 'backup-guard') !== false) {
44
- add_filter('wp_unique_filename', 'backupGuardShortenEddFilename', 10, 2);
45
- }
46
- return $return;
47
- }
48
-
49
- function backupGuardShortenEddFilename($filename, $ext)
50
- {
51
- $filename = substr($filename, 0, 20).$ext;
52
- remove_filter('wp_unique_filename', 'backupGuardShortenEddFilename', 10);
53
- return $filename;
54
- }
55
-
56
- add_filter('upgrader_pre_download', 'backupGuardMaybeShortenEddFilename', 10, 4);
57
-
58
- register_activation_hook(SG_BACKUP_GUARD_MAIN_FILE, 'activate_backup_guard');
59
- register_uninstall_hook(SG_BACKUP_GUARD_MAIN_FILE, 'uninstall_backup_guard');
60
- register_deactivation_hook(SG_BACKUP_GUARD_MAIN_FILE, 'deactivate_backup_guard');
61
- //add_action('admin_footer', 'before_deactivate_backup_guard');
62
-
63
- function before_deactivate_backup_guard()
64
- {
65
- wp_enqueue_style('before-deactivate-backup-guard-css', plugin_dir_url(__FILE__).'public/css/deactivationSurvey.css');
66
- wp_enqueue_script('before-deactivate-backup-guard-js', plugin_dir_url(__FILE__).'public/js/deactivationSurvey.js', array('jquery'));
67
-
68
- wp_localize_script('before-deactivate-backup-guard-js', 'BG_BACKUP_STRINGS_DEACTIVATE', array(
69
- 'nonce' => wp_create_nonce('backupGuardAjaxNonce'),
70
- 'areYouSure' => _backupGuardT('Are you sure?', true),
71
- 'invalidCloud' => _backupGuardT('Please select at least 1 cloud', true)
72
- ));
73
-
74
- require_once(plugin_dir_path(__FILE__).'public/include/uninstallSurveyPopup.php');
75
- }
76
-
77
- // Register Admin Menus for single and multisite
78
- if (is_multisite()) {
79
- add_action('network_admin_menu', 'backup_guard_admin_menu');
80
- }
81
- else {
82
- add_action('admin_menu', 'backup_guard_admin_menu');
83
- }
84
-
85
- function backup_guard_admin_menu()
86
- {
87
- $capability = 'manage_options';
88
- if (defined('SG_USER_MODE') && SG_USER_MODE) {
89
- $capability = 'read';
90
- }
91
-
92
- add_menu_page('Backups', 'BackupGuard', $capability, 'backup_guard_backups', 'includeAllPages', 'data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2MzAuMzQgNjYzLjAzIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkFydGJvYXJkIDI8L3RpdGxlPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTUzMC4xMSwxODUuNzljLTcxLjktOC44Mi0xMzcuNzMtNDAtMTkwLTg2LjU3djkyLjY1YTI4MC41OSwyODAuNTksMCwwLDAsMTE2LjUyLDUyYy05LjE0LDg5LjQzLTUyLDE2OS41NS0xMTYuNTIsMjI4Ljg3djkwLjRDNDU5Ljg0LDQ3Ny4xMyw1MzAuNiwzMzMuNDIsNTMwLjExLDE4NS43OVoiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xNzQuMjksMjQ0YTI4MC40NiwyODAuNDYsMCwwLDAsMTE1Ljc3LTUxLjExVjEwMGMtNTIuNDQsNDYuMjgtMTE3LjYyLDc3LTE4OS44Myw4NS4xNUM5OS41NCwzMzMsMTcwLjIyLDQ3Ni44MiwyOTAuMDYsNTYzVjQ3Mi4wOUMyMjYsNDEyLjg2LDE4My40MiwzMzMuMDYsMTc0LjI5LDI0NFoiLz48L3N2Zz4=', 74);
93
-
94
- add_submenu_page('backup_guard_backups', _backupGuardT('Backups', true), _backupGuardT('Backups', true), $capability, 'backup_guard_backups', 'includeAllPages');
95
- add_submenu_page('backup_guard_backups', _backupGuardT('Cloud', true), _backupGuardT('Cloud', true), $capability, 'backup_guard_cloud', 'includeAllPages');
96
- add_submenu_page('backup_guard_backups', _backupGuardT('Schedule', true), _backupGuardT('Schedule', true), $capability, 'backup_guard_schedule', 'includeAllPages');
97
-
98
- add_submenu_page('backup_guard_backups', _backupGuardT('Settings', true), _backupGuardT('Settings', true), $capability, 'backup_guard_settings', 'includeAllPages');
99
-
100
- add_submenu_page('backup_guard_backups', _backupGuardT('System Info.', true), _backupGuardT('System Info.', true), $capability, 'backup_guard_system_info', 'includeAllPages');
101
-
102
- add_submenu_page('backup_guard_backups', _backupGuardT('Services', true), _backupGuardT('Services', true), $capability, 'backup_guard_services', 'includeAllPages');
103
- add_submenu_page('backup_guard_backups', _backupGuardT('Video Tutorials', true), _backupGuardT('Video Tutorials', true), $capability, 'backup_guard_videoTutorials', 'includeAllPages');
104
- add_submenu_page('backup_guard_backups', _backupGuardT('Support', true), _backupGuardT('Support', true), $capability, 'backup_guard_support', 'includeAllPages');
105
-
106
- //Check if should show upgrade page
107
- if (SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE')) {
108
- add_submenu_page('backup_guard_backups', _backupGuardT('Why upgrade?', true), _backupGuardT('Why upgrade?', true), $capability, 'backup_guard_pro_features', 'includeAllPages');
109
- }
110
- }
111
-
112
- function getBackupPageContentClassName($pageName = '')
113
- {
114
- $hiddenClassName = 'sg-visibility-hidden';
115
- $page = $_GET['page'];
116
-
117
- if (strpos($page, $pageName)) {
118
- $hiddenClassName = '';
119
- }
120
-
121
- return $hiddenClassName;
122
- }
123
-
124
- function includeAllPages()
125
- {
126
- if (!backupGuardValidateLicense()) {
127
- return false;
128
- }
129
- backup_guard_backups_page();
130
- backup_guard_cloud_page();
131
- backup_guard_system_info_page();
132
- backup_guard_services_page();
133
- backup_guard_pro_features_page();
134
- backup_guard_support_page();
135
- backup_guard_schedule_page();
136
- backup_guard_settings_page();
137
-
138
- require_once(plugin_dir_path(__FILE__).'public/pagesContent.php');
139
-
140
- return true;
141
- }
142
-
143
- function backup_guard_system_info_page()
144
- {
145
- if (backupGuardValidateLicense()) {
146
- //require_once(plugin_dir_path(__FILE__).'public/systemInfo.php');
147
- }
148
- }
149
-
150
- function backup_guard_services_page()
151
- {
152
- if (backupGuardValidateLicense()) {
153
- //require_once(plugin_dir_path(__FILE__).'public/services.php');
154
- }
155
- }
156
-
157
- //Pro features page
158
- function backup_guard_pro_features_page()
159
- {
160
- // require_once(plugin_dir_path(__FILE__).'public/proFeatures.php');
161
- }
162
-
163
- function backup_guard_security_page()
164
- {
165
- require_once(plugin_dir_path(__FILE__).'public/security.php');
166
- }
167
-
168
- //Support page
169
- function backup_guard_support_page()
170
- {
171
- if (backupGuardValidateLicense()) {
172
- // require_once(plugin_dir_path(__FILE__).'public/support.php');
173
- }
174
- }
175
-
176
- //Backups Page
177
- function backup_guard_backups_page()
178
- {
179
- if (backupGuardValidateLicense()) {
180
- wp_enqueue_script('backup-guard-iframe-transport-js', plugin_dir_url(__FILE__).'public/js/jquery.iframe-transport.js', array('jquery'));
181
- wp_enqueue_script('backup-guard-fileupload-js', plugin_dir_url(__FILE__).'public/js/jquery.fileupload.js', array('jquery'));
182
- wp_enqueue_script('backup-guard-jstree-js', plugin_dir_url(__FILE__).'public/js/jstree.min.js', array('jquery'));
183
- wp_enqueue_script('backup-guard-jstree-checkbox-js', plugin_dir_url(__FILE__).'public/js/jstree.checkbox.js', array('jquery'));
184
- wp_enqueue_script('backup-guard-jstree-wholerow-js', plugin_dir_url(__FILE__).'public/js/jstree.wholerow.js', array('jquery'));
185
- wp_enqueue_script('backup-guard-jstree-types-js', plugin_dir_url(__FILE__).'public/js/jstree.types.js', array('jquery'));
186
- wp_enqueue_style('backup-guard-jstree-css', plugin_dir_url(__FILE__).'public/css/default/style.min.css');
187
- wp_enqueue_script('backup-guard-backups-js', plugin_dir_url(__FILE__).'public/js/sgbackup.js', array('jquery', 'jquery-effects-core', 'jquery-effects-transfer', 'jquery-ui-widget'));
188
-
189
- // Localize the script with new data
190
- wp_localize_script('backup-guard-backups-js', 'BG_BACKUP_STRINGS', array(
191
- 'confirm' => _backupGuardT('Are you sure you want to cancel import?', true),
192
- 'nonce' => wp_create_nonce('backupGuardAjaxNonce'),
193
- 'invalidBackupOption' => _backupGuardT('Please choose at least one option.', true),
194
- 'invalidDirectorySelected' => _backupGuardT('Please choose at least one directory.', true),
195
- 'invalidCloud' => _backupGuardT('Please choose at least one cloud.', true),
196
- 'backupInProgress' => _backupGuardT('Backing Up...', true),
197
- 'errorMessage' => _backupGuardT('Something went wrong. Please try again.', true),
198
- 'noBackupsAvailable' => _backupGuardT('No backups found.', true),
199
- 'invalidImportOption' => _backupGuardT('Please select one of the options.', true),
200
- 'invalidDownloadFile' => _backupGuardT('Please choose one of the files.', true),
201
- 'import' => _backupGuardT('Import', true),
202
- 'importInProgress' => _backupGuardT('Importing please wait...', true),
203
- 'fileUploadFailed' => _backupGuardT('File upload failed.', true)
204
- ));
205
-
206
- // require_once(plugin_dir_path( __FILE__ ).'public/backups.php');
207
- }
208
- }
209
-
210
- //Cloud Page
211
- function backup_guard_cloud_page()
212
- {
213
- if (backupGuardValidateLicense()) {
214
- wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
215
- wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), SG_BACKUP_GUARD_VERSION, true);
216
- wp_enqueue_script('backup-guard-jquery-validate-js', plugin_dir_url(__FILE__).'public/js/jquery.validate.min.js', array('jquery', 'backup-guard-switch-js'), SG_BACKUP_GUARD_VERSION, true);
217
- wp_enqueue_script('backup-guard-cloud-js', plugin_dir_url(__FILE__).'public/js/sgcloud.js', array('jquery', 'backup-guard-switch-js'), SG_BACKUP_GUARD_VERSION, true);
218
-
219
- // Localize the script with new data
220
- wp_localize_script('backup-guard-cloud-js', 'BG_CLOUD_STRINGS', array(
221
- 'invalidImportFile' => _backupGuardT('Please select a file.', true),
222
- 'invalidFileSize' => _backupGuardT('File is too large.', true),
223
- 'connectionInProgress' => _backupGuardT('Connecting...', true),
224
- 'invalidDestinationFolder' => _backupGuardT('Destination folder is required.', true),
225
- 'successMessage' => _backupGuardT('Successfully saved.', true)
226
- ));
227
-
228
- //require_once(plugin_dir_path(__FILE__).'public/cloud.php');
229
- }
230
- }
231
-
232
- //Schedule Page
233
- function backup_guard_schedule_page()
234
- {
235
- if (backupGuardValidateLicense()) {
236
- wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
237
- wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), '1.0.0', true);
238
- wp_enqueue_script('backup-guard-schedule-js', plugin_dir_url(__FILE__).'public/js/sgschedule.js', array('jquery'), '1.0.0', true);
239
-
240
- // Localize the script with new data
241
- wp_localize_script('backup-guard-schedule-js', 'BG_SCHEDULE_STRINGS', array(
242
- 'deletionError' => _backupGuardT('Unable to delete schedule', true),
243
- 'confirm' => _backupGuardT('Are you sure?', true),
244
- 'invalidBackupOption' => _backupGuardT('Please choose at least one option.', true),
245
- 'invalidDirectorySelected' => _backupGuardT('Please choose at least one directory.', true),
246
- 'invalidCloud' => _backupGuardT('Please choose at least one cloud.', true),
247
- 'savingInProgress' => _backupGuardT('Saving...', true),
248
- 'successMessage' => _backupGuardT('You have successfully activated schedule.', true),
249
- 'saveButtonText' => _backupGuardT('Save', true)
250
- ));
251
-
252
- // require_once(plugin_dir_path( __FILE__ ).'public/schedule.php');
253
- }
254
- }
255
-
256
- //Settings Page
257
- function backup_guard_settings_page()
258
- {
259
- if (backupGuardValidateLicense()) {
260
- wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
261
- wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), '1.0.0', true);
262
- wp_enqueue_script('backup-guard-settings-js', plugin_dir_url(__FILE__).'public/js/sgsettings.js', array('jquery'), '1.0.0', true );
263
-
264
- // Localize the script with new data
265
- wp_localize_script('backup-guard-settings-js', 'BG_SETTINGS_STRINGS', array(
266
- 'invalidEmailAddress' => _backupGuardT('Please enter valid email.', true),
267
- 'invalidFileName' => _backupGuardT('Please enter valid file name.', true),
268
- 'invalidRetentionNumber' => _backupGuardT('Please enter a valid retention number.', true),
269
- 'successMessage' => _backupGuardT('Successfully saved.', true),
270
- 'savingInProgress' => _backupGuardT('Saving...', true),
271
- 'retentionConfirmationFirstPart' => _backupGuardT('Are you sure you want to keep the latest', true),
272
- 'retentionConfirmationSecondPart' => _backupGuardT('backups? All older backups will be deleted.', true),
273
- 'saveButtonText' => _backupGuardT('Save', true)
274
- ));
275
-
276
- //require_once(plugin_dir_path(__FILE__).'public/settings.php');
277
- }
278
- }
279
-
280
- function backup_guard_login_page()
281
- {
282
- wp_enqueue_script('backup-guard-login-js', plugin_dir_url(__FILE__).'public/js/sglogin.js', array('jquery'), '1.0.0', true);
283
-
284
- require_once(plugin_dir_path(__FILE__).'public/login.php');
285
- }
286
-
287
- function backup_guard_link_license_page()
288
- {
289
- wp_enqueue_script('backup-guard-license-js', plugin_dir_url(__FILE__).'public/js/sglicense.js', array('jquery'), '1.0.0', true);
290
- // Localize the script with new data
291
- wp_localize_script('backup-guard-license-js', 'BG_LICENSE_STRINGS', array(
292
- 'invalidLicense' => _backupGuardT('Please choose a license first', true),
293
- 'availableLicenses' => _backupGuardT('There are no available licenses for using the selected product', true)
294
- ));
295
-
296
- require_once(plugin_dir_path(__FILE__).'public/link_license.php');
297
- }
298
-
299
- add_action('admin_enqueue_scripts', 'enqueue_backup_guard_scripts');
300
- function enqueue_backup_guard_scripts($hook)
301
- {
302
- wp_enqueue_script('backup-guard-discount-notice', plugin_dir_url(__FILE__).'public/js/sgNoticeDismiss.js', array('jquery'), '1.0', true);
303
-
304
- if (!strpos($hook,'backup_guard')) {
305
- if($hook == "index.php"){
306
- wp_enqueue_script('backup-guard-chart-manager', plugin_dir_url(__FILE__).'public/js/Chart.bundle.min.js');
307
- }
308
- return;
309
- }
310
-
311
- wp_enqueue_style('backup-guard-spinner', plugin_dir_url(__FILE__).'public/css/spinner.css');
312
- wp_enqueue_style('backup-guard-wordpress', plugin_dir_url(__FILE__).'public/css/bgstyle.wordpress.css');
313
- wp_enqueue_style('backup-guard-less', plugin_dir_url(__FILE__).'public/css/bgstyle.less.css');
314
- wp_enqueue_style('backup-guard-styles', plugin_dir_url(__FILE__).'public/css/styles.css');
315
-
316
- echo '<script type="text/javascript">sgBackup={};';
317
- $sgAjaxRequestFrequency = SGConfig::get('SG_AJAX_REQUEST_FREQUENCY');
318
- if (!$sgAjaxRequestFrequency) {
319
- $sgAjaxRequestFrequency = SG_AJAX_DEFAULT_REQUEST_FREQUENCY;
320
- }
321
- echo 'SG_AJAX_REQUEST_FREQUENCY = "'.$sgAjaxRequestFrequency.'";';
322
- echo 'function getAjaxUrl(url) {'.
323
- 'if (url==="cloudDropbox" || url==="cloudGdrive" || url==="cloudOneDrive") return "'.admin_url('admin-post.php?action=backup_guard_').'"+url+"&token='.wp_create_nonce('backupGuardAjaxNonce').'";'.
324
- 'return "'.admin_url('admin-ajax.php').'";}</script>';
325
-
326
- wp_enqueue_media();
327
- wp_enqueue_script('backup-guard-less-framework', plugin_dir_url(__FILE__).'public/js/less.min.js', array('jquery'), '1.0.0', true);
328
- wp_enqueue_script('backup-guard-bootstrap-framework', plugin_dir_url(__FILE__).'public/js/bootstrap.min.js', array('jquery'), '1.0.0', true);
329
- wp_enqueue_script('backup-guard-sgrequest-js', plugin_dir_url(__FILE__).'public/js/sgrequesthandler.js', array('jquery'), '1.0.0', true);
330
- wp_enqueue_script('backup-guard-sgwprequest-js', plugin_dir_url(__FILE__).'public/js/sgrequesthandler.wordpress.js', array('jquery'), '1.0.0', true);
331
-
332
- wp_enqueue_style('backup-guard-rateyo-css', plugin_dir_url(__FILE__).'public/css/jquery.rateyo.css');
333
- wp_enqueue_script('backup-guard-rateyo-js', plugin_dir_url(__FILE__).'public/js/jquery.rateyo.js');
334
-
335
- wp_enqueue_script('backup-guard-main-js', plugin_dir_url(__FILE__).'public/js/main.js', array('jquery'), '1.0.0', true);
336
- wp_enqueue_script('backup-popup.js', plugin_dir_url(__FILE__).'public/js/popup.js', array('jquery'), '1.0.0', true);
337
- wp_enqueue_style('popupTheme.css', plugin_dir_url(__FILE__).'public/css/popupTheme.css');
338
-
339
- // Localize the script with new data
340
- wp_localize_script('backup-guard-main-js', 'BG_MAIN_STRINGS', array(
341
- 'confirmCancel' => _backupGuardT('Are you sure you want to cancel?', true)
342
- ));
343
-
344
- wp_localize_script('backup-guard-main-js', 'BG_BACKUP_STRINGS', array(
345
- 'nonce' => wp_create_nonce('backupGuardAjaxNonce')
346
- ));
347
- }
348
-
349
- // adding actions to handle modal ajax requests
350
- add_action( 'wp_ajax_backup_guard_modalManualBackup', 'backup_guard_get_manual_modal');
351
- add_action( 'wp_ajax_backup_guard_modalManualRestore', 'backup_guard_get_manual_restore_modal');
352
- add_action( 'wp_ajax_backup_guard_modalImport', 'backup_guard_get_import_modal');
353
- add_action( 'wp_ajax_backup_guard_modalFtpSettings', 'backup_guard_get_ftp_modal');
354
- add_action( 'wp_ajax_backup_guard_modalAmazonSettings', 'backup_guard_get_amazon_modal');
355
- add_action( 'wp_ajax_backup_guard_modalPrivacy', 'backup_guard_get_privacy_modal');
356
- add_action( 'wp_ajax_backup_guard_modalTerms', 'backup_guard_get_terms_modal');
357
- add_action( 'wp_ajax_backup_guard_modalReview', 'backup_guard_get_review_modal');
358
- add_action( 'wp_ajax_backup_guard_getFileDownloadProgress', 'backup_guard_get_file_download_progress');
359
- add_action( 'wp_ajax_backup_guard_modalCreateSchedule', 'backup_guard_create_schedule');
360
- add_action( 'wp_ajax_backup_guard_getBackupContent', 'backup_guard_get_backup_content');
361
-
362
- add_action( 'wp_ajax_backup_guard_modalBackupGuardDetails', 'backup_guard_get_backup_guard_modal');
363
-
364
- function backup_guard_get_backup_guard_modal()
365
- {
366
- check_ajax_referer('backupGuardAjaxNonce', 'token');
367
- require_once(SG_PUBLIC_AJAX_PATH.'modalBackupGuardDetails.php');
368
- exit();
369
- }
370
-
371
- function backup_guard_get_file_download_progress()
372
- {
373
- check_ajax_referer('backupGuardAjaxNonce', 'token');
374
- require_once(SG_PUBLIC_AJAX_PATH.'getFileDownloadProgress.php');
375
- exit();
376
- }
377
-
378
- function backup_guard_create_schedule()
379
- {
380
- check_ajax_referer('backupGuardAjaxNonce', 'token');
381
- require_once(SG_PUBLIC_AJAX_PATH.'modalCreateSchedule.php');
382
- exit();
383
- }
384
-
385
- function backup_guard_get_manual_modal()
386
- {
387
- check_ajax_referer('backupGuardAjaxNonce', 'token');
388
- if (current_user_can( 'activate_plugins' ) || (defined('SG_USER_MODE') && SG_USER_MODE)) {
389
- require_once(SG_PUBLIC_AJAX_PATH.'modalManualBackup.php');
390
- }
391
- exit();
392
- }
393
-
394
- function backup_guard_get_manual_restore_modal()
395
- {
396
- check_ajax_referer('backupGuardAjaxNonce', 'token');
397
- require_once(SG_PUBLIC_AJAX_PATH.'modalManualRestore.php');
398
- exit();
399
- }
400
-
401
- function backup_guard_get_backup_content()
402
- {
403
- check_ajax_referer('backupGuardAjaxNonce', 'token');
404
- require_once (SG_PUBLIC_AJAX_PATH.'getBackupContent.php');
405
- exit();
406
- }
407
-
408
- function backup_guard_get_import_modal()
409
- {
410
- check_ajax_referer('backupGuardAjaxNonce', 'token');
411
- require_once(SG_PUBLIC_AJAX_PATH.'modalImport.php');
412
- exit();
413
- }
414
-
415
- function backup_guard_get_ftp_modal()
416
- {
417
- check_ajax_referer('backupGuardAjaxNonce', 'token');
418
- require_once(SG_PUBLIC_AJAX_PATH.'modalFtpSettings.php');
419
- exit();
420
- }
421
-
422
- function backup_guard_get_amazon_modal()
423
- {
424
- check_ajax_referer('backupGuardAjaxNonce', 'token');
425
- require_once(SG_PUBLIC_AJAX_PATH.'modalAmazonSettings.php');
426
- exit();
427
- }
428
-
429
- function backup_guard_get_privacy_modal()
430
- {
431
- require_once(SG_PUBLIC_AJAX_PATH.'modalPrivacy.php');
432
- }
433
-
434
- function backup_guard_get_terms_modal()
435
- {
436
- require_once(SG_PUBLIC_AJAX_PATH.'modalTerms.php');
437
- exit();
438
- }
439
-
440
- function backup_guard_get_review_modal()
441
- {
442
- check_ajax_referer('backupGuardAjaxNonce', 'token');
443
- require_once(SG_PUBLIC_AJAX_PATH.'modalReview.php');
444
- exit();
445
- }
446
-
447
- function backup_guard_register_ajax_callbacks()
448
- {
449
- if (is_super_admin() || (defined('SG_USER_MODE') && SG_USER_MODE)) {
450
- // adding actions to handle ajax and post requests
451
- add_action('wp_ajax_backup_guard_cancelBackup', 'backup_guard_cancel_backup');
452
- add_action('wp_ajax_backup_guard_checkBackupCreation', 'backup_guard_check_backup_creation');
453
- add_action('wp_ajax_backup_guard_checkRestoreCreation', 'backup_guard_check_restore_creation');
454
- add_action('wp_ajax_backup_guard_cloudDropbox', 'backup_guard_cloud_dropbox');
455
- add_action('wp_ajax_backup_guard_send_usage_status', 'backup_guard_send_usage_status');
456
-
457
- $pluginCapabilities = backupGuardGetCapabilities();
458
- if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
459
- require_once dirname(__FILE__).'/BackupGuardPro.php';
460
- }
461
- add_action('wp_ajax_backup_guard_curlChecker', 'backup_guard_curl_checker');
462
- add_action('wp_ajax_backup_guard_deleteBackup', 'backup_guard_delete_backup');
463
- add_action('wp_ajax_backup_guard_getAction', 'backup_guard_get_action');
464
- add_action('wp_ajax_backup_guard_getRunningActions', 'backup_guard_get_running_actions');
465
- add_action('wp_ajax_backup_guard_importBackup', 'backup_guard_get_import_backup');
466
- add_action('wp_ajax_backup_guard_resetStatus', 'backup_guard_reset_status');
467
- add_action('wp_ajax_backup_guard_restore', 'backup_guard_restore');
468
- add_action('wp_ajax_backup_guard_saveCloudFolder', 'backup_guard_save_cloud_folder');
469
- add_action('wp_ajax_backup_guard_schedule', 'backup_guard_schedule');
470
- add_action('wp_ajax_backup_guard_settings', 'backup_guard_settings');
471
- add_action('wp_ajax_backup_guard_setReviewPopupState', 'backup_guard_set_review_popup_state');
472
- add_action('wp_ajax_backup_guard_sendUsageStatistics', 'backup_guard_send_usage_statistics');
473
- add_action('wp_ajax_backup_guard_hideNotice', 'backup_guard_hide_notice');
474
- add_action('wp_ajax_backup_guard_downloadFromCloud', 'backup_guard_download_from_cloud');
475
- add_action('wp_ajax_backup_guard_listStorage', 'backup_guard_list_storage');
476
- add_action('wp_ajax_backup_guard_cancelDownload', 'backup_guard_cancel_download');
477
- add_action('wp_ajax_backup_guard_awake', 'backup_guard_awake');
478
- add_action('wp_ajax_backup_guard_manualBackup', 'backup_guard_manual_backup');
479
- add_action('admin_post_backup_guard_downloadBackup', 'backup_guard_download_backup');
480
- add_action('wp_ajax_backup_guard_login', 'backup_guard_login');
481
- add_action('wp_ajax_backup_guard_logout', 'backup_guard_logout');
482
- add_action('wp_ajax_backup_guard_link_license', 'backup_guard_link_license');
483
- add_action('wp_ajax_backup_guard_importKeyFile', 'backup_guard_import_key_file');
484
- add_action('wp_ajax_backup_guard_isFeatureAvailable', 'backup_guard_is_feature_available');
485
- add_action('wp_ajax_backup_guard_dismiss_discount_notice', 'backup_guard_dismiss_discount_notice');
486
- add_action('wp_ajax_backup_guard_checkFreeMigration', 'backup_guard_check_free_migration');
487
- add_action('wp_ajax_backup_guard_checkPHPVersionCompatibility', 'backup_guard_check_php_version_compatibility');
488
- add_action('wp_ajax_backup_guard_setUserInfoVerificationPopupState', 'backup_guard_set_user_info_verification_popup_state');
489
- add_action('wp_ajax_backup_guard_storeSubscriberInfo', 'backup_guard_store_subscriber_info');
490
- add_action('wp_ajax_backup_guard_storeSurveyResult', 'backup_guard_store_survey_result');
491
- add_action('wp_ajax_backup_guard_reviewDontShow', 'backup_guard_review_dont_show');
492
- add_action('wp_ajax_backup_guard_review_later', 'backup_guard_review_later');
493
- add_action('wp_ajax_backup_guard_closeFreeBanner', 'wp_ajax_backup_guard_close_free_banner');
494
- // related to cloud
495
- add_action('wp_ajax_backup_guard_isBgUserExists', 'backup_guard_is_bg_user_exists');
496
- add_action('wp_ajax_backup_guard_createCloudUser', 'backup_guard_create_cloud_user');
497
- add_action('wp_ajax_backup_guard_bgAutoLogin', 'backup_guard_bg_auto_login');
498
- add_action('wp_ajax_backup_guard_bgLogin', 'backup_guard_bg_login');
499
- add_action('wp_ajax_backup_guard_chooseProfile', 'backup_guard_choose_profile');
500
- }
501
- }
502
-
503
- function wp_ajax_backup_guard_close_free_banner()
504
- {
505
- check_ajax_referer('backupGuardAjaxNonce', 'token');
506
- SGConfig::set('SG_CLOSE_FREE_BANNER', 1);
507
- wp_die();
508
- }
509
-
510
- function backup_guard_review_dont_show()
511
- {
512
- check_ajax_referer('backupGuardAjaxNonce', 'token');
513
- SGConfig::set('closeReviewBanner', 1);
514
- wp_die();
515
- }
516
-
517
- function backup_guard_review_later()
518
- {
519
- check_ajax_referer('backupGuardAjaxNonce', 'token');
520
- require_once(SG_PUBLIC_AJAX_PATH.'reviewBannerActions.php');
521
- wp_die();
522
- }
523
-
524
- function backup_guard_choose_profile()
525
- {
526
- check_ajax_referer('backupGuardAjaxNonce', 'token');
527
- require_once(SG_PUBLIC_AJAX_PATH.'chooseProfile.php');
528
- }
529
-
530
- function backup_guard_bg_login()
531
- {
532
- check_ajax_referer('backupGuardAjaxNonce', 'token');
533
- require_once(SG_PUBLIC_AJAX_PATH.'bgLogin.php');
534
- }
535
-
536
- function backup_guard_bg_auto_login()
537
- {
538
- check_ajax_referer('backupGuardAjaxNonce', 'token');
539
- require_once(SG_PUBLIC_AJAX_PATH.'bgAutoLogin.php');
540
- }
541
-
542
- function backup_guard_create_cloud_user()
543
- {
544
- check_ajax_referer('backupGuardAjaxNonce', 'token');
545
- require_once(SG_PUBLIC_AJAX_PATH.'createCloudUser.php');
546
- }
547
-
548
- function backup_guard_is_bg_user_exists()
549
- {
550
- check_ajax_referer('backupGuardAjaxNonce', 'token');
551
- require_once(SG_PUBLIC_AJAX_PATH.'isBgUserExists.php');
552
- }
553
-
554
- function backup_guard_store_survey_result()
555
- {
556
- check_ajax_referer('backupGuardAjaxNonce', 'token');
557
- require_once(SG_PUBLIC_AJAX_PATH.'storeSurveyResult.php');
558
- }
559
-
560
- function backup_guard_store_subscriber_info()
561
- {
562
- check_ajax_referer('backupGuardAjaxNonce', 'token');
563
- require_once(SG_PUBLIC_AJAX_PATH.'storeSubscriberInfo.php');
564
- }
565
-
566
- function backup_guard_set_user_info_verification_popup_state()
567
- {
568
- check_ajax_referer('backupGuardAjaxNonce', 'token');
569
- require_once(SG_PUBLIC_AJAX_PATH.'setUserInfoVerificationPopupState.php');
570
- }
571
-
572
- function backup_guard_dismiss_discount_notice()
573
- {
574
- check_ajax_referer('backupGuardAjaxNonce', 'token');
575
- require_once(SG_PUBLIC_AJAX_PATH.'dismissDiscountNotice.php');
576
- }
577
-
578
- function backup_guard_is_feature_available()
579
- {
580
- require_once(SG_PUBLIC_AJAX_PATH.'isFeatureAvailable.php');
581
- }
582
-
583
- function backup_guard_check_free_migration()
584
- {
585
- check_ajax_referer('backupGuardAjaxNonce', 'token');
586
- require_once(SG_PUBLIC_AJAX_PATH.'checkFreeMigration.php');
587
- die;
588
- }
589
-
590
- function backup_guard_check_php_version_compatibility()
591
- {
592
- check_ajax_referer('backupGuardAjaxNonce', 'token');
593
- require_once(SG_PUBLIC_AJAX_PATH.'checkPHPVersionCompatibility.php');
594
- }
595
-
596
- add_action('init', 'backup_guard_init');
597
- add_action('wp_ajax_nopriv_backup_guard_awake', 'backup_guard_awake_nopriv');
598
- add_action('admin_post_backup_guard_cloudDropbox', 'backup_guard_cloud_dropbox');
599
-
600
- function backup_guard_import_key_file()
601
- {
602
- check_ajax_referer('backupGuardAjaxNonce', 'token');
603
- require_once(SG_PUBLIC_AJAX_PATH.'importKeyFile.php');
604
- }
605
-
606
- function backup_guard_awake()
607
- {
608
- $method = SG_RELOAD_METHOD_AJAX;
609
- require_once(SG_PUBLIC_AJAX_PATH.'awake.php');
610
- }
611
-
612
- function backup_guard_awake_nopriv()
613
- {
614
- $token = @$_GET['token'];
615
- $method = @$_GET['method'];
616
-
617
- if (backupGuardValidateApiCall($token)) {
618
- require_once(SG_PUBLIC_AJAX_PATH.'awake.php');
619
- }
620
- }
621
-
622
- function backup_guard_cancel_download()
623
- {
624
- check_ajax_referer('backupGuardAjaxNonce', 'token');
625
- require_once(SG_PUBLIC_AJAX_PATH.'cancelDownload.php');
626
- }
627
-
628
- function backup_guard_list_storage()
629
- {
630
- check_ajax_referer('backupGuardAjaxNonce', 'token');
631
- require_once(SG_PUBLIC_AJAX_PATH.'listStorage.php');
632
- }
633
-
634
- function backup_guard_download_from_cloud()
635
- {
636
- check_ajax_referer('backupGuardAjaxNonce', 'token');
637
- require_once(SG_PUBLIC_AJAX_PATH.'downloadFromCloud.php');
638
- }
639
-
640
- function backup_guard_hide_notice()
641
- {
642
- check_ajax_referer('backupGuardAjaxNonce', 'token');
643
- require_once(SG_PUBLIC_AJAX_PATH.'hideNotice.php');
644
- }
645
-
646
- function backup_guard_cancel_backup()
647
- {
648
- check_ajax_referer('backupGuardAjaxNonce', 'token');
649
- require_once(SG_PUBLIC_AJAX_PATH.'cancelBackup.php');
650
- }
651
-
652
- function backup_guard_check_backup_creation()
653
- {
654
- check_ajax_referer('backupGuardAjaxNonce', 'token');
655
- require_once(SG_PUBLIC_AJAX_PATH.'checkBackupCreation.php');
656
- }
657
-
658
- function backup_guard_check_restore_creation()
659
- {
660
- check_ajax_referer('backupGuardAjaxNonce', 'token');
661
- require_once(SG_PUBLIC_AJAX_PATH.'checkRestoreCreation.php');
662
- }
663
-
664
- function backup_guard_cloud_dropbox()
665
- {
666
- if (current_user_can('activate_plugins') || (defined('SG_USER_MODE') && SG_USER_MODE)) {
667
- check_ajax_referer('backupGuardAjaxNonce', 'token');
668
- require_once(SG_PUBLIC_AJAX_PATH . 'cloudDropbox.php');
669
- }
670
- }
671
-
672
- function backup_guard_send_usage_status()
673
- {
674
-
675
- if (current_user_can('activate_plugins') || (defined('SG_USER_MODE') && SG_USER_MODE)) {
676
- check_ajax_referer('backupGuardAjaxNonce', 'token');
677
- require_once(SG_PUBLIC_AJAX_PATH . 'sendUsageStatus.php');
678
- }
679
- }
680
-
681
- function backup_guard_curl_checker()
682
- {
683
- check_ajax_referer('backupGuardAjaxNonce', 'token');
684
- require_once(SG_PUBLIC_AJAX_PATH.'curlChecker.php');
685
- }
686
-
687
- function backup_guard_delete_backup()
688
- {
689
- check_ajax_referer('backupGuardAjaxNonce', 'token');
690
- require_once(SG_PUBLIC_AJAX_PATH.'deleteBackup.php');
691
- }
692
-
693
- function backup_guard_download_backup()
694
- {
695
- require_once(SG_PUBLIC_AJAX_PATH.'downloadBackup.php');
696
- }
697
-
698
- function backup_guard_get_action()
699
- {
700
- check_ajax_referer('backupGuardAjaxNonce', 'token');
701
- require_once(SG_PUBLIC_AJAX_PATH.'getAction.php');
702
- }
703
-
704
- function backup_guard_get_running_actions()
705
- {
706
- require_once(SG_PUBLIC_AJAX_PATH.'getRunningActions.php');
707
- }
708
-
709
- function backup_guard_get_import_backup()
710
- {
711
- check_ajax_referer('backupGuardAjaxNonce', 'token');
712
- require_once(SG_PUBLIC_AJAX_PATH.'importBackup.php');
713
- }
714
-
715
- function backup_guard_manual_backup()
716
- {
717
- check_ajax_referer('backupGuardAjaxNonce', 'token');
718
- require_once(SG_PUBLIC_AJAX_PATH.'manualBackup.php');
719
- }
720
-
721
- function backup_guard_reset_status()
722
- {
723
- check_ajax_referer('backupGuardAjaxNonce', 'token');
724
- require_once(SG_PUBLIC_AJAX_PATH.'resetStatus.php');
725
- }
726
-
727
- function backup_guard_restore()
728
- {
729
- require_once(SG_PUBLIC_AJAX_PATH.'restore.php');
730
- }
731
-
732
- function backup_guard_save_cloud_folder()
733
- {
734
- check_ajax_referer('backupGuardAjaxNonce', 'token');
735
- require_once(SG_PUBLIC_AJAX_PATH.'saveCloudFolder.php');
736
- }
737
-
738
- function backup_guard_schedule()
739
- {
740
- require_once(SG_PUBLIC_AJAX_PATH.'schedule.php');
741
- }
742
-
743
- function backup_guard_settings()
744
- {
745
- require_once(SG_PUBLIC_AJAX_PATH.'settings.php');
746
- }
747
-
748
- function backup_guard_set_review_popup_state()
749
- {
750
- check_ajax_referer('backupGuardAjaxNonce', 'token');
751
- require_once(SG_PUBLIC_AJAX_PATH.'setReviewPopupState.php');
752
- }
753
-
754
- function backup_guard_send_usage_statistics()
755
- {
756
- require_once(SG_PUBLIC_AJAX_PATH.'sendUsageStatistics.php');
757
- }
758
-
759
- function backup_guard_login()
760
- {
761
- check_ajax_referer('backupGuardAjaxNonce', 'token');
762
- require_once(SG_PUBLIC_AJAX_PATH.'login.php');
763
- }
764
-
765
- function backup_guard_logout()
766
- {
767
- check_ajax_referer('backupGuardAjaxNonce', 'token');
768
- require_once(SG_PUBLIC_AJAX_PATH.'logout.php');
769
- }
770
-
771
- function backup_guard_link_license()
772
- {
773
- check_ajax_referer('backupGuardAjaxNonce', 'token');
774
- require_once(SG_PUBLIC_AJAX_PATH.'linkLicense.php');
775
- }
776
-
777
- //adds once weekly to the existing schedules.
778
- add_filter('cron_schedules', 'backup_guard_cron_add_weekly');
779
- function backup_guard_cron_add_weekly($schedules)
780
- {
781
- $schedules['weekly'] = array(
782
- 'interval' => 60*60*24*7,
783
- 'display' => 'Once weekly'
784
- );
785
- return $schedules;
786
- }
787
-
788
- //adds once monthly to the existing schedules.
789
- add_filter('cron_schedules', 'backup_guard_cron_add_monthly');
790
- function backup_guard_cron_add_monthly($schedules)
791
- {
792
- $schedules['monthly'] = array(
793
- 'interval' => 60*60*24*30,
794
- 'display' => 'Once monthly'
795
- );
796
- return $schedules;
797
- }
798
-
799
- //adds once yearly to the existing schedules.
800
- add_filter('cron_schedules', 'backup_guard_cron_add_yearly');
801
- function backup_guard_cron_add_yearly($schedules)
802
- {
803
- $schedules['yearly'] = array(
804
- 'interval' => 60*60*24*30*12,
805
- 'display' => 'Once yearly'
806
- );
807
- return $schedules;
808
- }
809
-
810
- function backup_guard_init()
811
- {
812
- backup_guard_register_ajax_callbacks();
813
- // backupGuardPluginRedirect();
814
-
815
- //check if database should be updated
816
- if (backupGuardShouldUpdate()) {
817
- SGBoot::install();
818
- }
819
-
820
- backupGuardSymlinksCleanup(SG_SYMLINK_PATH);
821
- }
822
-
823
- add_action(SG_SCHEDULE_ACTION, 'backup_guard_schedule_action', 10, 1);
824
-
825
- function backup_guard_schedule_action($id)
826
- {
827
- require_once(SG_PUBLIC_PATH.'cron/sg_backup.php');
828
- }
829
-
830
- function sgBackupAdminInit() {
831
- //load pro plugin updater
832
- $pluginCapabilities = backupGuardGetCapabilities();
833
- $isLoggedIn = is_user_logged_in();
834
-
835
- if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE && $isLoggedIn) {
836
- require_once(dirname(__FILE__).'/plugin-update-checker/plugin-update-checker.php');
837
- require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/Utils.php');
838
- require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/UpdateChecker.php');
839
- require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/Scheduler.php');
840
- require_once(SG_LIB_PATH.'SGAuthClient.php');
841
-
842
- $licenseKey = SGConfig::get('SG_LICENSE_KEY');
843
-
844
- $updateChecker = Puc_v4_Factory::buildUpdateChecker(
845
- BackupGuard\Config::URL.'/products/details/'.$licenseKey,
846
- SG_BACKUP_GUARD_MAIN_FILE,
847
- SG_PRODUCT_IDENTIFIER
848
- );
849
-
850
- $updateChecker->addHttpRequestArgFilter(array(
851
- SGAuthClient::getInstance(),
852
- 'filterUpdateChecks'
853
- ));
854
- }
855
-
856
- require_once(SG_LIB_PATH.'SGStatsRequests.php');
857
- SGStatsRequests::initialSync();
858
- }
859
-
860
- add_action('admin_init', 'sgBackupAdminInit');
861
-
862
- if (SGBoot::isFeatureAvailable('ALERT_BEFORE_UPDATE')) {
863
- add_filter('upgrader_pre_download', 'backupGuardOnBeforeUpdateDownload', 10, 3);
864
- add_action('core_upgrade_preamble', 'backupGuardOnUpgradeScreenActivate');
865
- add_action('current_screen', 'backupGuardOnScreenActivate');
866
- }
867
-
868
- // Register the new dashboard widget with the 'wp_dashboard_setup' action
869
- add_action('wp_dashboard_setup', 'backup_guard_add_dashboard_widgets');
870
-
871
- function backup_guard_add_dashboard_widgets()
872
- {
873
- require_once(SG_CORE_PATH.'SGConfig.php');
874
-
875
- $userId = get_current_user_id();
876
- $userData = get_userdata($userId);
877
- $userRoles = $userData->roles;
878
- $isAdminUser = false;
879
- for($i = 0; $i < count($userRoles); $i++) {
880
- if ($userRoles[$i] == "administrator") {
881
- $isAdminUser = true;
882
- break;
883
- }
884
- }
885
-
886
- if (!$isAdminUser ) {
887
- return;
888
- }
889
-
890
- $isShowStatisticsWidgetEnabled = SGConfig::get('SG_SHOW_STATISTICS_WIDGET');
891
- if (!$isShowStatisticsWidgetEnabled) {
892
- return;
893
- }
894
-
895
-
896
- require_once(plugin_dir_path( __FILE__ ).'public/dashboardWidget.php');
897
- wp_add_dashboard_widget('backupGuardWidget', 'Backup Guard', 'backup_guard_dashboard_widget_function');
898
- }
899
-
900
- add_action('plugins_loaded', 'backupGuardloadTextDomain');
901
- function backupGuardloadTextDomain()
902
- {
903
- $backupGuardLangDir = plugin_dir_path(__FILE__).'languages/';
904
- $backupGuardLangDir = apply_filters('backupguardLanguagesDirectory', $backupGuardLangDir);
905
-
906
- $locale = apply_filters('bg_plugin_locale', get_locale(), BACKUP_GUARD_TEXTDOMAIN);
907
- $mofile = sprintf('%1$s-%2$s.mo', BACKUP_GUARD_TEXTDOMAIN, $locale);
908
-
909
- $mofileLocal = $backupGuardLangDir.$mofile;
910
-
911
- if (file_exists($mofileLocal)) {
912
- // Look in local /wp-content/plugins/popup-builder/languages/ folder
913
- load_textdomain(BACKUP_GUARD_TEXTDOMAIN, $mofileLocal);
914
- }
915
- else {
916
- // Load the default language files
917
- load_plugin_textdomain(BACKUP_GUARD_TEXTDOMAIN, false, $backupGuardLangDir);
918
- }
919
- }
920
-
921
- if (backupGuardShouldShowDiscountNotice() && checkDueDateDiscount()) {
922
- add_action('admin_notices', 'backup_guard_discount_notice');
923
- }
924
-
925
- function backup_guard_discount_notice()
926
- {
927
- $capabilities = backupGuardGetCapabilities();
928
- $upgradeUrl = BG_UPGRADE_URL;
929
- ?>
930
- <div class="backup-guard-discount-notice updated notice is-dismissible">
931
- <div class="sgbg-col sgbg-col1"></div>
932
- <div class="sgbg-col sgbg-col2"></div>
933
- <div class="sgbg-col sgbg-col3">
934
- <div class="sgbg-text-col-1">
935
- -50%
936
- </div>
937
- <div class="sgbg-text-col-2">
938
- <div class="sgbg-discount-text-1">Discount</div>
939
- <div class="sgbg-discount-text-2">All Backup Guard Solutions</div>
940
- </div>
941
- </div>
942
- <div class="sgbg-col sgbg-col4">
943
- <a href="https://backup-guard.com/products/backup-wordpress" target="_blank"><button class="sgbg-button">Click Here</button></a>
944
- </div>
945
- </div>
946
- <style>
947
- .backup-guard-discount-notice.updated.notice.is-dismissible {
948
- padding: 0;
949
- border-left-color: #FFFFFF !important;
950
- background-color: #000000;
951
- height: 160px;
952
- }
953
- .backup-guard-discount-notice button:before {
954
- color: #ffffff !important;
955
- }
956
- .sgbg-col {
957
- display: inline-block;
958
- width: 25%;
959
- height: 100%;
960
- padding: 0 25px;
961
- box-sizing: border-box;
962
- }
963
- .sgbg-col1 {
964
- width: 10%;
965
- background-color: #FFFFFF;
966
- background-image: url("<?php echo SG_IMAGE_URL ?>BgBFLogo.jpg");
967
- background-size: 80%;
968
- background-repeat: no-repeat;
969
- background-position: center;
970
- }
971
- .sgbg-col2 {
972
- width: 20%;
973
- background-image: url("<?php echo SG_IMAGE_URL ?>BF.png");
974
- background-size: contain;
975
- margin-left: 70px;
976
- background-position: center;
977
- background-repeat: no-repeat;
978
- }
979
- .sgbg-col3 {
980
- vertical-align: top;
981
- width: 45%;
982
- margin-top: 55px;
983
- }
984
- .sgbg-col4 {
985
- width: 10%;
986
- }
987
- .sgbg-text-col-1,
988
- .sgbg-text-col-2 {
989
- width: 49%;
990
- display: inline-block;
991
- color: #FFFFFF;
992
- }
993
- .sgbg-text-col-1 {
994
- font-size: 100px;
995
- line-height: 0;
996
- font-weight: bold;
997
- text-align: right;
998
- padding-right: 26px;
999
- box-sizing: border-box;
1000
- }
1001
- .sgbg-discount-text-2 {
1002
- font-size: 19px;
1003
- }
1004
- .sgbg-discount-text-1 {
1005
- font-size: 60px;
1006
- padding-bottom: 27px;
1007
- font-weight: bold;
1008
- }
1009
- .sgbg-col4 {
1010
- vertical-align: top;
1011
- }
1012
- .sgbg-button {
1013
- width: 183px;
1014
- height: 67px;
1015
- font-size: 20px;
1016
- border: #ffffff;
1017
- border-radius: 10px;
1018
- margin-top: 48px;
1019
- background-color: #FFFFFF;
1020
- color: #000000;
1021
- cursor: pointer !important;
1022
- }
1023
- .sgbg-button:hover {
1024
- background-color: #000000;
1025
- border: 1px solid #FFFFFF;
1026
- color: #FFFFFF;
1027
- }
1028
- .backup-guard-discount-notice .notice-dismiss::before {
1029
- content: "x";
1030
- font-weight: 300;
1031
- font-family: Arial, sans-serif;
1032
- }
1033
-
1034
- @media (max-width: 1810px) {
1035
- .sgbg-text-col-1 {
1036
- font-size: 80px;
1037
- }
1038
- .sgbg-discount-text-1 {
1039
- font-size: 43px;
1040
- }
1041
- .sgbg-discount-text-2 {
1042
- font-size: 15px;
1043
- }
1044
- .sgbg-discount-text-1 {
1045
- padding-bottom: 18px;
1046
- }
1047
- .sgbg-col3 {
1048
- margin-top: 60px;
1049
- }
1050
- }
1051
- @media (max-width: 1477px) {
1052
- .sgbg-discount-text-2 {
1053
- font-size: 12px;
1054
- }
1055
- .sgbg-discount-text-1 {
1056
- font-size: 35px;
1057
- }
1058
- .sgbg-discount-text-1 {
1059
- padding-bottom: 13px;
1060
- }
1061
- .sgbg-col {
1062
- padding: 0;
1063
- }
1064
- .sgbg-col2 {
1065
- margin-left: 40px;
1066
- }
1067
- .sgbg-col2 {
1068
- margin-left: 0;
1069
- }
1070
- }
1071
- </style>
1072
- <?php
1073
- }
1074
-
1075
- add_action('admin_notices', 'backup_guard_review_banner');
1076
- function backup_guard_review_banner()
1077
- {
1078
- require_once(SG_LIB_PATH.'SGReviewManager.php');
1079
- $reviewManager = new SGReviewManager();
1080
- $reviewManager->renderContent();
1081
- }
1
+ <?php
2
+
3
+ // hook to wordpres widget
4
+ function backup_guard_register_widget()
5
+ {
6
+ if (!class_exists('SGWordPressWidget')) {
7
+ @include_once(SG_WIDGET_PATH.'SGWordPressWidget.php');
8
+ }
9
+
10
+ register_widget('SGWordPressWidget');
11
+ }
12
+ add_action('widgets_init', 'backup_guard_register_widget');
13
+
14
+ //The code that runs during plugin activation.
15
+ function activate_backup_guard()
16
+ {
17
+ //check if database should be updated
18
+ if (backupGuardShouldUpdate()) {
19
+ SGBoot::install();
20
+ SGBoot::didInstallForFirstTime();
21
+ }
22
+ }
23
+
24
+ // The code that runs during plugin deactivation.
25
+ function uninstall_backup_guard()
26
+ {
27
+ SGBoot::uninstall();
28
+ }
29
+
30
+ function deactivate_backup_guard()
31
+ {
32
+ $pluginCapabilities = backupGuardGetCapabilities();
33
+ if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
34
+ require_once(SG_LIB_PATH.'SGAuthClient.php');
35
+ $res = SGAuthClient::getInstance()->logout();
36
+ SGConfig::set('SG_LICENSE_CHECK_TS', 0, true);
37
+ SGConfig::set('SG_LOGGED_USER', '', true);
38
+ }
39
+ }
40
+
41
+ function backupGuardMaybeShortenEddFilename($return, $package)
42
+ {
43
+ if (strpos($package, 'backup-guard') !== false) {
44
+ add_filter('wp_unique_filename', 'backupGuardShortenEddFilename', 10, 2);
45
+ }
46
+ return $return;
47
+ }
48
+
49
+ function backupGuardShortenEddFilename($filename, $ext)
50
+ {
51
+ $filename = substr($filename, 0, 20).$ext;
52
+ remove_filter('wp_unique_filename', 'backupGuardShortenEddFilename', 10);
53
+ return $filename;
54
+ }
55
+
56
+ add_filter('upgrader_pre_download', 'backupGuardMaybeShortenEddFilename', 10, 4);
57
+
58
+ register_activation_hook(SG_BACKUP_GUARD_MAIN_FILE, 'activate_backup_guard');
59
+ register_uninstall_hook(SG_BACKUP_GUARD_MAIN_FILE, 'uninstall_backup_guard');
60
+ register_deactivation_hook(SG_BACKUP_GUARD_MAIN_FILE, 'deactivate_backup_guard');
61
+ //add_action('admin_footer', 'before_deactivate_backup_guard');
62
+
63
+ function before_deactivate_backup_guard()
64
+ {
65
+ wp_enqueue_style('before-deactivate-backup-guard-css', plugin_dir_url(__FILE__).'public/css/deactivationSurvey.css');
66
+ wp_enqueue_script('before-deactivate-backup-guard-js', plugin_dir_url(__FILE__).'public/js/deactivationSurvey.js', array('jquery'));
67
+
68
+ wp_localize_script('before-deactivate-backup-guard-js', 'BG_BACKUP_STRINGS_DEACTIVATE', array(
69
+ 'nonce' => wp_create_nonce('backupGuardAjaxNonce'),
70
+ 'areYouSure' => _backupGuardT('Are you sure?', true),
71
+ 'invalidCloud' => _backupGuardT('Please select at least 1 cloud', true)
72
+ ));
73
+
74
+ require_once(plugin_dir_path(__FILE__).'public/include/uninstallSurveyPopup.php');
75
+ }
76
+
77
+ // Register Admin Menus for single and multisite
78
+ if (is_multisite()) {
79
+ add_action('network_admin_menu', 'backup_guard_admin_menu');
80
+ }
81
+ else {
82
+ add_action('admin_menu', 'backup_guard_admin_menu');
83
+ }
84
+
85
+ function backup_guard_admin_menu()
86
+ {
87
+ $capability = 'manage_options';
88
+ if (defined('SG_USER_MODE') && SG_USER_MODE) {
89
+ $capability = 'read';
90
+ }
91
+
92
+ add_menu_page('Backups', 'BackupGuard', $capability, 'backup_guard_backups', 'includeAllPages', 'data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2MzAuMzQgNjYzLjAzIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkFydGJvYXJkIDI8L3RpdGxlPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTUzMC4xMSwxODUuNzljLTcxLjktOC44Mi0xMzcuNzMtNDAtMTkwLTg2LjU3djkyLjY1YTI4MC41OSwyODAuNTksMCwwLDAsMTE2LjUyLDUyYy05LjE0LDg5LjQzLTUyLDE2OS41NS0xMTYuNTIsMjI4Ljg3djkwLjRDNDU5Ljg0LDQ3Ny4xMyw1MzAuNiwzMzMuNDIsNTMwLjExLDE4NS43OVoiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xNzQuMjksMjQ0YTI4MC40NiwyODAuNDYsMCwwLDAsMTE1Ljc3LTUxLjExVjEwMGMtNTIuNDQsNDYuMjgtMTE3LjYyLDc3LTE4OS44Myw4NS4xNUM5OS41NCwzMzMsMTcwLjIyLDQ3Ni44MiwyOTAuMDYsNTYzVjQ3Mi4wOUMyMjYsNDEyLjg2LDE4My40MiwzMzMuMDYsMTc0LjI5LDI0NFoiLz48L3N2Zz4=', 74);
93
+
94
+ add_submenu_page('backup_guard_backups', _backupGuardT('Backups', true), _backupGuardT('Backups', true), $capability, 'backup_guard_backups', 'includeAllPages');
95
+ add_submenu_page('backup_guard_backups', _backupGuardT('Cloud', true), _backupGuardT('Cloud', true), $capability, 'backup_guard_cloud', 'includeAllPages');
96
+ add_submenu_page('backup_guard_backups', _backupGuardT('Schedule', true), _backupGuardT('Schedule', true), $capability, 'backup_guard_schedule', 'includeAllPages');
97
+
98
+ add_submenu_page('backup_guard_backups', _backupGuardT('Settings', true), _backupGuardT('Settings', true), $capability, 'backup_guard_settings', 'includeAllPages');
99
+
100
+ add_submenu_page('backup_guard_backups', _backupGuardT('System Info.', true), _backupGuardT('System Info.', true), $capability, 'backup_guard_system_info', 'includeAllPages');
101
+
102
+ add_submenu_page('backup_guard_backups', _backupGuardT('Services', true), _backupGuardT('Services', true), $capability, 'backup_guard_services', 'includeAllPages');
103
+ add_submenu_page('backup_guard_backups', _backupGuardT('Video Tutorials', true), _backupGuardT('Video Tutorials', true), $capability, 'backup_guard_videoTutorials', 'includeAllPages');
104
+ add_submenu_page('backup_guard_backups', _backupGuardT('Support', true), _backupGuardT('Support', true), $capability, 'backup_guard_support', 'includeAllPages');
105
+
106
+ //Check if should show upgrade page
107
+ if (SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE')) {
108
+ add_submenu_page('backup_guard_backups', _backupGuardT('Why upgrade?', true), _backupGuardT('Why upgrade?', true), $capability, 'backup_guard_pro_features', 'includeAllPages');
109
+ }
110
+ }
111
+
112
+ function getBackupPageContentClassName($pageName = '')
113
+ {
114
+ $hiddenClassName = 'sg-visibility-hidden';
115
+ $page = $_GET['page'];
116
+
117
+ if (strpos($page, $pageName)) {
118
+ $hiddenClassName = '';
119
+ }
120
+
121
+ return $hiddenClassName;
122
+ }
123
+
124
+ function includeAllPages()
125
+ {
126
+ if (!backupGuardValidateLicense()) {
127
+ return false;
128
+ }
129
+ backup_guard_backups_page();
130
+ backup_guard_cloud_page();
131
+ backup_guard_system_info_page();
132
+ backup_guard_services_page();
133
+ backup_guard_pro_features_page();
134
+ backup_guard_support_page();
135
+ backup_guard_schedule_page();
136
+ backup_guard_settings_page();
137
+
138
+ require_once(plugin_dir_path(__FILE__).'public/pagesContent.php');
139
+
140
+ return true;
141
+ }
142
+
143
+ function backup_guard_system_info_page()
144
+ {
145
+ if (backupGuardValidateLicense()) {
146
+ //require_once(plugin_dir_path(__FILE__).'public/systemInfo.php');
147
+ }
148
+ }
149
+
150
+ function backup_guard_services_page()
151
+ {
152
+ if (backupGuardValidateLicense()) {
153
+ //require_once(plugin_dir_path(__FILE__).'public/services.php');
154
+ }
155
+ }
156
+
157
+ //Pro features page
158
+ function backup_guard_pro_features_page()
159
+ {
160
+ // require_once(plugin_dir_path(__FILE__).'public/proFeatures.php');
161
+ }
162
+
163
+ function backup_guard_security_page()
164
+ {
165
+ require_once(plugin_dir_path(__FILE__).'public/security.php');
166
+ }
167
+
168
+ //Support page
169
+ function backup_guard_support_page()
170
+ {
171
+ if (backupGuardValidateLicense()) {
172
+ // require_once(plugin_dir_path(__FILE__).'public/support.php');
173
+ }
174
+ }
175
+
176
+ //Backups Page
177
+ function backup_guard_backups_page()
178
+ {
179
+ if (backupGuardValidateLicense()) {
180
+ wp_enqueue_script('backup-guard-iframe-transport-js', plugin_dir_url(__FILE__).'public/js/jquery.iframe-transport.js', array('jquery'));
181
+ wp_enqueue_script('backup-guard-fileupload-js', plugin_dir_url(__FILE__).'public/js/jquery.fileupload.js', array('jquery'));
182
+ wp_enqueue_script('backup-guard-jstree-js', plugin_dir_url(__FILE__).'public/js/jstree.min.js', array('jquery'));
183
+ wp_enqueue_script('backup-guard-jstree-checkbox-js', plugin_dir_url(__FILE__).'public/js/jstree.checkbox.js', array('jquery'));
184
+ wp_enqueue_script('backup-guard-jstree-wholerow-js', plugin_dir_url(__FILE__).'public/js/jstree.wholerow.js', array('jquery'));
185
+ wp_enqueue_script('backup-guard-jstree-types-js', plugin_dir_url(__FILE__).'public/js/jstree.types.js', array('jquery'));
186
+ wp_enqueue_style('backup-guard-jstree-css', plugin_dir_url(__FILE__).'public/css/default/style.min.css');
187
+ wp_enqueue_script('backup-guard-backups-js', plugin_dir_url(__FILE__).'public/js/sgbackup.js', array('jquery', 'jquery-effects-core', 'jquery-effects-transfer', 'jquery-ui-widget'));
188
+
189
+ // Localize the script with new data
190
+ wp_localize_script('backup-guard-backups-js', 'BG_BACKUP_STRINGS', array(
191
+ 'confirm' => _backupGuardT('Are you sure you want to cancel import?', true),
192
+ 'nonce' => wp_create_nonce('backupGuardAjaxNonce'),
193
+ 'invalidBackupOption' => _backupGuardT('Please choose at least one option.', true),
194
+ 'invalidDirectorySelected' => _backupGuardT('Please choose at least one directory.', true),
195
+ 'invalidCloud' => _backupGuardT('Please choose at least one cloud.', true),
196
+ 'backupInProgress' => _backupGuardT('Backing Up...', true),
197
+ 'errorMessage' => _backupGuardT('Something went wrong. Please try again.', true),
198
+ 'noBackupsAvailable' => _backupGuardT('No backups found.', true),
199
+ 'invalidImportOption' => _backupGuardT('Please select one of the options.', true),
200
+ 'invalidDownloadFile' => _backupGuardT('Please choose one of the files.', true),
201
+ 'import' => _backupGuardT('Import', true),
202
+ 'importInProgress' => _backupGuardT('Importing please wait...', true),
203
+ 'fileUploadFailed' => _backupGuardT('File upload failed.', true)
204
+ ));
205
+
206
+ // require_once(plugin_dir_path( __FILE__ ).'public/backups.php');
207
+ }
208
+ }
209
+
210
+ //Cloud Page
211
+ function backup_guard_cloud_page()
212
+ {
213
+ if (backupGuardValidateLicense()) {
214
+ wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
215
+ wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), SG_BACKUP_GUARD_VERSION, true);
216
+ wp_enqueue_script('backup-guard-jquery-validate-js', plugin_dir_url(__FILE__).'public/js/jquery.validate.min.js', array('jquery', 'backup-guard-switch-js'), SG_BACKUP_GUARD_VERSION, true);
217
+ wp_enqueue_script('backup-guard-cloud-js', plugin_dir_url(__FILE__).'public/js/sgcloud.js', array('jquery', 'backup-guard-switch-js'), SG_BACKUP_GUARD_VERSION, true);
218
+
219
+ // Localize the script with new data
220
+ wp_localize_script('backup-guard-cloud-js', 'BG_CLOUD_STRINGS', array(
221
+ 'invalidImportFile' => _backupGuardT('Please select a file.', true),
222
+ 'invalidFileSize' => _backupGuardT('File is too large.', true),
223
+ 'connectionInProgress' => _backupGuardT('Connecting...', true),
224
+ 'invalidDestinationFolder' => _backupGuardT('Destination folder is required.', true),
225
+ 'successMessage' => _backupGuardT('Successfully saved.', true)
226
+ ));
227
+
228
+ //require_once(plugin_dir_path(__FILE__).'public/cloud.php');
229
+ }
230
+ }
231
+
232
+ //Schedule Page
233
+ function backup_guard_schedule_page()
234
+ {
235
+ if (backupGuardValidateLicense()) {
236
+ wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
237
+ wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), '1.0.0', true);
238
+ wp_enqueue_script('backup-guard-schedule-js', plugin_dir_url(__FILE__).'public/js/sgschedule.js', array('jquery'), '1.0.0', true);
239
+
240
+ // Localize the script with new data
241
+ wp_localize_script('backup-guard-schedule-js', 'BG_SCHEDULE_STRINGS', array(
242
+ 'deletionError' => _backupGuardT('Unable to delete schedule', true),
243
+ 'confirm' => _backupGuardT('Are you sure?', true),
244
+ 'invalidBackupOption' => _backupGuardT('Please choose at least one option.', true),
245
+ 'invalidDirectorySelected' => _backupGuardT('Please choose at least one directory.', true),
246
+ 'invalidCloud' => _backupGuardT('Please choose at least one cloud.', true),
247
+ 'savingInProgress' => _backupGuardT('Saving...', true),
248
+ 'successMessage' => _backupGuardT('You have successfully activated schedule.', true),
249
+ 'saveButtonText' => _backupGuardT('Save', true)
250
+ ));
251
+
252
+ // require_once(plugin_dir_path( __FILE__ ).'public/schedule.php');
253
+ }
254
+ }
255
+
256
+ //Settings Page
257
+ function backup_guard_settings_page()
258
+ {
259
+ if (backupGuardValidateLicense()) {
260
+ wp_enqueue_style('backup-guard-switch-css', plugin_dir_url(__FILE__).'public/css/bootstrap-switch.min.css');
261
+ wp_enqueue_script('backup-guard-switch-js', plugin_dir_url(__FILE__).'public/js/bootstrap-switch.min.js', array('jquery'), '1.0.0', true);
262
+ wp_enqueue_script('backup-guard-settings-js', plugin_dir_url(__FILE__).'public/js/sgsettings.js', array('jquery'), '1.0.0', true );
263
+
264
+ // Localize the script with new data
265
+ wp_localize_script('backup-guard-settings-js', 'BG_SETTINGS_STRINGS', array(
266
+ 'invalidEmailAddress' => _backupGuardT('Please enter valid email.', true),
267
+ 'invalidFileName' => _backupGuardT('Please enter valid file name.', true),
268
+ 'invalidRetentionNumber' => _backupGuardT('Please enter a valid retention number.', true),
269
+ 'successMessage' => _backupGuardT('Successfully saved.', true),
270
+ 'savingInProgress' => _backupGuardT('Saving...', true),
271
+ 'retentionConfirmationFirstPart' => _backupGuardT('Are you sure you want to keep the latest', true),
272
+ 'retentionConfirmationSecondPart' => _backupGuardT('backups? All older backups will be deleted.', true),
273
+ 'saveButtonText' => _backupGuardT('Save', true)
274
+ ));
275
+
276
+ //require_once(plugin_dir_path(__FILE__).'public/settings.php');
277
+ }
278
+ }
279
+
280
+ function backup_guard_login_page()
281
+ {
282
+ wp_enqueue_script('backup-guard-login-js', plugin_dir_url(__FILE__).'public/js/sglogin.js', array('jquery'), '1.0.0', true);
283
+
284
+ require_once(plugin_dir_path(__FILE__).'public/login.php');
285
+ }
286
+
287
+ function backup_guard_link_license_page()
288
+ {
289
+ wp_enqueue_script('backup-guard-license-js', plugin_dir_url(__FILE__).'public/js/sglicense.js', array('jquery'), '1.0.0', true);
290
+ // Localize the script with new data
291
+ wp_localize_script('backup-guard-license-js', 'BG_LICENSE_STRINGS', array(
292
+ 'invalidLicense' => _backupGuardT('Please choose a license first', true),
293
+ 'availableLicenses' => _backupGuardT('There are no available licenses for using the selected product', true)
294
+ ));
295
+
296
+ require_once(plugin_dir_path(__FILE__).'public/link_license.php');
297
+ }
298
+
299
+ add_action('admin_enqueue_scripts', 'enqueue_backup_guard_scripts');
300
+ function enqueue_backup_guard_scripts($hook)
301
+ {
302
+ wp_enqueue_script('backup-guard-discount-notice', plugin_dir_url(__FILE__).'public/js/sgNoticeDismiss.js', array('jquery'), '1.0', true);
303
+
304
+ if (!strpos($hook,'backup_guard')) {
305
+ if($hook == "index.php"){
306
+ wp_enqueue_script('backup-guard-chart-manager', plugin_dir_url(__FILE__).'public/js/Chart.bundle.min.js');
307
+ }
308
+ return;
309
+ }
310
+
311
+ wp_enqueue_style('backup-guard-spinner', plugin_dir_url(__FILE__).'public/css/spinner.css');
312
+ wp_enqueue_style('backup-guard-wordpress', plugin_dir_url(__FILE__).'public/css/bgstyle.wordpress.css');
313
+ wp_enqueue_style('backup-guard-less', plugin_dir_url(__FILE__).'public/css/bgstyle.less.css');
314
+ wp_enqueue_style('backup-guard-styles', plugin_dir_url(__FILE__).'public/css/styles.css');
315
+
316
+ echo '<script type="text/javascript">sgBackup={};';
317
+ $sgAjaxRequestFrequency = SGConfig::get('SG_AJAX_REQUEST_FREQUENCY');
318
+ if (!$sgAjaxRequestFrequency) {
319
+ $sgAjaxRequestFrequency = SG_AJAX_DEFAULT_REQUEST_FREQUENCY;
320
+ }
321
+ echo 'SG_AJAX_REQUEST_FREQUENCY = "'.$sgAjaxRequestFrequency.'";';
322
+ echo 'function getAjaxUrl(url) {'.
323
+ 'if (url==="cloudDropbox" || url==="cloudGdrive" || url==="cloudOneDrive") return "'.admin_url('admin-post.php?action=backup_guard_').'"+url+"&token='.wp_create_nonce('backupGuardAjaxNonce').'";'.
324
+ 'return "'.admin_url('admin-ajax.php').'";}</script>';
325
+
326
+ wp_enqueue_media();
327
+ wp_enqueue_script('backup-guard-less-framework', plugin_dir_url(__FILE__).'public/js/less.min.js', array('jquery'), '1.0.0', true);
328
+ wp_enqueue_script('backup-guard-bootstrap-framework', plugin_dir_url(__FILE__).'public/js/bootstrap.min.js', array('jquery'), '1.0.0', true);
329
+ wp_enqueue_script('backup-guard-sgrequest-js', plugin_dir_url(__FILE__).'public/js/sgrequesthandler.js', array('jquery'), '1.0.0', true);
330
+ wp_enqueue_script('backup-guard-sgwprequest-js', plugin_dir_url(__FILE__).'public/js/sgrequesthandler.wordpress.js', array('jquery'), '1.0.0', true);
331
+
332
+ wp_enqueue_style('backup-guard-rateyo-css', plugin_dir_url(__FILE__).'public/css/jquery.rateyo.css');
333
+ wp_enqueue_script('backup-guard-rateyo-js', plugin_dir_url(__FILE__).'public/js/jquery.rateyo.js');
334
+
335
+ wp_enqueue_script('backup-guard-main-js', plugin_dir_url(__FILE__).'public/js/main.js', array('jquery'), '1.0.0', true);
336
+ wp_enqueue_script('backup-popup.js', plugin_dir_url(__FILE__).'public/js/popup.js', array('jquery'), '1.0.0', true);
337
+ wp_enqueue_style('popupTheme.css', plugin_dir_url(__FILE__).'public/css/popupTheme.css');
338
+
339
+ // Localize the script with new data
340
+ wp_localize_script('backup-guard-main-js', 'BG_MAIN_STRINGS', array(
341
+ 'confirmCancel' => _backupGuardT('Are you sure you want to cancel?', true)
342
+ ));
343
+
344
+ wp_localize_script('backup-guard-main-js', 'BG_BACKUP_STRINGS', array(
345
+ 'nonce' => wp_create_nonce('backupGuardAjaxNonce')
346
+ ));
347
+ }
348
+
349
+ // adding actions to handle modal ajax requests
350
+ add_action( 'wp_ajax_backup_guard_modalManualBackup', 'backup_guard_get_manual_modal');
351
+ add_action( 'wp_ajax_backup_guard_modalManualRestore', 'backup_guard_get_manual_restore_modal');
352
+ add_action( 'wp_ajax_backup_guard_modalImport', 'backup_guard_get_import_modal');
353
+ add_action( 'wp_ajax_backup_guard_modalFtpSettings', 'backup_guard_get_ftp_modal');
354
+ add_action( 'wp_ajax_backup_guard_modalAmazonSettings', 'backup_guard_get_amazon_modal');
355
+ add_action( 'wp_ajax_backup_guard_modalPrivacy', 'backup_guard_get_privacy_modal');
356
+ add_action( 'wp_ajax_backup_guard_modalTerms', 'backup_guard_get_terms_modal');
357
+ add_action( 'wp_ajax_backup_guard_modalReview', 'backup_guard_get_review_modal');
358
+ add_action( 'wp_ajax_backup_guard_getFileDownloadProgress', 'backup_guard_get_file_download_progress');
359
+ add_action( 'wp_ajax_backup_guard_modalCreateSchedule', 'backup_guard_create_schedule');
360
+ add_action( 'wp_ajax_backup_guard_getBackupContent', 'backup_guard_get_backup_content');
361
+
362
+ add_action( 'wp_ajax_backup_guard_modalBackupGuardDetails', 'backup_guard_get_backup_guard_modal');
363
+
364
+ function backup_guard_get_backup_guard_modal()
365
+ {
366
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
367
+ require_once(SG_PUBLIC_AJAX_PATH.'modalBackupGuardDetails.php');
368
+ exit();
369
+ }
370
+
371
+ function backup_guard_get_file_download_progress()
372
+ {
373
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
374
+ require_once(SG_PUBLIC_AJAX_PATH.'getFileDownloadProgress.php');
375
+ exit();
376
+ }
377
+
378
+ function backup_guard_create_schedule()
379
+ {
380
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
381
+ require_once(SG_PUBLIC_AJAX_PATH.'modalCreateSchedule.php');
382
+ exit();
383
+ }
384
+
385
+ function backup_guard_get_manual_modal()
386
+ {
387
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
388
+ if (current_user_can( 'activate_plugins' ) || (defined('SG_USER_MODE') && SG_USER_MODE)) {
389
+ require_once(SG_PUBLIC_AJAX_PATH.'modalManualBackup.php');
390
+ }
391
+ exit();
392
+ }
393
+
394
+ function backup_guard_get_manual_restore_modal()
395
+ {
396
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
397
+ require_once(SG_PUBLIC_AJAX_PATH.'modalManualRestore.php');
398
+ exit();
399
+ }
400
+
401
+ function backup_guard_get_backup_content()
402
+ {
403
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
404
+ require_once (SG_PUBLIC_AJAX_PATH.'getBackupContent.php');
405
+ exit();
406
+ }
407
+
408
+ function backup_guard_get_import_modal()
409
+ {
410
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
411
+ require_once(SG_PUBLIC_AJAX_PATH.'modalImport.php');
412
+ exit();
413
+ }
414
+
415
+ function backup_guard_get_ftp_modal()
416
+ {
417
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
418
+ require_once(SG_PUBLIC_AJAX_PATH.'modalFtpSettings.php');
419
+ exit();
420
+ }
421
+
422
+ function backup_guard_get_amazon_modal()
423
+ {
424
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
425
+ require_once(SG_PUBLIC_AJAX_PATH.'modalAmazonSettings.php');
426
+ exit();
427
+ }
428
+
429
+ function backup_guard_get_privacy_modal()
430
+ {
431
+ require_once(SG_PUBLIC_AJAX_PATH.'modalPrivacy.php');
432
+ }
433
+
434
+ function backup_guard_get_terms_modal()
435
+ {
436
+ require_once(SG_PUBLIC_AJAX_PATH.'modalTerms.php');
437
+ exit();
438
+ }
439
+
440
+ function backup_guard_get_review_modal()
441
+ {
442
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
443
+ require_once(SG_PUBLIC_AJAX_PATH.'modalReview.php');
444
+ exit();
445
+ }
446
+
447
+ function backup_guard_register_ajax_callbacks()
448
+ {
449
+ if (is_super_admin() || (defined('SG_USER_MODE') && SG_USER_MODE)) {
450
+ // adding actions to handle ajax and post requests
451
+ add_action('wp_ajax_backup_guard_cancelBackup', 'backup_guard_cancel_backup');
452
+ add_action('wp_ajax_backup_guard_checkBackupCreation', 'backup_guard_check_backup_creation');
453
+ add_action('wp_ajax_backup_guard_checkRestoreCreation', 'backup_guard_check_restore_creation');
454
+ add_action('wp_ajax_backup_guard_cloudDropbox', 'backup_guard_cloud_dropbox');
455
+ add_action('wp_ajax_backup_guard_send_usage_status', 'backup_guard_send_usage_status');
456
+
457
+ $pluginCapabilities = backupGuardGetCapabilities();
458
+ if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
459
+ require_once dirname(__FILE__).'/BackupGuardPro.php';
460
+ }
461
+ add_action('wp_ajax_backup_guard_curlChecker', 'backup_guard_curl_checker');
462
+ add_action('wp_ajax_backup_guard_deleteBackup', 'backup_guard_delete_backup');
463
+ add_action('wp_ajax_backup_guard_getAction', 'backup_guard_get_action');
464
+ add_action('wp_ajax_backup_guard_getRunningActions', 'backup_guard_get_running_actions');
465
+ add_action('wp_ajax_backup_guard_importBackup', 'backup_guard_get_import_backup');
466
+ add_action('wp_ajax_backup_guard_resetStatus', 'backup_guard_reset_status');
467
+ add_action('wp_ajax_backup_guard_restore', 'backup_guard_restore');
468
+ add_action('wp_ajax_backup_guard_saveCloudFolder', 'backup_guard_save_cloud_folder');
469
+ add_action('wp_ajax_backup_guard_schedule', 'backup_guard_schedule');
470
+ add_action('wp_ajax_backup_guard_settings', 'backup_guard_settings');
471
+ add_action('wp_ajax_backup_guard_setReviewPopupState', 'backup_guard_set_review_popup_state');
472
+ add_action('wp_ajax_backup_guard_sendUsageStatistics', 'backup_guard_send_usage_statistics');
473
+ add_action('wp_ajax_backup_guard_hideNotice', 'backup_guard_hide_notice');
474
+ add_action('wp_ajax_backup_guard_downloadFromCloud', 'backup_guard_download_from_cloud');
475
+ add_action('wp_ajax_backup_guard_listStorage', 'backup_guard_list_storage');
476
+ add_action('wp_ajax_backup_guard_cancelDownload', 'backup_guard_cancel_download');
477
+ add_action('wp_ajax_backup_guard_awake', 'backup_guard_awake');
478
+ add_action('wp_ajax_backup_guard_manualBackup', 'backup_guard_manual_backup');
479
+ add_action('admin_post_backup_guard_downloadBackup', 'backup_guard_download_backup');
480
+ add_action('wp_ajax_backup_guard_login', 'backup_guard_login');
481
+ add_action('wp_ajax_backup_guard_logout', 'backup_guard_logout');
482
+ add_action('wp_ajax_backup_guard_link_license', 'backup_guard_link_license');
483
+ add_action('wp_ajax_backup_guard_importKeyFile', 'backup_guard_import_key_file');
484
+ add_action('wp_ajax_backup_guard_isFeatureAvailable', 'backup_guard_is_feature_available');
485
+ add_action('wp_ajax_backup_guard_dismiss_discount_notice', 'backup_guard_dismiss_discount_notice');
486
+ add_action('wp_ajax_backup_guard_checkFreeMigration', 'backup_guard_check_free_migration');
487
+ add_action('wp_ajax_backup_guard_checkPHPVersionCompatibility', 'backup_guard_check_php_version_compatibility');
488
+ add_action('wp_ajax_backup_guard_setUserInfoVerificationPopupState', 'backup_guard_set_user_info_verification_popup_state');
489
+ add_action('wp_ajax_backup_guard_storeSubscriberInfo', 'backup_guard_store_subscriber_info');
490
+ add_action('wp_ajax_backup_guard_storeSurveyResult', 'backup_guard_store_survey_result');
491
+ add_action('wp_ajax_backup_guard_reviewDontShow', 'backup_guard_review_dont_show');
492
+ add_action('wp_ajax_backup_guard_review_later', 'backup_guard_review_later');
493
+ add_action('wp_ajax_backup_guard_closeFreeBanner', 'wp_ajax_backup_guard_close_free_banner');
494
+ // related to cloud
495
+ add_action('wp_ajax_backup_guard_isBgUserExists', 'backup_guard_is_bg_user_exists');
496
+ add_action('wp_ajax_backup_guard_createCloudUser', 'backup_guard_create_cloud_user');
497
+ add_action('wp_ajax_backup_guard_bgAutoLogin', 'backup_guard_bg_auto_login');
498
+ add_action('wp_ajax_backup_guard_bgLogin', 'backup_guard_bg_login');
499
+ add_action('wp_ajax_backup_guard_chooseProfile', 'backup_guard_choose_profile');
500
+ }
501
+ }
502
+
503
+ function wp_ajax_backup_guard_close_free_banner()
504
+ {
505
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
506
+ SGConfig::set('SG_CLOSE_FREE_BANNER', 1);
507
+ wp_die();
508
+ }
509
+
510
+ function backup_guard_review_dont_show()
511
+ {
512
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
513
+ SGConfig::set('closeReviewBanner', 1);
514
+ wp_die();
515
+ }
516
+
517
+ function backup_guard_review_later()
518
+ {
519
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
520
+ require_once(SG_PUBLIC_AJAX_PATH.'reviewBannerActions.php');
521
+ wp_die();
522
+ }
523
+
524
+ function backup_guard_choose_profile()
525
+ {
526
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
527
+ require_once(SG_PUBLIC_AJAX_PATH.'chooseProfile.php');
528
+ }
529
+
530
+ function backup_guard_bg_login()
531
+ {
532
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
533
+ require_once(SG_PUBLIC_AJAX_PATH.'bgLogin.php');
534
+ }
535
+
536
+ function backup_guard_bg_auto_login()
537
+ {
538
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
539
+ require_once(SG_PUBLIC_AJAX_PATH.'bgAutoLogin.php');
540
+ }
541
+
542
+ function backup_guard_create_cloud_user()
543
+ {
544
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
545
+ require_once(SG_PUBLIC_AJAX_PATH.'createCloudUser.php');
546
+ }
547
+
548
+ function backup_guard_is_bg_user_exists()
549
+ {
550
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
551
+ require_once(SG_PUBLIC_AJAX_PATH.'isBgUserExists.php');
552
+ }
553
+
554
+ function backup_guard_store_survey_result()
555
+ {
556
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
557
+ require_once(SG_PUBLIC_AJAX_PATH.'storeSurveyResult.php');
558
+ }
559
+
560
+ function backup_guard_store_subscriber_info()
561
+ {
562
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
563
+ require_once(SG_PUBLIC_AJAX_PATH.'storeSubscriberInfo.php');
564
+ }
565
+
566
+ function backup_guard_set_user_info_verification_popup_state()
567
+ {
568
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
569
+ require_once(SG_PUBLIC_AJAX_PATH.'setUserInfoVerificationPopupState.php');
570
+ }
571
+
572
+ function backup_guard_dismiss_discount_notice()
573
+ {
574
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
575
+ require_once(SG_PUBLIC_AJAX_PATH.'dismissDiscountNotice.php');
576
+ }
577
+
578
+ function backup_guard_is_feature_available()
579
+ {
580
+ require_once(SG_PUBLIC_AJAX_PATH.'isFeatureAvailable.php');
581
+ }
582
+
583
+ function backup_guard_check_free_migration()
584
+ {
585
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
586
+ require_once(SG_PUBLIC_AJAX_PATH.'checkFreeMigration.php');
587
+ die;
588
+ }
589
+
590
+ function backup_guard_check_php_version_compatibility()
591
+ {
592
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
593
+ require_once(SG_PUBLIC_AJAX_PATH.'checkPHPVersionCompatibility.php');
594
+ }
595
+
596
+ add_action('init', 'backup_guard_init');
597
+ add_action('wp_ajax_nopriv_backup_guard_awake', 'backup_guard_awake_nopriv');
598
+ add_action('admin_post_backup_guard_cloudDropbox', 'backup_guard_cloud_dropbox');
599
+
600
+ function backup_guard_import_key_file()
601
+ {
602
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
603
+ require_once(SG_PUBLIC_AJAX_PATH.'importKeyFile.php');
604
+ }
605
+
606
+ function backup_guard_awake()
607
+ {
608
+ $method = SG_RELOAD_METHOD_AJAX;
609
+ require_once(SG_PUBLIC_AJAX_PATH.'awake.php');
610
+ }
611
+
612
+ function backup_guard_awake_nopriv()
613
+ {
614
+ $token = @$_GET['token'];
615
+ $method = @$_GET['method'];
616
+
617
+ if (backupGuardValidateApiCall($token)) {
618
+ require_once(SG_PUBLIC_AJAX_PATH.'awake.php');
619
+ }
620
+ }
621
+
622
+ function backup_guard_cancel_download()
623
+ {
624
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
625
+ require_once(SG_PUBLIC_AJAX_PATH.'cancelDownload.php');
626
+ }
627
+
628
+ function backup_guard_list_storage()
629
+ {
630
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
631
+ require_once(SG_PUBLIC_AJAX_PATH.'listStorage.php');
632
+ }
633
+
634
+ function backup_guard_download_from_cloud()
635
+ {
636
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
637
+ require_once(SG_PUBLIC_AJAX_PATH.'downloadFromCloud.php');
638
+ }
639
+
640
+ function backup_guard_hide_notice()
641
+ {
642
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
643
+ require_once(SG_PUBLIC_AJAX_PATH.'hideNotice.php');
644
+ }
645
+
646
+ function backup_guard_cancel_backup()
647
+ {
648
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
649
+ require_once(SG_PUBLIC_AJAX_PATH.'cancelBackup.php');
650
+ }
651
+
652
+ function backup_guard_check_backup_creation()
653
+ {
654
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
655
+ require_once(SG_PUBLIC_AJAX_PATH.'checkBackupCreation.php');
656
+ }
657
+
658
+ function backup_guard_check_restore_creation()
659
+ {
660
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
661
+ require_once(SG_PUBLIC_AJAX_PATH.'checkRestoreCreation.php');
662
+ }
663
+
664
+ function backup_guard_cloud_dropbox()
665
+ {
666
+ if (current_user_can('activate_plugins') || (defined('SG_USER_MODE') && SG_USER_MODE)) {
667
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
668
+ require_once(SG_PUBLIC_AJAX_PATH . 'cloudDropbox.php');
669
+ }
670
+ }
671
+
672
+ function backup_guard_send_usage_status()
673
+ {
674
+
675
+ if (current_user_can('activate_plugins') || (defined('SG_USER_MODE') && SG_USER_MODE)) {
676
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
677
+ require_once(SG_PUBLIC_AJAX_PATH . 'sendUsageStatus.php');
678
+ }
679
+ }
680
+
681
+ function backup_guard_curl_checker()
682
+ {
683
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
684
+ require_once(SG_PUBLIC_AJAX_PATH.'curlChecker.php');
685
+ }
686
+
687
+ function backup_guard_delete_backup()
688
+ {
689
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
690
+ require_once(SG_PUBLIC_AJAX_PATH.'deleteBackup.php');
691
+ }
692
+
693
+ function backup_guard_download_backup()
694
+ {
695
+ require_once(SG_PUBLIC_AJAX_PATH.'downloadBackup.php');
696
+ }
697
+
698
+ function backup_guard_get_action()
699
+ {
700
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
701
+ require_once(SG_PUBLIC_AJAX_PATH.'getAction.php');
702
+ }
703
+
704
+ function backup_guard_get_running_actions()
705
+ {
706
+ require_once(SG_PUBLIC_AJAX_PATH.'getRunningActions.php');
707
+ }
708
+
709
+ function backup_guard_get_import_backup()
710
+ {
711
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
712
+ require_once(SG_PUBLIC_AJAX_PATH.'importBackup.php');
713
+ }
714
+
715
+ function backup_guard_manual_backup()
716
+ {
717
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
718
+ require_once(SG_PUBLIC_AJAX_PATH.'manualBackup.php');
719
+ }
720
+
721
+ function backup_guard_reset_status()
722
+ {
723
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
724
+ require_once(SG_PUBLIC_AJAX_PATH.'resetStatus.php');
725
+ }
726
+
727
+ function backup_guard_restore()
728
+ {
729
+ require_once(SG_PUBLIC_AJAX_PATH.'restore.php');
730
+ }
731
+
732
+ function backup_guard_save_cloud_folder()
733
+ {
734
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
735
+ require_once(SG_PUBLIC_AJAX_PATH.'saveCloudFolder.php');
736
+ }
737
+
738
+ function backup_guard_schedule()
739
+ {
740
+ require_once(SG_PUBLIC_AJAX_PATH.'schedule.php');
741
+ }
742
+
743
+ function backup_guard_settings()
744
+ {
745
+ require_once(SG_PUBLIC_AJAX_PATH.'settings.php');
746
+ }
747
+
748
+ function backup_guard_set_review_popup_state()
749
+ {
750
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
751
+ require_once(SG_PUBLIC_AJAX_PATH.'setReviewPopupState.php');
752
+ }
753
+
754
+ function backup_guard_send_usage_statistics()
755
+ {
756
+ require_once(SG_PUBLIC_AJAX_PATH.'sendUsageStatistics.php');
757
+ }
758
+
759
+ function backup_guard_login()
760
+ {
761
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
762
+ require_once(SG_PUBLIC_AJAX_PATH.'login.php');
763
+ }
764
+
765
+ function backup_guard_logout()
766
+ {
767
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
768
+ require_once(SG_PUBLIC_AJAX_PATH.'logout.php');
769
+ }
770
+
771
+ function backup_guard_link_license()
772
+ {
773
+ check_ajax_referer('backupGuardAjaxNonce', 'token');
774
+ require_once(SG_PUBLIC_AJAX_PATH.'linkLicense.php');
775
+ }
776
+
777
+ //adds once weekly to the existing schedules.
778
+ add_filter('cron_schedules', 'backup_guard_cron_add_weekly');
779
+ function backup_guard_cron_add_weekly($schedules)
780
+ {
781
+ $schedules['weekly'] = array(
782
+ 'interval' => 60*60*24*7,
783
+ 'display' => 'Once weekly'
784
+ );
785
+ return $schedules;
786
+ }
787
+
788
+ //adds once monthly to the existing schedules.
789
+ add_filter('cron_schedules', 'backup_guard_cron_add_monthly');
790
+ function backup_guard_cron_add_monthly($schedules)
791
+ {
792
+ $schedules['monthly'] = array(
793
+ 'interval' => 60*60*24*30,
794
+ 'display' => 'Once monthly'
795
+ );
796
+ return $schedules;
797
+ }
798
+
799
+ //adds once yearly to the existing schedules.
800
+ add_filter('cron_schedules', 'backup_guard_cron_add_yearly');
801
+ function backup_guard_cron_add_yearly($schedules)
802
+ {
803
+ $schedules['yearly'] = array(
804
+ 'interval' => 60*60*24*30*12,
805
+ 'display' => 'Once yearly'
806
+ );
807
+ return $schedules;
808
+ }
809
+
810
+ function backup_guard_init()
811
+ {
812
+ backup_guard_register_ajax_callbacks();
813
+ // backupGuardPluginRedirect();
814
+
815
+ //check if database should be updated
816
+ if (backupGuardShouldUpdate()) {
817
+ SGBoot::install();
818
+ }
819
+
820
+ backupGuardSymlinksCleanup(SG_SYMLINK_PATH);
821
+ }
822
+
823
+ add_action(SG_SCHEDULE_ACTION, 'backup_guard_schedule_action', 10, 1);
824
+
825
+ function backup_guard_schedule_action($id)
826
+ {
827
+ require_once(SG_PUBLIC_PATH.'cron/sg_backup.php');
828
+ }
829
+
830
+ function sgBackupAdminInit() {
831
+ //load pro plugin updater
832
+ $pluginCapabilities = backupGuardGetCapabilities();
833
+ $isLoggedIn = is_user_logged_in();
834
+
835
+ if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE && $isLoggedIn) {
836
+ require_once(dirname(__FILE__).'/plugin-update-checker/plugin-update-checker.php');
837
+ require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/Utils.php');
838
+ require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/UpdateChecker.php');
839
+ require_once(dirname(__FILE__).'/plugin-update-checker/Puc/v4/Scheduler.php');
840
+ require_once(SG_LIB_PATH.'SGAuthClient.php');
841
+
842
+ $licenseKey = SGConfig::get('SG_LICENSE_KEY');
843
+
844
+ $updateChecker = Puc_v4_Factory::buildUpdateChecker(
845
+ BackupGuard\Config::URL.'/products/details/'.$licenseKey,
846
+ SG_BACKUP_GUARD_MAIN_FILE,
847
+ SG_PRODUCT_IDENTIFIER
848
+ );
849
+
850
+ $updateChecker->addHttpRequestArgFilter(array(
851
+ SGAuthClient::getInstance(),
852
+ 'filterUpdateChecks'
853
+ ));
854
+ }
855
+
856
+ require_once(SG_LIB_PATH.'SGStatsRequests.php');
857
+ SGStatsRequests::initialSync();
858
+ }
859
+
860
+ add_action('admin_init', 'sgBackupAdminInit');
861
+
862
+ if (SGBoot::isFeatureAvailable('ALERT_BEFORE_UPDATE')) {
863
+ add_filter('upgrader_pre_download', 'backupGuardOnBeforeUpdateDownload', 10, 3);
864
+ add_action('core_upgrade_preamble', 'backupGuardOnUpgradeScreenActivate');
865
+ add_action('current_screen', 'backupGuardOnScreenActivate');
866
+ }
867
+
868
+ // Register the new dashboard widget with the 'wp_dashboard_setup' action
869
+ add_action('wp_dashboard_setup', 'backup_guard_add_dashboard_widgets');
870
+
871
+ function backup_guard_add_dashboard_widgets()
872
+ {
873
+ require_once(SG_CORE_PATH.'SGConfig.php');
874
+
875
+ $userId = get_current_user_id();
876
+ $userData = get_userdata($userId);
877
+ $userRoles = $userData->roles;
878
+ $isAdminUser = false;
879
+ for($i = 0; $i < count($userRoles); $i++) {
880
+ if ($userRoles[$i] == "administrator") {
881
+ $isAdminUser = true;
882
+ break;
883
+ }
884
+ }
885
+
886
+ if (!$isAdminUser ) {
887
+ return;
888
+ }
889
+
890
+ $isShowStatisticsWidgetEnabled = SGConfig::get('SG_SHOW_STATISTICS_WIDGET');
891
+ if (!$isShowStatisticsWidgetEnabled) {
892
+ return;
893
+ }
894
+
895
+
896
+ require_once(plugin_dir_path( __FILE__ ).'public/dashboardWidget.php');
897
+ wp_add_dashboard_widget('backupGuardWidget', 'Backup Guard', 'backup_guard_dashboard_widget_function');
898
+ }
899
+
900
+ add_action('plugins_loaded', 'backupGuardloadTextDomain');
901
+ function backupGuardloadTextDomain()
902
+ {
903
+ $backupGuardLangDir = plugin_dir_path(__FILE__).'languages/';
904
+ $backupGuardLangDir = apply_filters('backupguardLanguagesDirectory', $backupGuardLangDir);
905
+
906
+ $locale = apply_filters('bg_plugin_locale', get_locale(), BACKUP_GUARD_TEXTDOMAIN);
907
+ $mofile = sprintf('%1$s-%2$s.mo', BACKUP_GUARD_TEXTDOMAIN, $locale);
908
+
909
+ $mofileLocal = $backupGuardLangDir.$mofile;
910
+
911
+ if (file_exists($mofileLocal)) {
912
+ // Look in local /wp-content/plugins/popup-builder/languages/ folder
913
+ load_textdomain(BACKUP_GUARD_TEXTDOMAIN, $mofileLocal);
914
+ }
915
+ else {
916
+ // Load the default language files
917
+ load_plugin_textdomain(BACKUP_GUARD_TEXTDOMAIN, false, $backupGuardLangDir);
918
+ }
919
+ }
920
+
921
+ if (backupGuardShouldShowDiscountNotice() && checkDueDateDiscount()) {
922
+ add_action('admin_notices', 'backup_guard_discount_notice');
923
+ }
924
+
925
+ function backup_guard_discount_notice()
926
+ {
927
+ $capabilities = backupGuardGetCapabilities();
928
+ $upgradeUrl = BG_UPGRADE_URL;
929
+ ?>
930
+ <div class="backup-guard-discount-notice updated notice is-dismissible">
931
+ <div class="sgbg-col sgbg-col1"></div>
932
+ <div class="sgbg-col sgbg-col2"></div>
933
+ <div class="sgbg-col sgbg-col3">
934
+ <div class="sgbg-text-col-1">
935
+ -50%
936
+ </div>
937
+ <div class="sgbg-text-col-2">
938
+ <div class="sgbg-discount-text-1">Discount</div>
939
+ <div class="sgbg-discount-text-2">All Backup Guard Solutions</div>
940
+ </div>
941
+ </div>
942
+ <div class="sgbg-col sgbg-col4">
943
+ <a href="https://backup-guard.com/products/backup-wordpress" target="_blank"><button class="sgbg-button">Click Here</button></a>
944
+ </div>
945
+ </div>
946
+ <style>
947
+ .backup-guard-discount-notice.updated.notice.is-dismissible {
948
+ padding: 0;
949
+ border-left-color: #FFFFFF !important;
950
+ background-color: #000000;
951
+ height: 160px;
952
+ }
953
+ .backup-guard-discount-notice button:before {
954
+ color: #ffffff !important;
955
+ }
956
+ .sgbg-col {
957
+ display: inline-block;
958
+ width: 25%;
959
+ height: 100%;
960
+ padding: 0 25px;
961
+ box-sizing: border-box;
962
+ }
963
+ .sgbg-col1 {
964
+ width: 10%;
965
+ background-color: #FFFFFF;
966
+ background-image: url("<?php echo SG_IMAGE_URL ?>BgBFLogo.jpg");
967
+ background-size: 80%;
968
+ background-repeat: no-repeat;
969
+ background-position: center;
970
+ }
971
+ .sgbg-col2 {
972
+ width: 20%;
973
+ background-image: url("<?php echo SG_IMAGE_URL ?>BF.png");
974
+ background-size: contain;
975
+ margin-left: 70px;
976
+ background-position: center;
977
+ background-repeat: no-repeat;
978
+ }
979
+ .sgbg-col3 {
980
+ vertical-align: top;
981
+ width: 45%;
982
+ margin-top: 55px;
983
+ }
984
+ .sgbg-col4 {
985
+ width: 10%;
986
+ }
987
+ .sgbg-text-col-1,
988
+ .sgbg-text-col-2 {
989
+ width: 49%;
990
+ display: inline-block;
991
+ color: #FFFFFF;
992
+ }
993
+ .sgbg-text-col-1 {
994
+ font-size: 100px;
995
+ line-height: 0;
996
+ font-weight: bold;
997
+ text-align: right;
998
+ padding-right: 26px;
999
+ box-sizing: border-box;
1000
+ }
1001
+ .sgbg-discount-text-2 {
1002
+ font-size: 19px;
1003
+ }
1004
+ .sgbg-discount-text-1 {
1005
+ font-size: 60px;
1006
+ padding-bottom: 27px;
1007
+ font-weight: bold;
1008
+ }
1009
+ .sgbg-col4 {
1010
+ vertical-align: top;
1011
+ }
1012
+ .sgbg-button {
1013
+ width: 183px;
1014
+ height: 67px;
1015
+ font-size: 20px;
1016
+ border: #ffffff;
1017
+ border-radius: 10px;
1018
+ margin-top: 48px;
1019
+ background-color: #FFFFFF;
1020
+ color: #000000;
1021
+ cursor: pointer !important;
1022
+ }
1023
+ .sgbg-button:hover {
1024
+ background-color: #000000;
1025
+ border: 1px solid #FFFFFF;
1026
+ color: #FFFFFF;
1027
+ }
1028
+ .backup-guard-discount-notice .notice-dismiss::before {
1029
+ content: "x";
1030
+ font-weight: 300;
1031
+ font-family: Arial, sans-serif;
1032
+ }
1033
+
1034
+ @media (max-width: 1810px) {
1035
+ .sgbg-text-col-1 {
1036
+ font-size: 80px;
1037
+ }
1038
+ .sgbg-discount-text-1 {
1039
+ font-size: 43px;
1040
+ }
1041
+ .sgbg-discount-text-2 {
1042
+ font-size: 15px;
1043
+ }
1044
+ .sgbg-discount-text-1 {
1045
+ padding-bottom: 18px;
1046
+ }
1047
+ .sgbg-col3 {
1048
+ margin-top: 60px;
1049
+ }
1050
+ }
1051
+ @media (max-width: 1477px) {
1052
+ .sgbg-discount-text-2 {
1053
+ font-size: 12px;
1054
+ }
1055
+ .sgbg-discount-text-1 {
1056
+ font-size: 35px;
1057
+ }
1058
+ .sgbg-discount-text-1 {
1059
+ padding-bottom: 13px;
1060
+ }
1061
+ .sgbg-col {
1062
+ padding: 0;
1063
+ }
1064
+ .sgbg-col2 {
1065
+ margin-left: 40px;
1066
+ }
1067
+ .sgbg-col2 {
1068
+ margin-left: 0;
1069
+ }
1070
+ }
1071
+ </style>
1072
+ <?php
1073
+ }
1074
+
1075
+ add_action('admin_notices', 'backup_guard_review_banner');
1076
+ function backup_guard_review_banner()
1077
+ {
1078
+ require_once(SG_LIB_PATH.'SGReviewManager.php');
1079
+ $reviewManager = new SGReviewManager();
1080
+ $reviewManager->renderContent();
1081
+ }
README.txt CHANGED
@@ -6,7 +6,7 @@ Donate link: https://backup-guard.com/products/backup-wordpress
6
  Tags: backup, wordpress backup plugin, backup plugin, database backup, migrate, back up
7
  Requires at least: 3.9
8
  Tested up to: 5.6
9
- Stable tag: 1.5.8
10
  License: GPLv2 or later
11
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
12
 
@@ -14,15 +14,15 @@ Backup site, restore or migrate it wherever you need it. Backup to Dropbox, Goog
14
 
15
  == Description ==
16
 
17
- Backup Guard is the most complete WordPress backup plugin. We offer the easiest way to <strong>Backup</strong>, <strong>Restore</strong> and <strong>Migrate</strong> your WordPress website. You can backup and restore your WordPress files, database or both.
18
 
19
  <p>Download <strong>BackupGuard Pro</strong> here: <a href="https://backup-guard.com/products/backup-wordpress">https://backup-guard.com/products/backup-wordpress</a></p>
20
 
21
  https://www.youtube.com/watch?v=HCz4mkMMXos
22
 
23
- <h4>Free backup features</h4>
24
  <ul>
25
- <li>Backup site - backup site as many times as you want</li>
26
  <li>Backup files, database or both</li>
27
  <li>Choose which folders to backup</li>
28
  <li>Choose which database tables to backup</li>
@@ -42,7 +42,7 @@ https://www.youtube.com/watch?v=HCz4mkMMXos
42
 
43
  See <strong>BackupGuard Free</strong> in action here: <a href="https://www.youtube.com/watch?v=nt6XoP69c0M">https://www.youtube.com/watch?v=nt6XoP69c0M</a>
44
 
45
- <h4>Pro backup features</h4>
46
  <ul>
47
  <li><strong>Migrate site</strong> - migrate site from one domain to another</li>
48
  <li>Fully automatic migration - no any <strong>find & replace</strong> rules are required for migration</li>
@@ -81,7 +81,7 @@ Backup Guard Pro will help you to skip all these problems because of its advance
81
  <h4>Documentation</h4>
82
  The documentation can be found here: <a href="https://backup-guard.com/products/backup-wordpress/doc">https://backup-guard.com/products/backup-wordpress/doc</a>
83
 
84
- <h4>This is how backup operates</h4>
85
  <ul>
86
  <li>No extra libraries required</li>
87
  <li>Support of large websites</li>
@@ -167,6 +167,15 @@ When you are facing an issue of any kind with any of our products, the first thi
167
  6. Site backup customization
168
 
169
  == Changelog ==
 
 
 
 
 
 
 
 
 
170
  = 1.5.8 =
171
  * Deactivation survey removed
172
  * PHP 8 related fixes
@@ -204,7 +213,7 @@ When you are facing an issue of any kind with any of our products, the first thi
204
 
205
  = 1.5.0 =
206
  * Fixed the database restore process failure which was caused by the backup tree file
207
-
208
  = 1.4.9 =
209
  * Fixed messages
210
 
@@ -217,7 +226,7 @@ When you are facing an issue of any kind with any of our products, the first thi
217
  * Improvement of BackupGuard sidebar menu
218
 
219
  = 1.4.6 =
220
- * "Send usage data" setting addition
221
  * Support section improvement
222
 
223
  = 1.4.5 =
@@ -260,7 +269,7 @@ When you are facing an issue of any kind with any of our products, the first thi
260
 
261
  = 1.3.5 =
262
  * A possibility to close/dismiss the plugin admin panel banner
263
-
264
  = 1.3.4 =
265
  * Admin side improvement
266
 
@@ -693,4 +702,4 @@ Now, when pressing on the button only one backup will be implemented.
693
  * Minor backup related bug fixes
694
 
695
  = 1.0 =
696
- * Initial backup plugin was commit
6
  Tags: backup, wordpress backup plugin, backup plugin, database backup, migrate, back up
7
  Requires at least: 3.9
8
  Tested up to: 5.6
9
+ Stable tag: 1.6.0
10
  License: GPLv2 or later
11
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
12
 
14
 
15
  == Description ==
16
 
17
+ Backup Guard is the most complete WordPress backup plugin. We offer the easiest way to <strong>Restore</strong>, <strong>Migrate</strong> and <strong>Backup</strong> WordPress website. You can backup and restore your WordPress files, database or both.
18
 
19
  <p>Download <strong>BackupGuard Pro</strong> here: <a href="https://backup-guard.com/products/backup-wordpress">https://backup-guard.com/products/backup-wordpress</a></p>
20
 
21
  https://www.youtube.com/watch?v=HCz4mkMMXos
22
 
23
+ <h4>FREE BACKUP WORDPRESS PLUGIN FEATURES</h4>
24
  <ul>
25
+ <li>Backup WordPress site - backup site as many times as you want</li>
26
  <li>Backup files, database or both</li>
27
  <li>Choose which folders to backup</li>
28
  <li>Choose which database tables to backup</li>
42
 
43
  See <strong>BackupGuard Free</strong> in action here: <a href="https://www.youtube.com/watch?v=nt6XoP69c0M">https://www.youtube.com/watch?v=nt6XoP69c0M</a>
44
 
45
+ <h4>PRO BACKUP WORDPRESS PLUGIN FEATURES</h4>
46
  <ul>
47
  <li><strong>Migrate site</strong> - migrate site from one domain to another</li>
48
  <li>Fully automatic migration - no any <strong>find & replace</strong> rules are required for migration</li>
81
  <h4>Documentation</h4>
82
  The documentation can be found here: <a href="https://backup-guard.com/products/backup-wordpress/doc">https://backup-guard.com/products/backup-wordpress/doc</a>
83
 
84
+ <h4>THIS IS HOW WORDPRESS BACKUP PLUGIN OPERATES</h4>
85
  <ul>
86
  <li>No extra libraries required</li>
87
  <li>Support of large websites</li>
167
  6. Site backup customization
168
 
169
  == Changelog ==
170
+ = 1.6.0 =
171
+ * Bug fixed related to security issues
172
+
173
+ = 1.5.9 =
174
+ * Improvement of Schedules section, scheduled backups should work for both WP Cron's enabled and disabled states
175
+ * Improvement of UI, popups are temporary disabled
176
+ * Improvement of plugin's separate sections' links, links are changing on page clicks
177
+ * Bug fixed related to Delete button, when bulk action is selected
178
+
179
  = 1.5.8 =
180
  * Deactivation survey removed
181
  * PHP 8 related fixes
213
 
214
  = 1.5.0 =
215
  * Fixed the database restore process failure which was caused by the backup tree file
216
+
217
  = 1.4.9 =
218
  * Fixed messages
219
 
226
  * Improvement of BackupGuard sidebar menu
227
 
228
  = 1.4.6 =
229
+ * "Send usage data" setting addition
230
  * Support section improvement
231
 
232
  = 1.4.5 =
269
 
270
  = 1.3.5 =
271
  * A possibility to close/dismiss the plugin admin panel banner
272
+
273
  = 1.3.4 =
274
  * Admin side improvement
275
 
702
  * Minor backup related bug fixes
703
 
704
  = 1.0 =
705
+ * Initial backup plugin was commit
backup.php CHANGED
@@ -4,7 +4,7 @@
4
  * Plugin Name: Backup
5
  * Plugin URI: https://backup-guard.com/products/backup-wordpress
6
  * Description: Backup Guard is the most complete site backup and restore plugin. We offer the easiest way to backup, restore or migrate your site. You can backup your files, database or both.
7
- * Version: 1.5.8
8
  * Author: BackupGuard
9
  * Author URI: https://backup-guard.com/products/backup-wordpress
10
  * License: GPL-2.0+
@@ -16,7 +16,7 @@ if (function_exists('activate_backup_guard')) {
16
  }
17
 
18
  if (!defined('SG_BACKUP_GUARD_VERSION')) {
19
- define('SG_BACKUP_GUARD_VERSION', '1.5.8');
20
  }
21
 
22
  if (!defined('SG_BACKUP_GUARD_MAIN_FILE')) {
4
  * Plugin Name: Backup
5
  * Plugin URI: https://backup-guard.com/products/backup-wordpress
6
  * Description: Backup Guard is the most complete site backup and restore plugin. We offer the easiest way to backup, restore or migrate your site. You can backup your files, database or both.
7
+ * Version: 1.6.0
8
  * Author: BackupGuard
9
  * Author URI: https://backup-guard.com/products/backup-wordpress
10
  * License: GPL-2.0+
16
  }
17
 
18
  if (!defined('SG_BACKUP_GUARD_VERSION')) {
19
+ define('SG_BACKUP_GUARD_VERSION', '1.6.0');
20
  }
21
 
22
  if (!defined('SG_BACKUP_GUARD_MAIN_FILE')) {
com/core/SGBoot.php CHANGED
@@ -1,308 +1,311 @@
1
- <?php
2
- //check PHP version
3
- if (version_compare(PHP_VERSION, '5.3.3', '<')) {
4
- die('PHP >=5.3.3 version required.');
5
- }
6
-
7
- require_once(SG_EXCEPTION_PATH.'SGException.php');
8
- require_once(SG_CORE_PATH.'functions.php');
9
- backupGuardIncludeFile(SG_CORE_PATH.'functions.silver.php');
10
- backupGuardIncludeFile(SG_CORE_PATH.'functions.gold.php');
11
- backupGuardIncludeFile(SG_CORE_PATH.'functions.platinum.php');
12
- require_once(SG_CORE_PATH.'SGPing.php');
13
- require_once(SG_DATABASE_PATH.'SGDatabase.php');
14
- require_once(SG_CORE_PATH.'SGConfig.php');
15
- require_once(SG_NOTICE_PATH.'SGNotice.php');
16
- require_once(SG_NOTICE_PATH.'SGNoticeHandler.php');
17
- backupGuardIncludeFile(SG_BACKUP_PATH.'SGBackupSchedule.php');
18
- backupGuardIncludeFile(SG_EXTENSION_PATH.'SGExtension.php');
19
-
20
- class SGBoot
21
- {
22
- public static $executionTimeLimit = 0;
23
- public static $memoryLimit = 0;
24
-
25
- public static function init()
26
- {
27
- //get current execution time limit
28
- self::$executionTimeLimit = ini_get('max_execution_time');
29
-
30
- //get current memory limit
31
- self::$memoryLimit = ini_get('memory_limit');
32
-
33
- //remove execution time limit
34
- @ini_set('max_execution_time', 0);
35
-
36
- //change initial memory limit
37
- @ini_set('memory_limit', '512M');
38
-
39
- //don't let server to abort scripts
40
- @ignore_user_abort(true);
41
-
42
- //load all config variables from database
43
- SGConfig::getAll();
44
-
45
- try {
46
- //check minimum requirements
47
- self::checkMinimumRequirements();
48
-
49
- //prepare directory for backups
50
- self::prepare();
51
- }
52
- catch (SGException $exception) {
53
- die($exception);
54
- }
55
- }
56
-
57
- public static function didInstallForFirstTime()
58
- {
59
- self::setPluginInstallUpdateDate();
60
- }
61
-
62
- public static function didUpdatePluginVersion()
63
- {
64
- self::setPluginInstallUpdateDate();
65
- }
66
-
67
- public static function setPluginInstallUpdateDate()
68
- {
69
- SGConfig::set('SG_PLUGIN_INSTALL_UPDATE_DATE', time());
70
- }
71
-
72
- private static function installConfigTable($sgdb)
73
- {
74
- $dbEngine = backupGuardGetDatabaseEngine();
75
- //create config table
76
- $res = $sgdb->query(
77
- 'CREATE TABLE IF NOT EXISTS `'.SG_CONFIG_TABLE_NAME.'` (
78
- `ckey` varchar(100) NOT NULL,
79
- `cvalue` text NOT NULL,
80
- PRIMARY KEY (`ckey`)
81
- ) ENGINE='.$dbEngine.' DEFAULT CHARSET=utf8;'
82
- );
83
- if ($res===false) {
84
- return false;
85
- }
86
-
87
- //delete all content from config table (just in case if wasn't dropped)
88
- $sgdb->query('DELETE FROM `'.SG_CONFIG_TABLE_NAME.'`;');
89
-
90
- //populate config table
91
- $res = $sgdb->query(
92
- "INSERT INTO `".SG_CONFIG_TABLE_NAME."` VALUES
93
- ('SG_BACKUP_GUARD_VERSION','".SG_BACKUP_GUARD_VERSION."'),
94
- ('SG_BACKUP_WITH_RELOADINGS', '1'),
95
- ('SG_BACKUP_SYNCHRONOUS_STORAGE_UPLOAD','1'),
96
- ('SG_NOTIFICATIONS_ENABLED','0'),
97
- ('SG_SHOW_STATISTICS_WIDGET','1'),
98
- ('SG_BACKUP_SEND_USAGE_STATUS','0'),
99
- ('SG_NOTIFICATIONS_EMAIL_ADDRESS',''),
100
- ('SG_STORAGE_BACKUPS_FOLDER_NAME','sg_backups');"
101
- );
102
- if ($res===false) {
103
- return false;
104
- }
105
-
106
- return true;
107
- }
108
-
109
- private static function installScheduleTable($sgdb)
110
- {
111
- $dbEngine = backupGuardGetDatabaseEngine();
112
-
113
- //create schedule table
114
- $res = $sgdb->query(
115
- 'CREATE TABLE IF NOT EXISTS `'.SG_SCHEDULE_TABLE_NAME.'` (
116
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
117
- `label` varchar(255) NOT NULL,
118
- `status` tinyint(3) unsigned NOT NULL,
119
- `schedule_options` varchar(255) NOT NULL,
120
- `backup_options` text NOT NULL,
121
- PRIMARY KEY (`id`)
122
- ) ENGINE='.$dbEngine.' DEFAULT CHARSET=utf8;'
123
- );
124
- if ($res===false) {
125
- return false;
126
- }
127
-
128
- return true;
129
- }
130
-
131
- private static function installActionTable($sgdb)
132
- {
133
- $dbEngine = backupGuardGetDatabaseEngine();
134
-
135
- //create action table
136
- $res = $sgdb->query(
137
- "CREATE TABLE IF NOT EXISTS `".SG_ACTION_TABLE_NAME."` (
138
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
139
- `name` varchar(255) NOT NULL,
140
- `type` tinyint(3) unsigned NOT NULL,
141
- `subtype` tinyint(3) unsigned NOT NULL DEFAULT '0',
142
- `status` tinyint(3) unsigned NOT NULL,
143
- `progress` tinyint(3) unsigned NOT NULL DEFAULT '0',
144
- `start_date` datetime NOT NULL,
145
- `update_date` datetime DEFAULT NULL,
146
- `options` text NOT NULL,
147
- PRIMARY KEY (`id`)
148
- ) ENGINE=".$dbEngine." DEFAULT CHARSET=utf8;"
149
- );
150
- if ($res===false) {
151
- return false;
152
- }
153
-
154
- return true;
155
- }
156
-
157
- public static function install()
158
- {
159
- $sgdb = SGDatabase::getInstance();
160
-
161
- try {
162
- if (!self::installConfigTable($sgdb)) {
163
- throw new SGExceptionDatabaseError('Could not install config table');
164
- }
165
-
166
- if (!self::installScheduleTable($sgdb)) {
167
- throw new SGExceptionDatabaseError('Could not install schedule table');
168
- }
169
-
170
- if (!self::installActionTable($sgdb)) {
171
- throw new SGExceptionDatabaseError('Could not install action table');
172
- }
173
-
174
- self::installReviewSettings();
175
- }
176
- catch (SGException $exception) {
177
- die($exception);
178
- }
179
- }
180
-
181
- private static function installReviewSettings()
182
- {
183
- $usageDays = SGConfig::get('usageDays');
184
- if (!$usageDays) {
185
- SGConfig::set('usageDays', 0);
186
-
187
- $timeDate = new \DateTime('now');
188
- $installTime = strtotime($timeDate->format('Y-m-d H:i:s'));
189
- SGConfig::set('installDate', $installTime);
190
- $timeDate->modify('+'.SG_BACKUP_REVIEW_PERIOD.' day');
191
-
192
- $timeNow = strtotime($timeDate->format('Y-m-d H:i:s'));
193
- SGConfig::set('openNextTime', $timeNow);
194
- }
195
- $backupCountReview = SGConfig::get('backupReviewCount');
196
- if (!$backupCountReview) {
197
- SGConfig::set('backupReviewCount', SG_BACKUP_REVIEW_BACKUP_COUNT);
198
- }
199
-
200
- $restoreReviewCount = SGConfig::get('restoreReviewCount');
201
- if (!$restoreReviewCount) {
202
- SGConfig::set('restoreReviewCount', SG_BACKUP_REVIEW_RESTORE_COUNT);
203
- }
204
- }
205
-
206
- private static function cleanupSchedules()
207
- {
208
- $schedules = SGBackupSchedule::getAllSchedules();
209
- foreach ($schedules as $schedule) {
210
- SGBackupSchedule::remove($schedule['id']);
211
- }
212
- }
213
-
214
- public static function uninstall($deleteBackups = false)
215
- {
216
- try {
217
- @unlink(SG_PING_FILE_PATH);
218
-
219
- if (self::isFeatureAvailable('SCHEDULE')) {
220
- self::cleanupSchedules();
221
- }
222
-
223
- $sgdb = SGDatabase::getInstance();
224
-
225
- //drop config table
226
- $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_CONFIG_TABLE_NAME.'`;');
227
- if ($res===false) {
228
- throw new SGExceptionDatabaseError('Could not execute query');
229
- }
230
-
231
- //drop schedule table
232
- $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_SCHEDULE_TABLE_NAME.'`;');
233
- if ($res===false) {
234
- throw new SGExceptionDatabaseError('Could not execute query');
235
- }
236
-
237
- //drop action table
238
- $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_ACTION_TABLE_NAME.'`;');
239
- if ($res===false) {
240
- throw new SGExceptionDatabaseError('Could not execute query');
241
- }
242
-
243
- //delete directory of backups
244
- if ($deleteBackups) {
245
- $backupPath = SGConfig::get('SG_BACKUP_DIRECTORY');
246
- backupGuardDeleteDirectory($backupPath);
247
- }
248
- }
249
- catch (SGException $exception) {
250
- die($exception);
251
- }
252
- }
253
-
254
- public static function checkRequirement($requirement)
255
- {
256
- if ($requirement=='ftp' && !extension_loaded('ftp')) {
257
- throw new SGExceptionNotFound('FTP extension is not loaded.');
258
- }
259
- else if ($requirement=='curl' && !function_exists('curl_version')) {
260
- throw new SGExceptionNotFound('cURL extension is not loaded.');
261
- }
262
- else if ($requirement=='intSize' && PHP_INT_SIZE < 8) {
263
- throw new SGExceptionIO("BackupGuard uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . ")");
264
- }
265
- }
266
-
267
- public static function isFeatureAvailable($feature)
268
- {
269
- return ((int)SGConfig::get('SG_FEATURE_'.strtoupper($feature))===1?true:false);
270
- }
271
-
272
- private static function prepare()
273
- {
274
- $backupPath = SGConfig::get('SG_BACKUP_DIRECTORY');
275
-
276
- //create directory for backups
277
- if (!is_dir($backupPath)) {
278
- if (!@mkdir($backupPath)) {
279
- throw new SGExceptionMethodNotAllowed('Cannot create folder: '.$backupPath);
280
- }
281
-
282
- if (!@file_put_contents($backupPath.'.htaccess', 'deny from all')) {
283
- throw new SGExceptionMethodNotAllowed('Cannot create htaccess file');
284
- }
285
-
286
- if (!@file_put_contents($backupPath.'index.php', "<?php\n// Silence is golden")) {
287
- throw new SGExceptionMethodNotAllowed('Cannot create index file');
288
- }
289
- }
290
-
291
- //check permissions of backups directory
292
- if (!is_writable($backupPath)) {
293
- throw new SGExceptionForbidden('Permission denied. Directory is not writable: '.$backupPath);
294
- }
295
-
296
- //prepare notices
297
- $noticeHandler = new SGNoticeHandler();
298
- $noticeHandler->run();
299
- }
300
-
301
- private static function checkMinimumRequirements()
302
- {
303
- //check ZLib library
304
- if (!function_exists('gzdeflate')) {
305
- throw new SGExceptionNotFound('ZLib extension is not loaded.');
306
- }
307
- }
308
- }
 
 
 
1
+ <?php
2
+ //check PHP version
3
+ if (version_compare(PHP_VERSION, '5.3.3', '<')) {
4
+ die('PHP >=5.3.3 version required.');
5
+ }
6
+
7
+ require_once(SG_EXCEPTION_PATH.'SGException.php');
8
+ require_once(SG_CORE_PATH.'functions.php');
9
+ backupGuardIncludeFile(SG_CORE_PATH.'functions.silver.php');
10
+ backupGuardIncludeFile(SG_CORE_PATH.'functions.gold.php');
11
+ backupGuardIncludeFile(SG_CORE_PATH.'functions.platinum.php');
12
+ require_once(SG_CORE_PATH.'SGPing.php');
13
+ require_once(SG_DATABASE_PATH.'SGDatabase.php');
14
+ require_once(SG_CORE_PATH.'SGConfig.php');
15
+ require_once(SG_NOTICE_PATH.'SGNotice.php');
16
+ require_once(SG_NOTICE_PATH.'SGNoticeHandler.php');
17
+ backupGuardIncludeFile(SG_BACKUP_PATH.'SGBackupSchedule.php');
18
+ backupGuardIncludeFile(SG_EXTENSION_PATH.'SGExtension.php');
19
+
20
+ class SGBoot
21
+ {
22
+ public static $executionTimeLimit = 0;
23
+ public static $memoryLimit = 0;
24
+
25
+ public static function init()
26
+ {
27
+ //get current execution time limit
28
+ self::$executionTimeLimit = ini_get('max_execution_time');
29
+
30
+ //get current memory limit
31
+ self::$memoryLimit = ini_get('memory_limit');
32
+
33
+ //remove execution time limit
34
+ @ini_set('max_execution_time', 0);
35
+
36
+ //change initial memory limit
37
+ @ini_set('memory_limit', '512M');
38
+
39
+ //don't let server to abort scripts
40
+ @ignore_user_abort(true);
41
+
42
+ //load all config variables from database
43
+ SGConfig::getAll();
44
+
45
+ // TODO: remove and check banners logic
46
+ SGConfig::set('closeReviewBanner', 1);
47
+
48
+ try {
49
+ //check minimum requirements
50
+ self::checkMinimumRequirements();
51
+
52
+ //prepare directory for backups
53
+ self::prepare();
54
+ }
55
+ catch (SGException $exception) {
56
+ die($exception);
57
+ }
58
+ }
59
+
60
+ public static function didInstallForFirstTime()
61
+ {
62
+ self::setPluginInstallUpdateDate();
63
+ }
64
+
65
+ public static function didUpdatePluginVersion()
66
+ {
67
+ self::setPluginInstallUpdateDate();
68
+ }
69
+
70
+ public static function setPluginInstallUpdateDate()
71
+ {
72
+ SGConfig::set('SG_PLUGIN_INSTALL_UPDATE_DATE', time());
73
+ }
74
+
75
+ private static function installConfigTable($sgdb)
76
+ {
77
+ $dbEngine = backupGuardGetDatabaseEngine();
78
+ //create config table
79
+ $res = $sgdb->query(
80
+ 'CREATE TABLE IF NOT EXISTS `'.SG_CONFIG_TABLE_NAME.'` (
81
+ `ckey` varchar(100) NOT NULL,
82
+ `cvalue` text NOT NULL,
83
+ PRIMARY KEY (`ckey`)
84
+ ) ENGINE='.$dbEngine.' DEFAULT CHARSET=utf8;'
85
+ );
86
+ if ($res===false) {
87
+ return false;
88
+ }
89
+
90
+ //delete all content from config table (just in case if wasn't dropped)
91
+ $sgdb->query('DELETE FROM `'.SG_CONFIG_TABLE_NAME.'`;');
92
+
93
+ //populate config table
94
+ $res = $sgdb->query(
95
+ "INSERT INTO `".SG_CONFIG_TABLE_NAME."` VALUES
96
+ ('SG_BACKUP_GUARD_VERSION','".SG_BACKUP_GUARD_VERSION."'),
97
+ ('SG_BACKUP_WITH_RELOADINGS', '1'),
98
+ ('SG_BACKUP_SYNCHRONOUS_STORAGE_UPLOAD','1'),
99
+ ('SG_NOTIFICATIONS_ENABLED','0'),
100
+ ('SG_SHOW_STATISTICS_WIDGET','1'),
101
+ ('SG_BACKUP_SEND_USAGE_STATUS','0'),
102
+ ('SG_NOTIFICATIONS_EMAIL_ADDRESS',''),
103
+ ('SG_STORAGE_BACKUPS_FOLDER_NAME','sg_backups');"
104
+ );
105
+ if ($res===false) {
106
+ return false;
107
+ }
108
+
109
+ return true;
110
+ }
111
+
112
+ private static function installScheduleTable($sgdb)
113
+ {
114
+ $dbEngine = backupGuardGetDatabaseEngine();
115
+
116
+ //create schedule table
117
+ $res = $sgdb->query(
118
+ 'CREATE TABLE IF NOT EXISTS `'.SG_SCHEDULE_TABLE_NAME.'` (
119
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
120
+ `label` varchar(255) NOT NULL,
121
+ `status` tinyint(3) unsigned NOT NULL,
122
+ `schedule_options` varchar(255) NOT NULL,
123
+ `backup_options` text NOT NULL,
124
+ PRIMARY KEY (`id`)
125
+ ) ENGINE='.$dbEngine.' DEFAULT CHARSET=utf8;'
126
+ );
127
+ if ($res===false) {
128
+ return false;
129
+ }
130
+
131
+ return true;
132
+ }
133
+
134
+ private static function installActionTable($sgdb)
135
+ {
136
+ $dbEngine = backupGuardGetDatabaseEngine();
137
+
138
+ //create action table
139
+ $res = $sgdb->query(
140
+ "CREATE TABLE IF NOT EXISTS `".SG_ACTION_TABLE_NAME."` (
141
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
142
+ `name` varchar(255) NOT NULL,
143
+ `type` tinyint(3) unsigned NOT NULL,
144
+ `subtype` tinyint(3) unsigned NOT NULL DEFAULT '0',
145
+ `status` tinyint(3) unsigned NOT NULL,
146
+ `progress` tinyint(3) unsigned NOT NULL DEFAULT '0',
147
+ `start_date` datetime NOT NULL,
148
+ `update_date` datetime DEFAULT NULL,
149
+ `options` text NOT NULL,
150
+ PRIMARY KEY (`id`)
151
+ ) ENGINE=".$dbEngine." DEFAULT CHARSET=utf8;"
152
+ );
153
+ if ($res===false) {
154
+ return false;
155
+ }
156
+
157
+ return true;
158
+ }
159
+
160
+ public static function install()
161
+ {
162
+ $sgdb = SGDatabase::getInstance();
163
+
164
+ try {
165
+ if (!self::installConfigTable($sgdb)) {
166
+ throw new SGExceptionDatabaseError('Could not install config table');
167
+ }
168
+
169
+ if (!self::installScheduleTable($sgdb)) {
170
+ throw new SGExceptionDatabaseError('Could not install schedule table');
171
+ }
172
+
173
+ if (!self::installActionTable($sgdb)) {
174
+ throw new SGExceptionDatabaseError('Could not install action table');
175
+ }
176
+
177
+ self::installReviewSettings();
178
+ }
179
+ catch (SGException $exception) {
180
+ die($exception);
181
+ }
182
+ }
183
+
184
+ private static function installReviewSettings()
185
+ {
186
+ $usageDays = SGConfig::get('usageDays');
187
+ if (!$usageDays) {
188
+ SGConfig::set('usageDays', 0);
189
+
190
+ $timeDate = new \DateTime('now');
191
+ $installTime = strtotime($timeDate->format('Y-m-d H:i:s'));
192
+ SGConfig::set('installDate', $installTime);
193
+ $timeDate->modify('+'.SG_BACKUP_REVIEW_PERIOD.' day');
194
+
195
+ $timeNow = strtotime($timeDate->format('Y-m-d H:i:s'));
196
+ SGConfig::set('openNextTime', $timeNow);
197
+ }
198
+ $backupCountReview = SGConfig::get('backupReviewCount');
199
+ if (!$backupCountReview) {
200
+ SGConfig::set('backupReviewCount', SG_BACKUP_REVIEW_BACKUP_COUNT);
201
+ }
202
+
203
+ $restoreReviewCount = SGConfig::get('restoreReviewCount');
204
+ if (!$restoreReviewCount) {
205
+ SGConfig::set('restoreReviewCount', SG_BACKUP_REVIEW_RESTORE_COUNT);
206
+ }
207
+ }
208
+
209
+ private static function cleanupSchedules()
210
+ {
211
+ $schedules = SGBackupSchedule::getAllSchedules();
212
+ foreach ($schedules as $schedule) {
213
+ SGBackupSchedule::remove($schedule['id']);
214
+ }
215
+ }
216
+
217
+ public static function uninstall($deleteBackups = false)
218
+ {
219
+ try {
220
+ @unlink(SG_PING_FILE_PATH);
221
+
222
+ if (self::isFeatureAvailable('SCHEDULE')) {
223
+ self::cleanupSchedules();
224
+ }
225
+
226
+ $sgdb = SGDatabase::getInstance();
227
+
228
+ //drop config table
229
+ $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_CONFIG_TABLE_NAME.'`;');
230
+ if ($res===false) {
231
+ throw new SGExceptionDatabaseError('Could not execute query');
232
+ }
233
+
234
+ //drop schedule table
235
+ $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_SCHEDULE_TABLE_NAME.'`;');
236
+ if ($res===false) {
237
+ throw new SGExceptionDatabaseError('Could not execute query');
238
+ }
239
+
240
+ //drop action table
241
+ $res = $sgdb->query('DROP TABLE IF EXISTS `'.SG_ACTION_TABLE_NAME.'`;');
242
+ if ($res===false) {
243
+ throw new SGExceptionDatabaseError('Could not execute query');
244
+ }
245
+
246
+ //delete directory of backups
247
+ if ($deleteBackups) {
248
+ $backupPath = SGConfig::get('SG_BACKUP_DIRECTORY');
249
+ backupGuardDeleteDirectory($backupPath);
250
+ }
251
+ }
252
+ catch (SGException $exception) {
253
+ die($exception);
254
+ }
255
+ }
256
+
257
+ public static function checkRequirement($requirement)
258
+ {
259
+ if ($requirement=='ftp' && !extension_loaded('ftp')) {
260
+ throw new SGExceptionNotFound('FTP extension is not loaded.');
261
+ }
262
+ else if ($requirement=='curl' && !function_exists('curl_version')) {
263
+ throw new SGExceptionNotFound('cURL extension is not loaded.');
264
+ }
265
+ else if ($requirement=='intSize' && PHP_INT_SIZE < 8) {
266
+ throw new SGExceptionIO("BackupGuard uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . ")");
267
+ }
268
+ }
269
+
270
+ public static function isFeatureAvailable($feature)
271
+ {
272
+ return ((int)SGConfig::get('SG_FEATURE_'.strtoupper($feature))===1?true:false);
273
+ }
274
+
275
+ private static function prepare()
276
+ {
277
+ $backupPath = SGConfig::get('SG_BACKUP_DIRECTORY');
278
+
279
+ //create directory for backups
280
+ if (!is_dir($backupPath)) {
281
+ if (!@mkdir($backupPath)) {
282
+ throw new SGExceptionMethodNotAllowed('Cannot create folder: '.$backupPath);
283
+ }
284
+
285
+ if (!@file_put_contents($backupPath.'.htaccess', 'deny from all')) {
286
+ throw new SGExceptionMethodNotAllowed('Cannot create htaccess file');
287
+ }
288
+
289
+ if (!@file_put_contents($backupPath.'index.php', "<?php\n// Silence is golden")) {
290
+ throw new SGExceptionMethodNotAllowed('Cannot create index file');
291
+ }
292
+ }
293
+
294
+ //check permissions of backups directory
295
+ if (!is_writable($backupPath)) {
296
+ throw new SGExceptionForbidden('Permission denied. Directory is not writable: '.$backupPath);
297
+ }
298
+
299
+ //prepare notices
300
+ $noticeHandler = new SGNoticeHandler();
301
+ $noticeHandler->run();
302
+ }
303
+
304
+ private static function checkMinimumRequirements()
305
+ {
306
+ //check ZLib library
307
+ if (!function_exists('gzdeflate')) {
308
+ throw new SGExceptionNotFound('ZLib extension is not loaded.');
309
+ }
310
+ }
311
+ }
com/core/schedule/SGIScheduleAdapter.php CHANGED
@@ -1,8 +1,8 @@
1
- <?php
2
-
3
- interface SGIScheduleAdapter
4
- {
5
- public static function create($cron, $id);
6
- public static function remove($cron);
7
- public static function isCronAvailable();
8
- }
1
+ <?php
2
+
3
+ interface SGIScheduleAdapter
4
+ {
5
+ public static function create($cron, $id);
6
+ public static function remove($cron);
7
+ public static function isCronAvailable($force = false);
8
+ }
com/core/schedule/SGSchedule.php CHANGED
@@ -1,37 +1,37 @@
1
- <?php
2
-
3
- class SGSchedule
4
- {
5
- public static function create($cron, $id)
6
- {
7
- $className = self::getCurrentScheduleClassName();
8
- require_once(SG_SCHEDULE_PATH.$className.'.php');
9
- $className::create($cron, $id);
10
- }
11
-
12
- public static function getCronExecutionData($cron)
13
- {
14
- $className = self::getCurrentScheduleClassName();
15
- require_once(SG_SCHEDULE_PATH.$className.'.php');
16
- return $className::getCronExecutionData($cron);
17
- }
18
-
19
- public static function remove($id)
20
- {
21
- $className = self::getCurrentScheduleClassName();
22
- require_once(SG_SCHEDULE_PATH.$className.'.php');
23
- $className::remove($id);
24
- }
25
-
26
- public static function isCronAvailable()
27
- {
28
- $className = self::getCurrentScheduleClassName();
29
- require_once(SG_SCHEDULE_PATH.$className.'.php');
30
- return $className::isCronAvailable();
31
- }
32
-
33
- private static function getCurrentScheduleClassName()
34
- {
35
- return 'SGScheduleAdapter'.SG_ENV_ADAPTER;
36
- }
37
- }
1
+ <?php
2
+
3
+ class SGSchedule
4
+ {
5
+ public static function create($cron, $id)
6
+ {
7
+ $className = self::getCurrentScheduleClassName();
8
+ require_once(SG_SCHEDULE_PATH.$className.'.php');
9
+ $className::create($cron, $id);
10
+ }
11
+
12
+ public static function getCronExecutionData($cron)
13
+ {
14
+ $className = self::getCurrentScheduleClassName();
15
+ require_once(SG_SCHEDULE_PATH.$className.'.php');
16
+ return $className::getCronExecutionData($cron);
17
+ }
18
+
19
+ public static function remove($id)
20
+ {
21
+ $className = self::getCurrentScheduleClassName();
22
+ require_once(SG_SCHEDULE_PATH.$className.'.php');
23
+ $className::remove($id);
24
+ }
25
+
26
+ public static function isCronAvailable($force = false)
27
+ {
28
+ $className = self::getCurrentScheduleClassName();
29
+ require_once(SG_SCHEDULE_PATH.$className.'.php');
30
+ return $className::isCronAvailable($force);
31
+ }
32
+
33
+ private static function getCurrentScheduleClassName()
34
+ {
35
+ return 'SGScheduleAdapter'.SG_ENV_ADAPTER;
36
+ }
37
+ }
com/core/schedule/SGScheduleAdapterWordpress.php CHANGED
@@ -1,124 +1,128 @@
1
- <?php
2
- require_once(SG_SCHEDULE_PATH.'SGIScheduleAdapter.php');
3
-
4
- class SGScheduleAdapterWordpress implements SGIScheduleAdapter
5
- {
6
- public static function create($cron, $id = SG_SCHEDULER_DEFAULT_ID)
7
- {
8
- if (!self::isCronAvailable()) {
9
- return false;
10
- }
11
-
12
- $cronExecutionData = self::getCronExecutionData($cron);
13
- $time = $cronExecutionData['time'];
14
- $recurrence = $cronExecutionData['recurrence'];
15
-
16
- $args = array((int)$id);
17
-
18
- $dateString = backupGuardConvertDateTimezone(@date("Y-m-d H:i:s", $time));
19
- $time = strtotime($dateString);
20
- $res = wp_schedule_event($time, $recurrence, SG_SCHEDULE_ACTION, $args);
21
- }
22
-
23
- public static function getCronExecutionData($cron)
24
- {
25
- $recurrence = '';
26
- $tmpTime = self::getTmpTime($cron['intervalHour']);
27
-
28
- if ($cron['interval'] == BG_SCHEDULE_INTERVAL_HOURLY) {
29
- $recurrence = 'hourly';
30
- $time = time() + 3600;
31
- }
32
- else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_DAILY) {
33
- $recurrence = 'daily';
34
-
35
- if ($tmpTime < time()) {
36
- $time = strtotime('Next day '.sprintf("%02d:00", $cron['intervalHour']));
37
- }
38
- else {
39
- $time = $tmpTime;
40
- }
41
- }
42
- else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_WEEKLY) {
43
- $recurrence = 'weekly';
44
- $dayOfInterval = $cron['dayOfInterval'];
45
-
46
- switch ($dayOfInterval) {
47
- case 1:
48
- $dayOfInterval = 'Monday';
49
- break;
50
- case 2:
51
- $dayOfInterval = 'Tuesday';
52
- break;
53
- case 3:
54
- $dayOfInterval = 'Wednesday';
55
- break;
56
- case 4:
57
- $dayOfInterval = 'Thursday';
58
- break;
59
- case 5:
60
- $dayOfInterval = 'Friday';
61
- break;
62
- case 6:
63
- $dayOfInterval = 'Saturday';
64
- break;
65
- case 7:
66
- $dayOfInterval = 'Sunday';
67
- break;
68
- default:
69
- $dayOfInterval = 'Monday';
70
- break;
71
- }
72
-
73
- if ($tmpTime < time()) {
74
- $time = strtotime('Next '.$dayOfInterval.' '.sprintf("%02d:00", $cron['intervalHour']));
75
- }
76
- else {
77
- $time = strtotime('this '.$dayOfInterval.' '.sprintf("%02d:00", $cron['intervalHour']));
78
- }
79
- }
80
- else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_MONTHLY) {
81
- $recurrence = 'monthly';
82
- $dayOfInterval = $cron['dayOfInterval'];
83
- $today = (int)date('d');
84
-
85
- if ($today < $dayOfInterval) {
86
- $time = $tmpTime + ($dayOfInterval - $today) * SG_ONE_DAY_IN_SECONDS;
87
- }
88
- else {
89
- if ($tmpTime > time() && $today == $dayOfInterval) {
90
- $time = $tmpTime;
91
- }
92
- else {
93
- $time = strtotime('first day of next month '.sprintf("%02d:00", $cron['intervalHour']));
94
- $time += ($dayOfInterval - 1) * SG_ONE_DAY_IN_SECONDS;
95
- }
96
- }
97
- }
98
- else {
99
- $recurrence = 'yearly';
100
- $time = strtotime('Next year today '.sprintf("%02d:00", $cron['intervalHour']));
101
- }
102
-
103
- return array(
104
- 'time' => $time,
105
- 'recurrence' => $recurrence
106
- );
107
- }
108
-
109
- public static function remove($id = SG_SCHEDULER_DEFAULT_ID)
110
- {
111
- $args = array((int)$id);
112
- wp_clear_scheduled_hook(SG_SCHEDULE_ACTION, $args);
113
- }
114
-
115
- public static function getTmpTime($hours)
116
- {
117
- return strtotime('Today '.sprintf("%02d:00", $hours));
118
- }
119
-
120
- public static function isCronAvailable()
121
- {
122
- return defined('DISABLE_WP_CRON')?!DISABLE_WP_CRON:true;
123
- }
124
- }
 
 
 
 
1
+ <?php
2
+ require_once(SG_SCHEDULE_PATH.'SGIScheduleAdapter.php');
3
+
4
+ class SGScheduleAdapterWordpress implements SGIScheduleAdapter
5
+ {
6
+ public static function create($cron, $id = SG_SCHEDULER_DEFAULT_ID)
7
+ {
8
+ if (!self::isCronAvailable()) {
9
+ return false;
10
+ }
11
+
12
+ $cronExecutionData = self::getCronExecutionData($cron);
13
+ $time = $cronExecutionData['time'];
14
+ $recurrence = $cronExecutionData['recurrence'];
15
+
16
+ $args = array((int)$id);
17
+
18
+ $dateString = backupGuardConvertDateTimezone(@date("Y-m-d H:i:s", $time));
19
+ $time = strtotime($dateString);
20
+ $res = wp_schedule_event($time, $recurrence, SG_SCHEDULE_ACTION, $args);
21
+ }
22
+
23
+ public static function getCronExecutionData($cron)
24
+ {
25
+ $recurrence = '';
26
+ $tmpTime = self::getTmpTime($cron['intervalHour']);
27
+
28
+ if ($cron['interval'] == BG_SCHEDULE_INTERVAL_HOURLY) {
29
+ $recurrence = 'hourly';
30
+ $time = time() + 3600;
31
+ }
32
+ else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_DAILY) {
33
+ $recurrence = 'daily';
34
+
35
+ if ($tmpTime < time()) {
36
+ $time = strtotime('Next day '.sprintf("%02d:00", $cron['intervalHour']));
37
+ }
38
+ else {
39
+ $time = $tmpTime;
40
+ }
41
+ }
42
+ else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_WEEKLY) {
43
+ $recurrence = 'weekly';
44
+ $dayOfInterval = $cron['dayOfInterval'];
45
+
46
+ switch ($dayOfInterval) {
47
+ case 1:
48
+ $dayOfInterval = 'Monday';
49
+ break;
50
+ case 2:
51
+ $dayOfInterval = 'Tuesday';
52
+ break;
53
+ case 3:
54
+ $dayOfInterval = 'Wednesday';
55
+ break;
56
+ case 4:
57
+ $dayOfInterval = 'Thursday';
58
+ break;
59
+ case 5:
60
+ $dayOfInterval = 'Friday';
61
+ break;
62
+ case 6:
63
+ $dayOfInterval = 'Saturday';
64
+ break;
65
+ case 7:
66
+ $dayOfInterval = 'Sunday';
67
+ break;
68
+ default:
69
+ $dayOfInterval = 'Monday';
70
+ break;
71
+ }
72
+
73
+ if ($tmpTime < time()) {
74
+ $time = strtotime('Next '.$dayOfInterval.' '.sprintf("%02d:00", $cron['intervalHour']));
75
+ }
76
+ else {
77
+ $time = strtotime('this '.$dayOfInterval.' '.sprintf("%02d:00", $cron['intervalHour']));
78
+ }
79
+ }
80
+ else if ($cron['interval'] == BG_SCHEDULE_INTERVAL_MONTHLY) {
81
+ $recurrence = 'monthly';
82
+ $dayOfInterval = $cron['dayOfInterval'];
83
+ $today = (int)date('d');
84
+
85
+ if ($today < $dayOfInterval) {
86
+ $time = $tmpTime + ($dayOfInterval - $today) * SG_ONE_DAY_IN_SECONDS;
87
+ }
88
+ else {
89
+ if ($tmpTime > time() && $today == $dayOfInterval) {
90
+ $time = $tmpTime;
91
+ }
92
+ else {
93
+ $time = strtotime('first day of next month '.sprintf("%02d:00", $cron['intervalHour']));
94
+ $time += ($dayOfInterval - 1) * SG_ONE_DAY_IN_SECONDS;
95
+ }
96
+ }
97
+ }
98
+ else {
99
+ $recurrence = 'yearly';
100
+ $time = strtotime('Next year today '.sprintf("%02d:00", $cron['intervalHour']));
101
+ }
102
+
103
+ return array(
104
+ 'time' => $time,
105
+ 'recurrence' => $recurrence
106
+ );
107
+ }
108
+
109
+ public static function remove($id = SG_SCHEDULER_DEFAULT_ID)
110
+ {
111
+ $args = array((int)$id);
112
+ wp_clear_scheduled_hook(SG_SCHEDULE_ACTION, $args);
113
+ }
114
+
115
+ public static function getTmpTime($hours)
116
+ {
117
+ return strtotime('Today '.sprintf("%02d:00", $hours));
118
+ }
119
+
120
+ public static function isCronAvailable($force = false)
121
+ {
122
+ if ($force) {
123
+ return defined('DISABLE_WP_CRON') ? !DISABLE_WP_CRON : true;
124
+ }
125
+
126
+ return true;
127
+ }
128
+ }
com/lib/SGArchive.php CHANGED
@@ -1,793 +1,806 @@
1
- <?php
2
-
3
- interface SGArchiveDelegate
4
- {
5
- public function getCorrectCdrFilename($filename);
6
- public function didExtractFile($filePath);
7
- public function didCountFilesInsideArchive($count);
8
- public function didFindExtractError($error);
9
- public function warn($message);
10
- public function didExtractArchiveMeta($meta);
11
- public function didStartRestoreFiles();
12
- }
13
-
14
- class SGArchive
15
- {
16
- const VERSION = 5;
17
- const CHUNK_SIZE = 1048576; //1mb
18
- private $filePath = '';
19
- private $mode = '';
20
- private $fileHandle = null;
21
- private $cdrFileHandle = null;
22
- private $cdrFilesCount = 0;
23
- private $cdr = array();
24
- private $fileOffset = 0;
25
- private $delegate;
26
- private $ranges = array();
27
- private $state = null;
28
- private $rangeCursor = 0;
29
-
30
- private $cdrOffset = 0;
31
-
32
- public function __construct($filePath, $mode, $cdrSize = 0)
33
- {
34
- $this->filePath = $filePath;
35
- $this->mode = $mode;
36
- $this->fileHandle = @fopen($filePath, $mode.'b');
37
- $this->clear();
38
-
39
- if ($cdrSize) {
40
- $this->cdrFilesCount = $cdrSize;
41
- }
42
-
43
- if ($mode == 'a') {
44
-
45
- $cdrPath = $filePath.'.cdr';
46
-
47
- $this->cdrFileHandle = @fopen($cdrPath, $mode.'b');
48
- }
49
- }
50
-
51
- public function setDelegate(SGArchiveDelegate $delegate)
52
- {
53
- $this->delegate = $delegate;
54
- }
55
-
56
- public function getCdrFilesCount()
57
- {
58
- return $this->cdrFilesCount;
59
- }
60
-
61
- public function addFileFromPath($filename, $path)
62
- {
63
- $headerSize = 0;
64
- $len = 0;
65
- $zlen = 0;
66
- $start = 0;
67
-
68
- $fp = fopen($path, 'rb');
69
- $fileSize = backupGuardRealFilesize($path);
70
-
71
- $state = $this->delegate->getState();
72
- $offset = $state->getOffset();
73
-
74
- if (!$state->getInprogress()) {
75
- $headerSize = $this->addFileHeader();
76
- }
77
- else{
78
- $headerSize = $state->getHeaderSize();
79
- $this->fileOffset = $state->getFileOffsetInArchive();
80
- }
81
-
82
- $this->ranges = $state->getRanges();
83
- if (count($this->ranges)) {
84
- $range = end($this->ranges); //get last range of file
85
-
86
- $start += $range['start'] + $range['size'];
87
- $zlen = $start; // get file compressed size before reload
88
- }
89
-
90
- fseek($fp, $offset); // move to point before reload
91
- //read file in small chunks
92
- while ($offset < $fileSize)
93
- {
94
- $data = fread($fp, self::CHUNK_SIZE);
95
- if ($data === '') {
96
- //When fread fails to read and compress on fly
97
- if ($zlen == 0 && $fileSize != 0 && strlen($data) == 0) {
98
- $this->delegate->warn('Failed to read file: '.basename($filename));
99
- }
100
- break;
101
- }
102
-
103
- $data = gzdeflate($data);
104
- $zlen += strlen($data);
105
- $sgArchiveSize = backupGuardRealFilesize($this->filePath);
106
- $sgArchiveSize += strlen($data);
107
-
108
- if($sgArchiveSize > SG_ARCHIVE_MAX_SIZE_32) {
109
- SGBoot::checkRequirement('intSize');
110
- }
111
-
112
- $this->write($data);
113
-
114
- array_push($this->ranges, array(
115
- 'start' => $start,
116
- 'size' => strlen($data)
117
- ));
118
- $offset = ftell($fp);
119
-
120
- $start += strlen($data);
121
-
122
- SGPing::update();
123
- $shouldReload = $this->delegate->shouldReload();
124
- if ($shouldReload) {
125
- $this->delegate->saveStateData(SG_STATE_ACTION_COMPRESSING_FILES, $this->ranges, $offset, $headerSize, true, $this->fileOffset);
126
-
127
- if (backupGuardIsReloadEnabled()) {
128
- @fclose($fp);
129
- @fclose($this->fileHandle);
130
- @fclose($this->cdrFileHandle);
131
-
132
- $this->delegate->reload();
133
- }
134
- }
135
- }
136
-
137
- if ($state->getInprogress()) {
138
- $headerSize = $state->getHeaderSize();
139
- }
140
-
141
- SGPing::update();
142
-
143
- fclose($fp);
144
-
145
- $this->addFileToCdr($filename, $zlen, $len, $headerSize);
146
- }
147
-
148
- public function addFile($filename, $data)
149
- {
150
- $headerSize = $this->addFileHeader();
151
-
152
- if ($data)
153
- {
154
- $data = gzdeflate($data);
155
- $this->write($data);
156
- }
157
-
158
- $zlen = strlen($data);
159
- $len = 0;
160
-
161
- $this->addFileToCdr($filename, $zlen, $len, $headerSize);
162
- }
163
-
164
- private function addFileHeader()
165
- {
166
- //save extra
167
- $extra = '';
168
-
169
- $extraLengthInBytes = 4;
170
- $this->write($this->packToLittleEndian(strlen($extra), $extraLengthInBytes).$extra);
171
-
172
- return $extraLengthInBytes+strlen($extra);
173
- }
174
-
175
- private function addFileToCdr($filename, $zlen, $len, $headerSize)
176
- {
177
- //store cdr data for later use
178
- $this->addToCdr($filename, $zlen, $len);
179
-
180
- $this->fileOffset += $headerSize + $zlen;
181
- }
182
-
183
- public function finalize()
184
- {
185
- $this->addFooter();
186
-
187
- fclose($this->fileHandle);
188
-
189
- $this->clear();
190
- }
191
-
192
- private function addFooter()
193
- {
194
- $footer = '';
195
-
196
- //save version
197
- $footer .= $this->packToLittleEndian(self::VERSION, 1);
198
-
199
- $tables = SGConfig::get('SG_BACKUPED_TABLES');
200
-
201
- if ($tables) {
202
- $table = json_encode($tables);
203
- }
204
- else {
205
- $tables = "";
206
- }
207
-
208
- $multisitePath = "";
209
- $multisiteDomain = "";
210
-
211
- if (SG_ENV_ADAPTER == SG_ENV_WORDPRESS) {
212
- // in case of multisite save old path and domain for later usage
213
- if (is_multisite()) {
214
- $multisitePath = PATH_CURRENT_SITE;
215
- $multisiteDomain = DOMAIN_CURRENT_SITE;
216
- }
217
- }
218
-
219
- //save db prefix, site and home url for later use
220
- $extra = json_encode(array(
221
- 'siteUrl' => get_site_url(),
222
- 'home' => get_home_url(),
223
- 'dbPrefix' => SG_ENV_DB_PREFIX,
224
- 'tables' => $tables,
225
- 'method' => SGConfig::get('SG_BACKUP_TYPE'),
226
- 'multisitePath' => $multisitePath,
227
- 'multisiteDomain' => $multisiteDomain,
228
- 'selectivRestoreable' => true,
229
- 'phpVersion' => phpversion()
230
- ));
231
-
232
- //extra size
233
- $footer .= $this->packToLittleEndian(strlen($extra), 4).$extra;
234
-
235
- //save cdr size
236
- $footer .= $this->packToLittleEndian($this->cdrFilesCount, 4);
237
-
238
- $this->write($footer);
239
-
240
- //save cdr
241
- $cdrLen = $this->writeCdr();
242
-
243
- //save offset to the start of footer
244
- $len = $cdrLen+strlen($extra)+13;
245
- $this->write($this->packToLittleEndian($len, 4));
246
- }
247
-
248
- private function writeCdr()
249
- {
250
- @fclose($this->cdrFileHandle);
251
-
252
- $cdrLen = 0;
253
- $fp = @fopen($this->filePath.'.cdr', 'rb');
254
-
255
- while (!feof($fp))
256
- {
257
- $data = fread($fp, self::CHUNK_SIZE);
258
- $cdrLen += strlen($data);
259
- $this->write($data);
260
- }
261
-
262
- @fclose($fp);
263
- @unlink($this->filePath.'.cdr');
264
-
265
- return $cdrLen;
266
- }
267
-
268
- private function clear()
269
- {
270
- $this->cdr = array();
271
- $this->fileOffset = 0;
272
- $this->cdrFilesCount = 0;
273
- }
274
-
275
- private function addToCdr($filename, $compressedLength, $uncompressedLength)
276
- {
277
- $rec = $this->packToLittleEndian(0, 4); //crc (not used in this version)
278
- $rec .= $this->packToLittleEndian(strlen($filename), 2);
279
- $rec .= $filename;
280
- // file offset, compressed length, uncompressed length all are writen in 8 bytes to cover big integer size
281
- $rec .= $this->packToLittleEndian($this->fileOffset, 8);
282
- $rec .= $this->packToLittleEndian($compressedLength, 8);
283
- $rec .= $this->packToLittleEndian($uncompressedLength, 8); //uncompressed size (not used in this version)
284
- $rec .= $this->packToLittleEndian(count($this->ranges), 4);
285
-
286
- foreach ($this->ranges as $range) {
287
- // start and size all are writen in 8 bytes to cover big integer size
288
- $rec .= $this->packToLittleEndian($range['start'], 8);
289
- $rec .= $this->packToLittleEndian($range['size'], 8);
290
- }
291
-
292
- fwrite($this->cdrFileHandle, $rec);
293
- fflush($this->cdrFileHandle);
294
-
295
- $this->cdrFilesCount++;
296
- }
297
-
298
- private function isEnoughFreeSpaceOnDisk($dataSize)
299
- {
300
- $freeSpace = @disk_free_space(SG_APP_ROOT_DIRECTORY);
301
-
302
- if ($freeSpace === false || $freeSpace === null) {
303
- return true;
304
- }
305
-
306
- if ($freeSpace < $dataSize) {
307
- return false;
308
- }
309
-
310
- return true;
311
- }
312
-
313
- private function write($data)
314
- {
315
- $isEnoughFreeSpaceOnDisk = $this->isEnoughFreeSpaceOnDisk(strlen($data));
316
- if (!$isEnoughFreeSpaceOnDisk) {
317
- throw new SGExceptionIO('Failed to write in the archive due to not sufficient disk free space.');
318
- }
319
-
320
- $result = fwrite($this->fileHandle, $data);
321
- if ($result === FALSE) {
322
- throw new SGExceptionIO('Failed to write in archive');
323
- }
324
- fflush($this->fileHandle);
325
- }
326
-
327
- private function read($length)
328
- {
329
- $result = fread($this->fileHandle, $length);
330
- if ($result === FALSE) {
331
- throw new SGExceptionIO('Failed to read from archive');
332
- }
333
- return $result;
334
- }
335
-
336
- private function packToLittleEndian($value, $size = 4)
337
- {
338
- if (is_int($value))
339
- {
340
- $size *= 2; //2 characters for each byte
341
- $value = str_pad(dechex($value), $size, '0', STR_PAD_LEFT);
342
- return strrev(pack('H'.$size, $value));
343
- }
344
-
345
- $hex = str_pad($value->toHex(), 16, '0', STR_PAD_LEFT);
346
-
347
- $high = substr($hex, 0, 8);
348
- $low = substr($hex, 8, 8);
349
-
350
- $high = strrev(pack('H8', $high));
351
- $low = strrev(pack('H8', $low));
352
-
353
- return $low.$high;
354
- }
355
-
356
- public function getArchiveHeaders()
357
- {
358
- return $this->extractHeaders();
359
- }
360
-
361
- public function getFilesList()
362
- {
363
- $list = array();
364
- $cdrSize = hexdec($this->unpackLittleEndian($this->read(4), 4));
365
- $this->cdrOffset = ftell($this->fileHandle);
366
-
367
- for($i = 0; $i < $cdrSize; $i++) {
368
- $el = $this->getNextCdrElement($this->cdrOffset);
369
- array_push($list, $el[0]);
370
- }
371
- return $list;
372
- }
373
-
374
- public function getTreefromList($list, $limit = "")
375
- {
376
- $tree = array();
377
- if(end($list) == "./sql") {
378
- array_pop($list);
379
- }
380
- for($i=0; $i < count($list); $i++) {
381
- if(!backupGuardStringStartsWith($list[$i], $limit)) {
382
- continue;
383
- }
384
- $path = substr($list[$i], strlen($limit));
385
- $path = explode(DIRECTORY_SEPARATOR, $path);
386
- $exists = false;
387
- foreach($tree as $el) {
388
- if ($path[0] == $el->name) {
389
- $exists = true;
390
- break;
391
- }
392
- }
393
- if(!$exists) {
394
- $node = new stdClass();
395
- $node->name = $path[0];
396
- if(count($path) > 1){
397
- $node->type = "folder";
398
- }else{
399
- $node->type = "file";
400
- }
401
- array_push($tree,$node);
402
- }
403
-
404
- }
405
- return $tree;
406
- }
407
-
408
- public function extractTo($destinationPath, $state = null)
409
- {
410
- $this->state = $state;
411
- $action = $state->getAction();
412
-
413
- if ($action == SG_STATE_ACTION_PREPARING_STATE_FILE) {
414
- $this->extract($destinationPath);
415
- }
416
- else {
417
- $this->continueExtract($destinationPath);
418
- }
419
- }
420
-
421
- private function extractHeaders()
422
- {
423
- //read offset
424
- fseek($this->fileHandle, -4, SEEK_END);
425
- $offset = hexdec($this->unpackLittleEndian($this->read(4), 4));
426
-
427
- //read version
428
- fseek($this->fileHandle, -$offset, SEEK_END);
429
- $version = hexdec($this->unpackLittleEndian($this->read(1), 1));
430
- SGConfig::set('SG_CURRENT_ARCHIVE_VERSION', $version);
431
-
432
- //read extra size (not used in this version)
433
- $extraSize = hexdec($this->unpackLittleEndian($this->read(4), 4));
434
-
435
- //read extra
436
- $extra = array();
437
- if ($extraSize > 0) {
438
- $extra = $this->read($extraSize);
439
- $extra = json_decode($extra, true);
440
-
441
- SGConfig::set('SG_OLD_SITE_URL', $extra['siteUrl']);
442
- SGConfig::set('SG_OLD_DB_PREFIX', $extra['dbPrefix']);
443
-
444
- if (isset($extra['phpVersion'])) {
445
- SGConfig::set('SG_OLD_PHP_VERSION', $extra['phpVersion']);
446
- }
447
-
448
- SGConfig::set('SG_BACKUPED_TABLES', $extra['tables']);
449
- SGConfig::set('SG_BACKUP_TYPE', $extra['method']);
450
-
451
- SGConfig::set('SG_MULTISITE_OLD_PATH', $extra['multisitePath']);
452
- SGConfig::set('SG_MULTISITE_OLD_DOMAIN', $extra['multisiteDomain']);
453
- }
454
-
455
- $extra['version'] = $version;
456
- return $extra;
457
- }
458
-
459
- private function extract($destinationPath)
460
- {
461
- $extra = $this->extractHeaders();
462
- $version = $extra['version'];
463
-
464
- $this->delegate->didExtractArchiveMeta($extra);
465
-
466
- $isMultisite = backupGuardIsMultisite();
467
- $archiveIsMultisite = $extra['multisitePath'] != '' || $extra['multisiteDomain'] != '';
468
-
469
- if (SG_ENV_ADAPTER == SG_ENV_WORDPRESS) {
470
- if ($archiveIsMultisite && !$isMultisite) {
471
- throw new SGExceptionMigrationError("In order to restore this archive you should set up Multisite WordPress!");
472
- }
473
- elseif (!$archiveIsMultisite && $isMultisite) {
474
- throw new SGExceptionMigrationError("In order to restore this archive you should set up a Standard instead of Multisite WordPress!");
475
- }
476
- }
477
-
478
- if ($version >= SG_MIN_SUPPORTED_ARCHIVE_VERSION && $version <= SG_MAX_SUPPORTED_ARCHIVE_VERSION) {
479
- if( !SGBoot::isFeatureAvailable('BACKUP_WITH_MIGRATION') ) {
480
- if ($extra['method'] != SG_BACKUP_METHOD_MIGRATE) {
481
- if ($extra['siteUrl'] == SG_SITE_URL) {
482
- if ($extra['dbPrefix'] != SG_ENV_DB_PREFIX) {
483
- throw new SGException("Seems you have changed database prefix. You should keep it constant to be able to restore this backup. Setup your WordPress installation with ".$extra['dbPrefix']." datbase prefix.");
484
- }
485
- }
486
- else {
487
- throw new SGExceptionMigrationError("You should install <b>BackupGuard Pro</b> to be able to migrate the website. More detailed information regarding features included in <b>Free</b> and <b>Pro</b> versions you can find here: <a href='".SG_BACKUP_SITE_URL."'>".SG_BACKUP_SITE_URL."</a>");
488
- }
489
- }
490
- else {
491
- throw new SGExceptionMigrationError("You should install <b>BackupGuard Pro</b> to be able to restore a package designed for migration.More detailed information regarding features included in <b>Free</b> and <b>Pro</b> versions you can find here: <a href='".SG_BACKUP_SITE_URL."'>".SG_BACKUP_SITE_URL."</a>");
492
- }
493
- }
494
- }
495
- else {
496
- throw new SGExceptionBadRequest('Invalid SGArchive file');
497
- }
498
-
499
- //read cdr size
500
- $this->cdrFilesCount = hexdec($this->unpackLittleEndian($this->read(4), 4));
501
-
502
- $this->delegate->didStartRestoreFiles();
503
- $this->delegate->didCountFilesInsideArchive($this->cdrFilesCount);
504
-
505
- // $this->extractCdr($cdrSize, $destinationPath);
506
- $this->cdrOffset = ftell($this->fileHandle);
507
- $this->extractFiles($destinationPath);
508
- }
509
-
510
- private function continueExtract($destinationPath)
511
- {
512
- $this->fileOffset = $this->state->getOffset();
513
- fseek($this->fileHandle, $this->fileOffset);
514
- $this->extractFiles($destinationPath);
515
- }
516
-
517
- private function getNextCdrElement($offset)
518
- {
519
- fseek($this->fileHandle, $this->cdrOffset);
520
- //read crc (not used in this version)
521
- $this->read(4);
522
-
523
- //read filename
524
- $filenameLen = hexdec($this->unpackLittleEndian($this->read(2), 2));
525
- $filename = $this->read($filenameLen);
526
- $filename = $this->delegate->getCorrectCdrFilename($filename);
527
-
528
- //read file offset
529
- $fileOffsetInArchive = $this->unpackLittleEndian($this->read(8), 8);
530
- $fileOffsetInArchive = hexdec($fileOffsetInArchive);
531
-
532
- //read compressed length
533
- $zlen = $this->unpackLittleEndian($this->read(8), 8);
534
- $zlen = hexdec($zlen);
535
-
536
- //read uncompressed length (not used in this version)
537
- $this->read(8);
538
-
539
- $rangeLen = hexdec($this->unpackLittleEndian($this->read(4), 4));
540
-
541
- $ranges = array();
542
- for ($i=0; $i < $rangeLen; $i++) {
543
- $start = $this->unpackLittleEndian($this->read(8), 8);
544
- $start = hexdec($start);
545
-
546
- $size = $this->unpackLittleEndian($this->read(8), 8);
547
- $size = hexdec($size);
548
-
549
- $ranges[] = array(
550
- 'start' => $start,
551
- 'size' => $size
552
- );
553
- }
554
-
555
- $this->cdrOffset = ftell($this->fileHandle);
556
- return array($filename, $zlen, $ranges, $fileOffsetInArchive);
557
- }
558
-
559
- private function extractFiles($destinationPath)
560
- {
561
- $action = $this->state->getAction();
562
- if ($action == SG_STATE_ACTION_PREPARING_STATE_FILE) {
563
- $inprogress = false;
564
- fseek($this->fileHandle, 0, SEEK_SET);
565
- }
566
- else {
567
- $inprogress = $this->state->getInprogress();
568
- $this->cdrFilesCount = $this->state->getCdrSize();
569
- $this->cdrOffset = $this->state->getCdrCursor();
570
- }
571
-
572
- $sqlFileEnding = $this->state->getBackupFileName().'/'.$this->state->getBackupFileName().'.sql';
573
- $restoreMode = $this->state->getRestoreMode();
574
- $restoreFiles = $this->state->getRestoreFiles();
575
-
576
- while ($this->cdrFilesCount) {
577
-
578
- $warningFoundDuringExtract = false;
579
-
580
- if ($inprogress) {
581
- $row = $this->state->getCdr();
582
- }
583
- else {
584
- $row = $this->getNextCdrElement($this->cdrOffset);
585
-
586
- fseek($this->fileHandle, $this->fileOffset);
587
-
588
- //read extra (not used in this version)
589
- $this->read(4);
590
- }
591
-
592
- $path = $destinationPath . $row[0];
593
- $path = str_replace('\\', '/', $path);
594
- $restoreCurrentFile = false;
595
-
596
- if ($restoreMode == SG_RESTORE_MODE_FILES && $restoreFiles != NULL && count($restoreFiles) > 0) {
597
- for ($j = 0; $j < count($restoreFiles); $j++) {
598
- if ($restoreFiles[$j] == "/" || backupGuardStringStartsWith($row[0], $restoreFiles[$j])) {
599
- $restoreCurrentFile = true;
600
- break;
601
- }
602
- }
603
- }
604
-
605
- // check if file should be restored according restore mode selected by user
606
- if($restoreMode == SG_RESTORE_MODE_FULL || ($restoreMode == SG_RESTORE_MODE_DB && backupGuardStringEndsWith($path,$sqlFileEnding)) || ($restoreMode == SG_RESTORE_MODE_FILES && !backupGuardStringEndsWith($path,$sqlFileEnding) && $restoreCurrentFile)) {
607
-
608
- if ($path[strlen($path) - 1] != '/') {//it's not an empty directory
609
- $path = dirname($path);
610
- }
611
-
612
- if (!$inprogress) {
613
- if (!$this->createPath($path)) {
614
- $ranges = $row[2];
615
-
616
- //get last range of file
617
- $range = end($ranges);
618
- $offset = $range['start'] + $range['size'];
619
-
620
- // skip file and continue
621
- fseek($this->fileHandle, $offset, SEEK_CUR);
622
- $this->delegate->didFindExtractError('Could not create directory: ' . dirname($path));
623
- continue;
624
- }
625
- }
626
-
627
- $path = $destinationPath . $row[0];
628
- $tmpPath = $path . ".sgbpTmpFile";
629
-
630
- if (!$inprogress) {
631
- $this->delegate->didStartExtractFile($path);
632
-
633
- if (!is_writable(dirname($tmpPath))) {
634
- $this->delegate->didFindExtractError('Destination path is not writable: ' . dirname($path));
635
- }
636
- }
637
-
638
- if (!$inprogress) {
639
- $tmpFp = @fopen($tmpPath, 'wb');
640
- }
641
- else {
642
- $tmpFp = @fopen($tmpPath, 'ab');
643
- }
644
-
645
- $zlen = $row[1];
646
- SGPing::update();
647
- $ranges = $row[2];
648
-
649
- if ($inprogress) {
650
- $this->rangeCursor = $this->state->getRangeCursor();
651
- }
652
- else {
653
- $this->rangeCursor = 0;
654
- }
655
-
656
- for ($i = $this->rangeCursor; $i < count($ranges); $i++) {
657
- $start = $ranges[$i]['start'];
658
- $size = $ranges[$i]['size'];
659
-
660
- $data = $this->read($size);
661
- $data = gzinflate($data);
662
-
663
- //If gzinflate() failed to uncompress, skip the current file and continue extraction
664
- if (!$data) {
665
- $warningFoundDuringExtract = true;
666
- $this->delegate->didFindExtractError('Failed to extract path: ' . $path);
667
-
668
- //Assume we've extracted the current file
669
- for ($idx = $i + 1; $idx < count($ranges); $idx++) {
670
- $start = $ranges[$idx]['start'];
671
- $size = $ranges[$idx]['size'];
672
-
673
- fseek($this->fileHandle, $size, SEEK_CUR);
674
- }
675
-
676
- $inprogress = false;
677
- @fclose($tmpFp);
678
-
679
- SGPing::update();
680
-
681
- break;
682
- }
683
- else {
684
- $inprogress = true;
685
- if (($i + 1) == count($ranges)) {
686
- $inprogress = false;
687
- }
688
- if (is_resource($tmpFp)) {
689
- $isEnoughFreeSpaceOnDisk = $this->isEnoughFreeSpaceOnDisk(strlen($data));
690
- if (!$isEnoughFreeSpaceOnDisk) {
691
- throw new SGExceptionIO('Failed to write in the archive due to not sufficient disk free space.');
692
- }
693
-
694
- fwrite($tmpFp, $data);
695
- fflush($tmpFp);
696
-
697
- $shouldReload = $this->delegate->shouldReload();
698
-
699
- //restore with reloads will only work in external mode
700
- if ($shouldReload && SGExternalRestore::isEnabled()) {
701
-
702
- if (!$inprogress) {
703
- $this->cdrFilesCount--;
704
-
705
- @rename($tmpPath, $path);
706
- $this->delegate->didExtractFile($path);
707
- }
708
-
709
- $token = $this->delegate->getToken();
710
- $progress = $this->delegate->getProgress();
711
-
712
- $this->fileOffset = ftell($this->fileHandle);
713
-
714
- $this->state->setRestoreMode($restoreMode);
715
- $this->state->setOffset($this->fileOffset);
716
- $this->state->setInprogress($inprogress);
717
- $this->state->setToken($token);
718
- $this->state->setProgress($progress);
719
- $this->state->setAction(SG_STATE_ACTION_RESTORING_FILES);
720
- $this->state->setRangeCursor($i + 1);
721
-
722
- $this->state->setCdr($row);
723
- $this->state->setCdrSize($this->cdrFilesCount);
724
- $this->state->setCdrCursor($this->cdrOffset);
725
- $this->state->save();
726
-
727
- SGPing::update();
728
-
729
- @fclose($tmpFp);
730
- @fclose($this->fileHandle);
731
-
732
- $this->delegate->reload();
733
- }
734
- }
735
- }
736
- SGPing::update();
737
- }
738
-
739
- if (is_resource($tmpFp)) {
740
- @fclose($tmpFp);
741
- }
742
-
743
- if (!$warningFoundDuringExtract) {
744
- @rename($tmpPath, $path);
745
- }
746
- else {
747
- @unlink($tmpPath);
748
- }
749
-
750
- $this->delegate->didExtractFile($path);
751
- $this->fileOffset = ftell($this->fileHandle);
752
- }
753
- else {
754
- //if file should not be restored skip it and go to the next file
755
- $ranges = $row[2];
756
-
757
- for ($idx = 0; $idx < count($ranges); $idx++) {
758
-
759
- $size = $ranges[$idx]['size'];
760
-
761
- fseek($this->fileHandle, $size, SEEK_CUR);
762
- }
763
- $this->fileOffset = ftell($this->fileHandle);
764
- }
765
-
766
- $this->cdrFilesCount--;
767
- }
768
- }
769
-
770
- private function unpackLittleEndian($data, $size)
771
- {
772
- $size *= 2; //2 characters for each byte
773
-
774
- $data = unpack('H'.$size, strrev($data));
775
- return $data[1];
776
- }
777
-
778
- private function createPath($path)
779
- {
780
- if (is_dir($path)) return true;
781
- $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1);
782
- $return = $this->createPath($prev_path);
783
- if ($return && is_writable($prev_path))
784
- {
785
- if (!@mkdir($path)) return false;
786
-
787
- @chmod($path, 0777);
788
- return true;
789
- }
790
-
791
- return false;
792
- }
793
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ interface SGArchiveDelegate
4
+ {
5
+ public function getCorrectCdrFilename($filename);
6
+ public function didExtractFile($filePath);
7
+ public function didCountFilesInsideArchive($count);
8
+ public function didFindExtractError($error);
9
+ public function warn($message);
10
+ public function didExtractArchiveMeta($meta);
11
+ public function didStartRestoreFiles();
12
+ }
13
+
14
+ class SGArchive
15
+ {
16
+ const VERSION = 5;
17
+ const CHUNK_SIZE = 1048576; //1mb
18
+ private $filePath = '';
19
+ private $mode = '';
20
+ private $fileHandle = null;
21
+ private $cdrFileHandle = null;
22
+ private $cdrFilesCount = 0;
23
+ private $cdr = array();
24
+ private $fileOffset = 0;
25
+ private $delegate;
26
+ private $ranges = array();
27
+ private $state = null;
28
+ private $rangeCursor = 0;
29
+
30
+ private $cdrOffset = 0;
31
+
32
+ public function __construct($filePath, $mode, $cdrSize = 0)
33
+ {
34
+ $this->filePath = $filePath;
35
+ $this->mode = $mode;
36
+ $this->fileHandle = @fopen($filePath, $mode.'b');
37
+ $this->clear();
38
+
39
+ if ($cdrSize) {
40
+ $this->cdrFilesCount = $cdrSize;
41
+ }
42
+
43
+ if ($mode == 'a') {
44
+
45
+ $cdrPath = $filePath.'.cdr';
46
+
47
+ $this->cdrFileHandle = @fopen($cdrPath, $mode.'b');
48
+ }
49
+ }
50
+
51
+ public function setDelegate(SGArchiveDelegate $delegate)
52
+ {
53
+ $this->delegate = $delegate;
54
+ }
55
+
56
+ public function getCdrFilesCount()
57
+ {
58
+ return $this->cdrFilesCount;
59
+ }
60
+
61
+ public function addFileFromPath($filename, $path)
62
+ {
63
+ $headerSize = 0;
64
+ $len = 0;
65
+ $zlen = 0;
66
+ $start = 0;
67
+
68
+ $fp = fopen($path, 'rb');
69
+ $fileSize = backupGuardRealFilesize($path);
70
+
71
+ $state = $this->delegate->getState();
72
+ $offset = $state->getOffset();
73
+
74
+ if (!$state->getInprogress()) {
75
+ $headerSize = $this->addFileHeader();
76
+ }
77
+ else{
78
+ $headerSize = $state->getHeaderSize();
79
+ $this->fileOffset = $state->getFileOffsetInArchive();
80
+ }
81
+
82
+ $this->ranges = $state->getRanges();
83
+ if (count($this->ranges)) {
84
+ $range = end($this->ranges); //get last range of file
85
+
86
+ $start += $range['start'] + $range['size'];
87
+ $zlen = $start; // get file compressed size before reload
88
+ }
89
+
90
+ fseek($fp, $offset); // move to point before reload
91
+ //read file in small chunks
92
+ while ($offset < $fileSize)
93
+ {
94
+ $data = fread($fp, self::CHUNK_SIZE);
95
+ if ($data === '') {
96
+ //When fread fails to read and compress on fly
97
+ if ($zlen == 0 && $fileSize != 0 && strlen($data) == 0) {
98
+ $this->delegate->warn('Failed to read file: '.basename($filename));
99
+ }
100
+ break;
101
+ }
102
+
103
+ $data = gzdeflate($data);
104
+ $zlen += strlen($data);
105
+ $sgArchiveSize = backupGuardRealFilesize($this->filePath);
106
+ $sgArchiveSize += strlen($data);
107
+
108
+ if($sgArchiveSize > SG_ARCHIVE_MAX_SIZE_32) {
109
+ SGBoot::checkRequirement('intSize');
110
+ }
111
+
112
+ $this->write($data);
113
+
114
+ array_push($this->ranges, array(
115
+ 'start' => $start,
116
+ 'size' => strlen($data)
117
+ ));
118
+ $offset = ftell($fp);
119
+
120
+ $start += strlen($data);
121
+
122
+ SGPing::update();
123
+ $shouldReload = $this->delegate->shouldReload();
124
+ if ($shouldReload) {
125
+ $this->delegate->saveStateData(SG_STATE_ACTION_COMPRESSING_FILES, $this->ranges, $offset, $headerSize, true, $this->fileOffset);
126
+
127
+ if (backupGuardIsReloadEnabled()) {
128
+ @fclose($fp);
129
+ @fclose($this->fileHandle);
130
+ @fclose($this->cdrFileHandle);
131
+
132
+ $this->delegate->reload();
133
+ }
134
+ }
135
+ }
136
+
137
+ if ($state->getInprogress()) {
138
+ $headerSize = $state->getHeaderSize();
139
+ }
140
+
141
+ SGPing::update();
142
+
143
+ fclose($fp);
144
+
145
+ $this->addFileToCdr($filename, $zlen, $len, $headerSize);
146
+ }
147
+
148
+ public function addFile($filename, $data)
149
+ {
150
+ $headerSize = $this->addFileHeader();
151
+
152
+ if ($data)
153
+ {
154
+ $data = gzdeflate($data);
155
+ $this->write($data);
156
+ }
157
+
158
+ $zlen = strlen($data);
159
+ $len = 0;
160
+
161
+ $this->addFileToCdr($filename, $zlen, $len, $headerSize);
162
+ }
163
+
164
+ private function addFileHeader()
165
+ {
166
+ //save extra
167
+ $extra = '';
168
+
169
+ $extraLengthInBytes = 4;
170
+ $this->write($this->packToLittleEndian(strlen($extra), $extraLengthInBytes).$extra);
171
+
172
+ return $extraLengthInBytes+strlen($extra);
173
+ }
174
+
175
+ private function addFileToCdr($filename, $zlen, $len, $headerSize)
176
+ {
177
+ //store cdr data for later use
178
+ $this->addToCdr($filename, $zlen, $len);
179
+
180
+ $this->fileOffset += $headerSize + $zlen;
181
+ }
182
+
183
+ public function finalize()
184
+ {
185
+ $this->addFooter();
186
+
187
+ fclose($this->fileHandle);
188
+
189
+ $this->clear();
190
+ }
191
+
192
+ private function addFooter()
193
+ {
194
+ $footer = '';
195
+
196
+ //save version
197
+ $footer .= $this->packToLittleEndian(self::VERSION, 1);
198
+
199
+ $tables = SGConfig::get('SG_BACKUPED_TABLES');
200
+
201
+ if ($tables) {
202
+ $table = json_encode($tables);
203
+ }
204
+ else {
205
+ $tables = "";
206
+ }
207
+
208
+ $multisitePath = "";
209
+ $multisiteDomain = "";
210
+
211
+ if (SG_ENV_ADAPTER == SG_ENV_WORDPRESS) {
212
+ // in case of multisite save old path and domain for later usage
213
+ if (is_multisite()) {
214
+ $multisitePath = PATH_CURRENT_SITE;
215
+ $multisiteDomain = DOMAIN_CURRENT_SITE;
216
+ }
217
+ }
218
+
219
+ //save db prefix, site and home url for later use
220
+ $extra = json_encode(array(
221
+ 'siteUrl' => get_site_url(),
222
+ 'home' => get_home_url(),
223
+ 'dbPrefix' => SG_ENV_DB_PREFIX,
224
+ 'tables' => $tables,
225
+ 'method' => SGConfig::get('SG_BACKUP_TYPE'),
226
+ 'multisitePath' => $multisitePath,
227
+ 'multisiteDomain' => $multisiteDomain,
228
+ 'selectivRestoreable' => true,
229
+ 'phpVersion' => phpversion()
230
+ ));
231
+
232
+ //extra size
233
+ $footer .= $this->packToLittleEndian(strlen($extra), 4).$extra;
234
+
235
+ //save cdr size
236
+ $footer .= $this->packToLittleEndian($this->cdrFilesCount, 4);
237
+
238
+ $this->write($footer);
239
+
240
+ //save cdr
241
+ $cdrLen = $this->writeCdr();
242
+
243
+ //save offset to the start of footer
244
+ $len = $cdrLen+strlen($extra)+13;
245
+ $this->write($this->packToLittleEndian($len, 4));
246
+ }
247
+
248
+ private function writeCdr()
249
+ {
250
+ @fclose($this->cdrFileHandle);
251
+
252
+ $cdrLen = 0;
253
+ $fp = @fopen($this->filePath.'.cdr', 'rb');
254
+
255
+ while (!feof($fp))
256
+ {
257
+ $data = fread($fp, self::CHUNK_SIZE);
258
+ $cdrLen += strlen($data);
259
+ $this->write($data);
260
+ }
261
+
262
+ @fclose($fp);
263
+ @unlink($this->filePath.'.cdr');
264
+
265
+ return $cdrLen;
266
+ }
267
+
268
+ private function clear()
269
+ {
270
+ $this->cdr = array();
271
+ $this->fileOffset = 0;
272
+ $this->cdrFilesCount = 0;
273
+ }
274
+
275
+ private function addToCdr($filename, $compressedLength, $uncompressedLength)
276
+ {
277
+ $rec = $this->packToLittleEndian(0, 4); //crc (not used in this version)
278
+ $rec .= $this->packToLittleEndian(strlen($filename), 2);
279
+ $rec .= $filename;
280
+ // file offset, compressed length, uncompressed length all are writen in 8 bytes to cover big integer size
281
+ $rec .= $this->packToLittleEndian($this->fileOffset, 8);
282
+ $rec .= $this->packToLittleEndian($compressedLength, 8);
283
+ $rec .= $this->packToLittleEndian($uncompressedLength, 8); //uncompressed size (not used in this version)
284
+ $rec .= $this->packToLittleEndian(count($this->ranges), 4);
285
+
286
+ foreach ($this->ranges as $range) {
287
+ // start and size all are writen in 8 bytes to cover big integer size
288
+ $rec .= $this->packToLittleEndian($range['start'], 8);
289
+ $rec .= $this->packToLittleEndian($range['size'], 8);
290
+ }
291
+
292
+ fwrite($this->cdrFileHandle, $rec);
293
+ fflush($this->cdrFileHandle);
294
+
295
+ $this->cdrFilesCount++;
296
+ }
297
+
298
+ private function isEnoughFreeSpaceOnDisk($dataSize)
299
+ {
300
+ $freeSpace = @disk_free_space(SG_APP_ROOT_DIRECTORY);
301
+
302
+ if ($freeSpace === false || $freeSpace === null) {
303
+ return true;
304
+ }
305
+
306
+ if ($freeSpace < $dataSize) {
307
+ return false;
308
+ }
309
+
310
+ return true;
311
+ }
312
+
313
+ private function write($data)
314
+ {
315
+ $isEnoughFreeSpaceOnDisk = $this->isEnoughFreeSpaceOnDisk(strlen($data));
316
+ if (!$isEnoughFreeSpaceOnDisk) {
317
+ throw new SGExceptionIO('Failed to write in the archive due to not sufficient disk free space.');
318
+ }
319
+
320
+ $result = fwrite($this->fileHandle, $data);
321
+ if ($result === FALSE) {
322
+ throw new SGExceptionIO('Failed to write in archive');
323
+ }
324
+ fflush($this->fileHandle);
325
+ }
326
+
327
+ private function read($length)
328
+ {
329
+ $result = fread($this->fileHandle, $length);
330
+ if ($result === FALSE) {
331
+ throw new SGExceptionIO('Failed to read from archive');
332
+ }
333
+ return $result;
334
+ }
335
+
336
+ private function packToLittleEndian($value, $size = 4)
337
+ {
338
+ if (is_int($value))
339
+ {
340
+ $size *= 2; //2 characters for each byte
341
+ $value = str_pad(dechex($value), $size, '0', STR_PAD_LEFT);
342
+ return strrev(pack('H'.$size, $value));
343
+ }
344
+
345
+ $hex = str_pad($value->toHex(), 16, '0', STR_PAD_LEFT);
346
+
347
+ $high = substr($hex, 0, 8);
348
+ $low = substr($hex, 8, 8);
349
+
350
+ $high = strrev(pack('H8', $high));
351
+ $low = strrev(pack('H8', $low));
352
+
353
+ return $low.$high;
354
+ }
355
+
356
+ public function getArchiveHeaders()
357
+ {
358
+ return $this->extractHeaders();
359
+ }
360
+
361
+ public function getFilesList()
362
+ {
363
+ $list = array();
364
+ $cdrSize = hexdec($this->unpackLittleEndian($this->read(4), 4));
365
+ $this->cdrOffset = ftell($this->fileHandle);
366
+
367
+ for($i = 0; $i < $cdrSize; $i++) {
368
+ $el = $this->getNextCdrElement($this->cdrOffset);
369
+ array_push($list, $el[0]);
370
+ }
371
+ return $list;
372
+ }
373
+
374
+ public function getTreefromList($list, $limit = "")
375
+ {
376
+ $tree = array();
377
+ if(end($list) == "./sql") {
378
+ array_pop($list);
379
+ }
380
+ for($i=0; $i < count($list); $i++) {
381
+ if(!backupGuardStringStartsWith($list[$i], $limit)) {
382
+ continue;
383
+ }
384
+ $path = substr($list[$i], strlen($limit));
385
+ $path = explode(DIRECTORY_SEPARATOR, $path);
386
+ $exists = false;
387
+ foreach($tree as $el) {
388
+ if ($path[0] == $el->name) {
389
+ $exists = true;
390
+ break;
391
+ }
392
+ }
393
+ if(!$exists) {
394
+ $node = new stdClass();
395
+ $node->name = $path[0];
396
+ if(count($path) > 1){
397
+ $node->type = "folder";
398
+ }else{
399
+ $node->type = "file";
400
+ }
401
+ array_push($tree,$node);
402
+ }
403
+
404
+ }
405
+ return $tree;
406
+ }
407
+
408
+ public function extractTo($destinationPath, $state = null)
409
+ {
410
+ $this->state = $state;
411
+ $action = $state->getAction();
412
+
413
+ if ($action == SG_STATE_ACTION_PREPARING_STATE_FILE) {
414
+ $this->extract($destinationPath);
415
+ }
416
+ else {
417
+ $this->continueExtract($destinationPath);
418
+ }
419
+ }
420
+
421
+ private function extractHeaders()
422
+ {
423
+ //read offset
424
+ fseek($this->fileHandle, -4, SEEK_END);
425
+ $offset = hexdec($this->unpackLittleEndian($this->read(4), 4));
426
+
427
+ //read version
428
+ fseek($this->fileHandle, -$offset, SEEK_END);
429
+ $version = hexdec($this->unpackLittleEndian($this->read(1), 1));
430
+ SGConfig::set('SG_CURRENT_ARCHIVE_VERSION', $version);
431
+
432
+ //read extra size (not used in this version)
433
+ $extraSize = hexdec($this->unpackLittleEndian($this->read(4), 4));
434
+
435
+ //read extra
436
+ $extra = array();
437
+ if ($extraSize > 0) {
438
+ $extra = $this->read($extraSize);
439
+ $extra = json_decode($extra, true);
440
+
441
+ SGConfig::set('SG_OLD_SITE_URL', $extra['siteUrl']);
442
+ SGConfig::set('SG_OLD_DB_PREFIX', $extra['dbPrefix']);
443
+
444
+ if (isset($extra['phpVersion'])) {
445
+ SGConfig::set('SG_OLD_PHP_VERSION', $extra['phpVersion']);
446
+ }
447
+
448
+ SGConfig::set('SG_BACKUPED_TABLES', $extra['tables']);
449
+ SGConfig::set('SG_BACKUP_TYPE', $extra['method']);
450
+
451
+ SGConfig::set('SG_MULTISITE_OLD_PATH', $extra['multisitePath']);
452
+ SGConfig::set('SG_MULTISITE_OLD_DOMAIN', $extra['multisiteDomain']);
453
+ }
454
+
455
+ $extra['version'] = $version;
456
+ return $extra;
457
+ }
458
+
459
+ private function extract($destinationPath)
460
+ {
461
+ $extra = $this->extractHeaders();
462
+ $version = $extra['version'];
463
+
464
+ $this->delegate->didExtractArchiveMeta($extra);
465
+
466
+ $isMultisite = backupGuardIsMultisite();
467
+ $archiveIsMultisite = $extra['multisitePath'] != '' || $extra['multisiteDomain'] != '';
468
+
469
+ if (SG_ENV_ADAPTER == SG_ENV_WORDPRESS) {
470
+ if ($archiveIsMultisite && !$isMultisite) {
471
+ throw new SGExceptionMigrationError("In order to restore this archive you should set up Multisite WordPress!");
472
+ }
473
+ elseif (!$archiveIsMultisite && $isMultisite) {
474
+ throw new SGExceptionMigrationError("In order to restore this archive you should set up a Standard instead of Multisite WordPress!");
475
+ }
476
+ }
477
+
478
+ if ($version >= SG_MIN_SUPPORTED_ARCHIVE_VERSION && $version <= SG_MAX_SUPPORTED_ARCHIVE_VERSION) {
479
+ if( !SGBoot::isFeatureAvailable('BACKUP_WITH_MIGRATION') ) {
480
+ if ($extra['method'] != SG_BACKUP_METHOD_MIGRATE) {
481
+ if ($extra['siteUrl'] == SG_SITE_URL) {
482
+ if ($extra['dbPrefix'] != SG_ENV_DB_PREFIX) {
483
+ throw new SGException("Seems you have changed database prefix. You should keep it constant to be able to restore this backup. Setup your WordPress installation with ".$extra['dbPrefix']." datbase prefix.");
484
+ }
485
+ }
486
+ else {
487
+ throw new SGExceptionMigrationError("You should install <b>BackupGuard Pro</b> to be able to migrate the website. More detailed information regarding features included in <b>Free</b> and <b>Pro</b> versions you can find here: <a href='".SG_BACKUP_SITE_URL."'>".SG_BACKUP_SITE_URL."</a>");
488
+ }
489
+ }
490
+ else {
491
+ throw new SGExceptionMigrationError("You should install <b>BackupGuard Pro</b> to be able to restore a package designed for migration.More detailed information regarding features included in <b>Free</b> and <b>Pro</b> versions you can find here: <a href='".SG_BACKUP_SITE_URL."'>".SG_BACKUP_SITE_URL."</a>");
492
+ }
493
+ }
494
+ }
495
+ else {
496
+ throw new SGExceptionBadRequest('Invalid SGArchive file');
497
+ }
498
+
499
+ //read cdr size
500
+ $this->cdrFilesCount = hexdec($this->unpackLittleEndian($this->read(4), 4));
501
+
502
+ $this->delegate->didStartRestoreFiles();
503
+ $this->delegate->didCountFilesInsideArchive($this->cdrFilesCount);
504
+
505
+ // $this->extractCdr($cdrSize, $destinationPath);
506
+ $this->cdrOffset = ftell($this->fileHandle);
507
+ $this->extractFiles($destinationPath);
508
+ }
509
+
510
+ private function continueExtract($destinationPath)
511
+ {
512
+ $this->fileOffset = $this->state->getOffset();
513
+ fseek($this->fileHandle, $this->fileOffset);
514
+ $this->extractFiles($destinationPath);
515
+ }
516
+
517
+ private function getNextCdrElement($offset)
518
+ {
519
+ fseek($this->fileHandle, $this->cdrOffset);
520
+ //read crc (not used in this version)
521
+ $this->read(4);
522
+
523
+ //read filename
524
+ $filenameLen = hexdec($this->unpackLittleEndian($this->read(2), 2));
525
+ $filename = $this->read($filenameLen);
526
+ $filename = $this->delegate->getCorrectCdrFilename($filename);
527
+
528
+ //read file offset
529
+ $fileOffsetInArchive = $this->unpackLittleEndian($this->read(8), 8);
530
+ $fileOffsetInArchive = hexdec($fileOffsetInArchive);
531
+
532
+ //read compressed length
533
+ $zlen = $this->unpackLittleEndian($this->read(8), 8);
534
+ $zlen = hexdec($zlen);
535
+
536
+ //read uncompressed length (not used in this version)
537
+ $this->read(8);
538
+
539
+ $rangeLen = hexdec($this->unpackLittleEndian($this->read(4), 4));
540
+
541
+ $ranges = array();
542
+ for ($i=0; $i < $rangeLen; $i++) {
543
+ $start = $this->unpackLittleEndian($this->read(8), 8);
544
+ $start = hexdec($start);
545
+
546
+ $size = $this->unpackLittleEndian($this->read(8), 8);
547
+ $size = hexdec($size);
548
+
549
+ $ranges[] = array(
550
+ 'start' => $start,
551
+ 'size' => $size
552
+ );
553
+ }
554
+
555
+ $this->cdrOffset = ftell($this->fileHandle);
556
+ return array($filename, $zlen, $ranges, $fileOffsetInArchive);
557
+ }
558
+
559
+ private function extractFiles($destinationPath)
560
+ {
561
+ $action = $this->state->getAction();
562
+ if ($action == SG_STATE_ACTION_PREPARING_STATE_FILE) {
563
+ $inprogress = false;
564
+ fseek($this->fileHandle, 0, SEEK_SET);
565
+ }
566
+ else {
567
+ $inprogress = $this->state->getInprogress();
568
+ $this->cdrFilesCount = $this->state->getCdrSize();
569
+ $this->cdrOffset = $this->state->getCdrCursor();
570
+ }
571
+
572
+ $sqlFileEnding = $this->state->getBackupFileName().'/'.$this->state->getBackupFileName().'.sql';
573
+ $restoreMode = $this->state->getRestoreMode();
574
+ $restoreFiles = $this->state->getRestoreFiles();
575
+
576
+ while ($this->cdrFilesCount) {
577
+
578
+ $warningFoundDuringExtract = false;
579
+
580
+ if ($inprogress) {
581
+ $row = $this->state->getCdr();
582
+ }
583
+ else {
584
+ $row = $this->getNextCdrElement($this->cdrOffset);
585
+
586
+ fseek($this->fileHandle, $this->fileOffset);
587
+
588
+ //read extra (not used in this version)
589
+ $this->read(4);
590
+ }
591
+
592
+ $path = $destinationPath . $row[0];
593
+ $path = str_replace('\\', '/', $path);
594
+ $restoreCurrentFile = false;
595
+
596
+ if ($restoreMode == SG_RESTORE_MODE_FILES && $restoreFiles != NULL && count($restoreFiles) > 0) {
597
+ for ($j = 0; $j < count($restoreFiles); $j++) {
598
+ if ($restoreFiles[$j] == "/" || backupGuardStringStartsWith($row[0], $restoreFiles[$j])) {
599
+ $restoreCurrentFile = true;
600
+ break;
601
+ }
602
+ }
603
+ }
604
+
605
+ // check if file should be restored according restore mode selected by user
606
+ if($restoreMode == SG_RESTORE_MODE_FULL || ($restoreMode == SG_RESTORE_MODE_DB && backupGuardStringEndsWith($path,$sqlFileEnding)) || ($restoreMode == SG_RESTORE_MODE_FILES && !backupGuardStringEndsWith($path,$sqlFileEnding) && $restoreCurrentFile)) {
607
+
608
+ if ($path[strlen($path) - 1] != '/') {//it's not an empty directory
609
+ $path = dirname($path);
610
+ }
611
+
612
+ if (!$inprogress) {
613
+ if (!$this->createPath($path)) {
614
+ $ranges = $row[2];
615
+
616
+ //get last range of file
617
+ $range = end($ranges);
618
+ $offset = $range['start'] + $range['size'];
619
+
620
+ // skip file and continue
621
+ fseek($this->fileHandle, $offset, SEEK_CUR);
622
+ $this->delegate->didFindExtractError('Could not create directory: ' . dirname($path));
623
+ continue;
624
+ }
625
+ }
626
+
627
+ $path = $destinationPath . $row[0];
628
+ $tmpPath = $path . ".sgbpTmpFile";
629
+
630
+ if (!$inprogress) {
631
+ $this->delegate->didStartExtractFile($path);
632
+
633
+ if (!is_writable(dirname($tmpPath))) {
634
+ $this->delegate->didFindExtractError('Destination path is not writable: ' . dirname($path));
635
+ }
636
+ }
637
+
638
+ if (!$inprogress) {
639
+ $tmpFp = @fopen($tmpPath, 'wb');
640
+ }
641
+ else {
642
+ $tmpFp = @fopen($tmpPath, 'ab');
643
+ }
644
+
645
+ $zlen = $row[1];
646
+ SGPing::update();
647
+ $ranges = $row[2];
648
+
649
+ if ($inprogress) {
650
+ $this->rangeCursor = $this->state->getRangeCursor();
651
+ }
652
+ else {
653
+ $this->rangeCursor = 0;
654
+ }
655
+
656
+ for ($i = $this->rangeCursor; $i < count($ranges); $i++) {
657
+ $start = $ranges[$i]['start'];
658
+ $size = $ranges[$i]['size'];
659
+
660
+ $data = $this->read($size);
661
+ $data = gzinflate($data);
662
+
663
+ //If gzinflate() failed to uncompress, skip the current file and continue extraction
664
+ if (!$data) {
665
+ $warningFoundDuringExtract = true;
666
+ $this->delegate->didFindExtractError('Failed to extract path: ' . $path);
667
+
668
+ //Assume we've extracted the current file
669
+ for ($idx = $i + 1; $idx < count($ranges); $idx++) {
670
+ $start = $ranges[$idx]['start'];
671
+ $size = $ranges[$idx]['size'];
672
+
673
+ fseek($this->fileHandle, $size, SEEK_CUR);
674
+ }
675
+
676
+ $inprogress = false;
677
+ @fclose($tmpFp);
678
+
679
+ SGPing::update();
680
+
681
+ break;
682
+ }
683
+ else {
684
+ $inprogress = true;
685
+ if (($i + 1) == count($ranges)) {
686
+ $inprogress = false;
687
+ }
688
+ if (is_resource($tmpFp)) {
689
+ $isEnoughFreeSpaceOnDisk = $this->isEnoughFreeSpaceOnDisk(strlen($data));
690
+ if (!$isEnoughFreeSpaceOnDisk) {
691
+ throw new SGExceptionIO('Failed to write in the archive due to not sufficient disk free space.');
692
+ }
693
+
694
+ fwrite($tmpFp, $data);
695
+ fflush($tmpFp);
696
+
697
+ $shouldReload = $this->delegate->shouldReload();
698
+
699
+ //restore with reloads will only work in external mode
700
+ if ($shouldReload && SGExternalRestore::isEnabled()) {
701
+
702
+ if (!$inprogress) {
703
+ $this->cdrFilesCount--;
704
+
705
+ @rename($tmpPath, $path);
706
+ $this->delegate->didExtractFile($path);
707
+ }
708
+
709
+ $token = $this->delegate->getToken();
710
+ $progress = $this->delegate->getProgress();
711
+
712
+ $this->fileOffset = ftell($this->fileHandle);
713
+
714
+ $this->state->setRestoreMode($restoreMode);
715
+ $this->state->setOffset($this->fileOffset);
716
+ $this->state->setInprogress($inprogress);
717
+ $this->state->setToken($token);
718
+ $this->state->setProgress($progress);
719
+ $this->state->setAction(SG_STATE_ACTION_RESTORING_FILES);
720
+ $this->state->setRangeCursor($i + 1);
721
+
722
+ $this->state->setCdr($row);
723
+ $this->state->setCdrSize($this->cdrFilesCount);
724
+ $this->state->setCdrCursor($this->cdrOffset);
725
+ $this->state->save();
726
+
727
+ SGPing::update();
728
+
729
+ @fclose($tmpFp);
730
+ @fclose($this->fileHandle);
731
+
732
+ $this->delegate->reload();
733
+ }
734
+ }
735
+ }
736
+ SGPing::update();
737
+ }
738
+
739
+ if (is_resource($tmpFp)) {
740
+ @fclose($tmpFp);
741
+ }
742
+
743
+ if (!$warningFoundDuringExtract) {
744
+ @rename($tmpPath, $path);
745
+ }
746
+ else {
747
+ @unlink($tmpPath);
748
+ }
749
+
750
+ $this->delegate->didExtractFile($path);
751
+ $this->fileOffset = ftell($this->fileHandle);
752
+ }
753
+ else {
754
+ //if file should not be restored skip it and go to the next file
755
+ $ranges = $row[2];
756
+
757
+ for ($idx = 0; $idx < count($ranges); $idx++) {
758
+
759
+ $size = $ranges[$idx]['size'];
760
+
761
+ fseek($this->fileHandle, $size, SEEK_CUR);
762
+ }
763
+ $this->fileOffset = ftell($this->fileHandle);
764
+ }
765
+
766
+ $this->cdrFilesCount--;
767
+ }
768
+ }
769
+
770
+ private function unpackLittleEndian($data, $size)
771
+ {
772
+ $size *= 2; //2 characters for each byte
773
+
774
+ $data = unpack('H'.$size, strrev($data));
775
+ return $data[1];
776
+ }
777
+
778
+ private function createPath($path)
779
+ {
780
+ if (is_dir($path)) return true;
781
+ $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1);
782
+ $return = $this->createPath($prev_path);
783
+ if ($return && is_writable($prev_path))
784
+ {
785
+ if (!@mkdir($path)) return false;
786
+
787
+ @chmod($path, 0777);
788
+ return true;
789
+ }
790
+
791
+ return false;
792
+ }
793
+
794
+ public function getVersion()
795
+ {
796
+ //read offset
797
+ fseek($this->fileHandle, -4, SEEK_END);
798
+ $offset = hexdec($this->unpackLittleEndian($this->read(4), 4));
799
+
800
+ //read version
801
+ fseek($this->fileHandle, -$offset, SEEK_END);
802
+ $version = hexdec($this->unpackLittleEndian($this->read(1), 1));
803
+
804
+ return $version;
805
+ }
806
+ }
com/lib/SGMysqldump.php CHANGED
@@ -1,1558 +1,1558 @@
1
- <?php
2
- /**
3
- * SGMysqldump Class Doc Comment
4
- *
5
- * @category Library
6
- * @package Ifsnop\Mysqldump
7
- * @author Michael J. Calkins <clouddueling@github.com>
8
- * @author Diego Torres <ifsnop@github.com>
9
- * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10
- * @link https://github.com/ifsnop/mysqldump-php
11
- *
12
- */
13
-
14
- interface SGIMysqldumpDelegate
15
- {
16
- public function didExportRow();
17
- }
18
-
19
- class SGMysqldump
20
- {
21
-
22
- // Same as mysqldump
23
- const MAXLINESIZE = 1000000;
24
-
25
- // Available compression methods as constants
26
- const GZIP = 'Gzip';
27
- const BZIP2 = 'Bzip2';
28
- const NONE = 'None';
29
-
30
- // Available connection strings
31
- const UTF8 = 'utf8';
32
- const UTF8MB4 = 'utf8mb4';
33
-
34
- // This can be set both on constructor or manually
35
- public $db;
36
- public $fileName;
37
-
38
- // Internal stuff
39
- private $tables = array();
40
- private $views = array();
41
- private $triggers = array();
42
- private $dbHandler;
43
- private $dbType;
44
- private $compressManager;
45
- private $typeAdapter;
46
- private $dumpSettings = array();
47
- private $version;
48
- private $tableColumnTypes = array();
49
- private $delegate = null;
50
- private $excludeTables = array();
51
-
52
- private $cursor = 0;
53
- private $state = null;
54
- private $inprogress = false;
55
- private $backedUpTables = array();
56
-
57
- /**
58
- * Constructor of SGMysqldump. Note that in the case of an SQLite database
59
- * connection, the filename must be in the $db parameter.
60
- *
61
- * @param string $db Database name
62
- * @param string $type SQL database type
63
- * @param array $dumpSettings SQL database settings
64
- */
65
- public function __construct(
66
- $dbHandler,
67
- $db = '',
68
- $type = 'mysql',
69
- $dumpSettings = array()
70
- ) {
71
- $dumpSettingsDefault = array(
72
- 'include-tables' => array(),
73
- 'exclude-tables' => array(),
74
- 'compress' => SGMysqldump::NONE,
75
- 'no-data' => false,
76
- 'add-drop-table' => false,
77
- 'single-transaction' => true,
78
- 'lock-tables' => true,
79
- 'add-locks' => true,
80
- 'extended-insert' => true,
81
- 'disable-keys' => true,
82
- 'where' => '',
83
- 'no-create-info' => false,
84
- 'skip-triggers' => false,
85
- 'add-drop-trigger' => true,
86
- 'hex-blob' => true,
87
- 'databases' => false,
88
- 'add-drop-database' => false,
89
- 'skip-tz-utz' => false,
90
- 'no-autocommit' => true,
91
- 'default-character-set' => SGMysqldump::UTF8,
92
- 'skip-comments' => false,
93
- 'skip-dump-date' => false,
94
- /* deprecated */
95
- 'disable-foreign-keys-check' => true
96
- );
97
-
98
- $this->db = $db;
99
- $this->dbHandler = $dbHandler;
100
- $this->dbType = strtolower($type);
101
- $this->dumpSettings = self::array_replace_recursive($dumpSettingsDefault, $dumpSettings);
102
- $this->excludeTables = $dumpSettings['exclude-tables'];
103
-
104
- $diff = array_diff(array_keys($this->dumpSettings), array_keys($dumpSettingsDefault));
105
- if (count($diff)>0) {
106
- throw new Exception("Unexpected value in dumpSettings: (" . implode(",", $diff) . ")");
107
- }
108
-
109
- // Create a new compressManager to manage compressed output
110
- $this->compressManager = CompressManagerFactory::create($this->dumpSettings['compress']);
111
- }
112
-
113
- public function setDelegate(SGIMysqldumpDelegate $delegate)
114
- {
115
- $this->delegate = $delegate;
116
- }
117
-
118
- private function getState()
119
- {
120
- return $this->delegate->getState();
121
- }
122
-
123
- private function shouldReload()
124
- {
125
- return $this->delegate->shouldReload();
126
- }
127
-
128
- /**
129
- * Custom array_replace_recursive to be used if PHP < 5.3
130
- * Replaces elements from passed arrays into the first array recursively
131
- *
132
- * @param array $array1 The array in which elements are replaced
133
- * @param array $array2 The array from which elements will be extracted
134
- *
135
- * @return array Returns an array, or NULL if an error occurs.
136
- */
137
- public static function array_replace_recursive($array1, $array2)
138
- {
139
- if (function_exists('array_replace_recursive')) {
140
- return array_replace_recursive($array1, $array2);
141
- }
142
-
143
- foreach ($array2 as $key => $value) {
144
- if (is_array($value)) {
145
- $array1[$key] = self::array_replace_recursive($array1[$key], $value);
146
- } else {
147
- $array1[$key] = $value;
148
- }
149
- }
150
- return $array1;
151
- }
152
-
153
- /**
154
- * Connect with PDO
155
- *
156
- * @return null
157
- */
158
- private function connect()
159
- {
160
- $this->dbHandler->query("SET NAMES " . $this->dumpSettings['default-character-set']);
161
- $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler);
162
- }
163
-
164
- /**
165
- * Main call
166
- *
167
- * @param string $filename Name of file to write sql dump to
168
- * @return null
169
- */
170
- public function start($filename)
171
- {
172
- $this->state = $this->getState();
173
- $this->fileName = $filename;
174
-
175
- // Connect to database
176
- $this->connect();
177
-
178
- // Create output file
179
- $this->compressManager->open($this->fileName);
180
-
181
- if ($this->state->getAction() == SG_STATE_ACTION_PREPARING_STATE_FILE) {
182
- // Write some basic info to output file
183
- $this->compressManager->write($this->getDumpFileHeader());
184
-
185
- // Store server settings and use sanner defaults to dump
186
- $this->compressManager->write(
187
- $this->typeAdapter->backup_parameters($this->dumpSettings)
188
- );
189
-
190
- if ($this->dumpSettings['databases']) {
191
- $this->compressManager->write(
192
- $this->typeAdapter->getDatabaseHeader($this->db)
193
- );
194
- if ($this->dumpSettings['add-drop-database']) {
195
- $this->compressManager->write(
196
- $this->typeAdapter->add_drop_database($this->db)
197
- );
198
- }
199
- }
200
- }
201
-
202
- // Get table, view and trigger structures from database
203
- $this->getDatabaseStructure();
204
-
205
- if ($this->state->getAction() == SG_STATE_ACTION_PREPARING_STATE_FILE) {
206
- if ($this->dumpSettings['databases']) {
207
- $this->compressManager->write(
208
- $this->typeAdapter->databases($this->db)
209
- );
210
- }
211
-
212
- // If there still are some tables/views in include-tables array,
213
- // that means that some tables or views weren't found.
214
- // Give proper error and exit.
215
- if (0 < count($this->dumpSettings['include-tables'])) {
216
- $name = implode(",", $this->dumpSettings['include-tables']);
217
- throw new SGException("Table or View (" . $name . ") not found in database");
218
- }
219
- }
220
-
221
- $this->exportTables();
222
- $this->exportViews();
223
- $this->exportTriggers();
224
-
225
- // Restore saved parameters
226
- $this->compressManager->write(
227
- $this->typeAdapter->restore_parameters($this->dumpSettings)
228
- );
229
- // Write some stats to output file
230
- $this->compressManager->write($this->getDumpFileFooter());
231
- // Close output file
232
- $this->compressManager->close();
233
- }
234
-
235
- /**
236
- * Returns header for dump file
237
- *
238
- * @return string
239
- */
240
- private function getDumpFileHeader()
241
- {
242
- $header = '';
243
- if (!$this->dumpSettings['skip-comments']) {
244
- // Some info about software, source and time
245
- $header = '';
246
-
247
- if (!empty($this->version)) {
248
- $header .= "-- Server version \t" . $this->version . PHP_EOL;
249
- }
250
-
251
- $header .= "-- Date: " . @date('r') . PHP_EOL . PHP_EOL;
252
- }
253
- return $header;
254
- }
255
-
256
- /**
257
- * Returns footer for dump file
258
- *
259
- * @return string
260
- */
261
- private function getDumpFileFooter()
262
- {
263
- $footer = '';
264
- if (!$this->dumpSettings['skip-comments']) {
265
- $footer .= '-- Dump completed';
266
- if (!$this->dumpSettings['skip-dump-date']) {
267
- $footer .= ' on: ' . @date('r');
268
- }
269
- $footer .= PHP_EOL;
270
- }
271
-
272
- return $footer;
273
- }
274
-
275
- /**
276
- * Reads table and views names from database.
277
- * Fills $this->tables array so they will be dumped later.
278
- *
279
- * @return null
280
- */
281
- private function getDatabaseStructure()
282
- {
283
- // Listing all tables from database
284
- if (empty($this->dumpSettings['include-tables'])) {
285
- // include all tables for now, blacklisting happens later
286
- $arr = $this->dbHandler->query($this->typeAdapter->show_tables($this->db));
287
- foreach ($arr as $row) {
288
- // Push wp_options table to front to solve restore related bug
289
- if ($row['tbl_name'] != SG_ENV_DB_PREFIX.'options') {
290
- array_push($this->tables, $row['tbl_name']);
291
- }
292
- else {
293
- array_unshift($this->tables, $row['tbl_name']);
294
- }
295
- }
296
- } else {
297
- // include only the tables mentioned in include-tables
298
- $arr = $this->dbHandler->query($this->typeAdapter->show_tables($this->db));
299
- foreach ($arr as $row) {
300
- if (in_array($row['tbl_name'], $this->dumpSettings['include-tables'], true)) {
301
- array_push($this->tables, $row['tbl_name']);
302
- $elem = array_search(
303
- $row['tbl_name'],
304
- $this->dumpSettings['include-tables']
305
- );
306
- unset($this->dumpSettings['include-tables'][$elem]);
307
- }
308
- }
309
- }
310
-
311
- // Listing all views from database
312
- if (empty($this->dumpSettings['include-tables'])) {
313
- // include all views for now, blacklisting happens later
314
- $arr = $this->dbHandler->query($this->typeAdapter->show_views($this->db));
315
- foreach ($arr as $row) {
316
- array_push($this->views, $row['tbl_name']);
317
- }
318
- } else {
319
- // include only the tables mentioned in include-tables
320
- $arr = $this->dbHandler->query($this->typeAdapter->show_views($this->db));
321
- foreach ($arr as $row) {
322
- if (in_array($row['tbl_name'], $this->dumpSettings['include-tables'], true)) {
323
- array_push($this->views, $row['tbl_name']);
324
- $elem = array_search(
325
- $row['tbl_name'],
326
- $this->dumpSettings['include-tables']
327
- );
328
- unset($this->dumpSettings['include-tables'][$elem]);
329
- }
330
- }
331
- }
332
-
333
- // Listing all triggers from database
334
- if (false === $this->dumpSettings['skip-triggers']) {
335
- $arr = $this->dbHandler->query($this->typeAdapter->show_triggers($this->db));
336
- foreach ($arr as $row) {
337
- array_push($this->triggers, $row['Trigger']);
338
- }
339
- }
340
- }
341
-
342
- /**
343
- * Exports all the tables selected from database
344
- *
345
- * @return null
346
- */
347
- private function exportTables()
348
- {
349
- if ($this->state->getAction() != SG_STATE_ACTION_PREPARING_STATE_FILE) {
350
- $this->cursor = $this->state->getCursor();
351
- $this->inprogress = $this->state->getInprogress();
352
- $this->backedUpTables = $this->state->getBackedUpTables();
353
- }
354
- else {
355
- $this->cursor = 0;
356
- $this->inprogress = false;
357
- $this->backedUpTables = array();
358
- }
359
-
360
- // Exporting tables one by one
361
- for($i = $this->cursor; $i < count($this->tables); $i++) {
362
- $table = $this->tables[$i];
363
- if (in_array($table, $this->dumpSettings['exclude-tables'], true)) {
364
- $this->cursor += 1;
365
- continue;
366
- }
367
-
368
- if (!$this->inprogress) {
369
- SGBackupLog::writeAction('backup table: '.$table, SG_BACKUP_LOG_POS_START);
370
- $this->getTableStructure($table, false);
371
- }
372
- else {
373
- $this->getTableStructure($table, true);
374
- }
375
-
376
- if (false === $this->dumpSettings['no-data']) {
377
- $this->listValues($table);
378
- }
379
-
380
- $this->backedUpTables[] = $table;
381
- SGBackupLog::writeAction('backup table: '.$table, SG_BACKUP_LOG_POS_END);
382
- }
383
-
384
- SGConfig::set('SG_BACKUPED_TABLES', json_encode($this->backedUpTables));
385
- }
386
-
387
- /**
388
- * Exports all the views found in database
389
- *
390
- * @return null
391
- */
392
- private function exportViews()
393
- {
394
- if (false === $this->dumpSettings['no-create-info']) {
395
- // Exporting views one by one
396
- foreach ($this->views as $view) {
397
- if (in_array($view, $this->dumpSettings['exclude-tables'], true)) {
398
- continue;
399
- }
400
- $this->getViewStructure($view);
401
- }
402
- }
403
- }
404
-
405
- /**
406
- * Exports all the triggers found in database
407
- *
408
- * @return null
409
- */
410
- private function exportTriggers()
411
- {
412
- // Exporting triggers one by one
413
- foreach ($this->triggers as $trigger) {
414
- $this->getTriggerStructure($trigger);
415
- }
416
- }
417
-
418
- /**
419
- * Table structure extractor
420
- *
421
- * @todo move specific mysql code to typeAdapter
422
- * @param string $tableName Name of table to export
423
- * @return null
424
- */
425
- private function getTableStructure($tableName, $skipCreate = false)
426
- {
427
- if (!$skipCreate && !$this->dumpSettings['no-create-info']) {
428
- $ret = '';
429
- if (!$this->dumpSettings['skip-comments']) {
430
- $ret = "--" . PHP_EOL .
431
- "-- Table structure for table `$tableName`" . PHP_EOL .
432
- "--" . PHP_EOL . PHP_EOL;
433
- }
434
- $stmt = $this->typeAdapter->show_create_table($tableName);
435
- $arr = $this->dbHandler->query($stmt);
436
- foreach ($arr as $r) {
437
- $this->compressManager->write($ret);
438
- if ($this->dumpSettings['add-drop-table']) {
439
- $this->compressManager->write(
440
- $this->typeAdapter->drop_table($tableName)
441
- );
442
- }
443
- $this->compressManager->write(
444
- $this->typeAdapter->create_table($r, $this->dumpSettings)
445
- );
446
- break;
447
- }
448
- }
449
-
450
- $columnTypes = array();
451
- $columns = $this->dbHandler->query(
452
- $this->typeAdapter->show_columns($tableName)
453
- );
454
-
455
- foreach($columns as $key => $col) {
456
- $types = $this->typeAdapter->parseColumnType($col);
457
- $columnTypes[$col['Field']] = array(
458
- 'is_numeric'=> $types['is_numeric'],
459
- 'is_blob' => $types['is_blob'],
460
- 'type' => $types['type']
461
- );
462
- }
463
- $this->tableColumnTypes[$tableName] = $columnTypes;
464
- return;
465
- }
466
-
467
- /**
468
- * View structure extractor
469
- *
470
- * @todo move mysql specific code to typeAdapter
471
- * @param string $viewName Name of view to export
472
- * @return null
473
- */
474
- private function getViewStructure($viewName)
475
- {
476
- $ret = '';
477
- if (!$this->dumpSettings['skip-comments']) {
478
- $ret = "--" . PHP_EOL .
479
- "-- Table structure for view `${viewName}`" . PHP_EOL .
480
- "--" . PHP_EOL . PHP_EOL;
481
- }
482
- $this->compressManager->write($ret);
483
- $stmt = $this->typeAdapter->show_create_view($viewName);
484
- $arr = $this->dbHandler->query($stmt);
485
- foreach ($arr as $r) {
486
- if ($this->dumpSettings['add-drop-table']) {
487
- $this->compressManager->write(
488
- $this->typeAdapter->drop_view($viewName)
489
- );
490
- }
491
- $this->compressManager->write(
492
- $this->typeAdapter->create_view($r)
493
- );
494
- break;
495
- }
496
- }
497
-
498
- /**
499
- * Trigger structure extractor
500
- *
501
- * @param string $triggerName Name of trigger to export
502
- * @return null
503
- */
504
- private function getTriggerStructure($triggerName)
505
- {
506
- $stmt = $this->typeAdapter->show_create_trigger($triggerName);
507
- $arr = $this->dbHandler->query($stmt);
508
- foreach ($arr as $r) {
509
- if ($this->dumpSettings['add-drop-trigger']) {
510
- $this->compressManager->write(
511
- $this->typeAdapter->add_drop_trigger($triggerName)
512
- );
513
- }
514
- $this->compressManager->write(
515
- $this->typeAdapter->create_trigger($r)
516
- );
517
- return;
518
- }
519
-
520
- }
521
-
522
-
523
- /**
524
- * Escape values with quotes when needed
525
- *
526
- * @param string $tableName Name of table which contains rows
527
- * @param array $row Associative array of column names and values to be quoted
528
- *
529
- * @return string
530
- */
531
- private function escape($tableName, $row)
532
- {
533
- $ret = array();
534
- $columnTypes = $this->tableColumnTypes[$tableName];
535
- foreach ($row as $colName => $colValue) {
536
- if (is_null($colValue)) {
537
- $ret[] = "NULL";
538
- } elseif ($this->dumpSettings['hex-blob'] && $columnTypes[$colName]['is_blob']) {
539
- if ($columnTypes[$colName]['type'] == 'bit' || !empty($colValue)) {
540
- $ret[] = "0x${colValue}";
541
- } else {
542
- $ret[] = "''";
543
- }
544
- } elseif ($columnTypes[$colName]['is_numeric']) {
545
- $ret[] = $colValue;
546
- } else {
547
- $str = "'".str_replace("'", "''", $colValue)."'";
548
- $str = str_replace("\\", "\\\\", $str);
549
- $ret[] = $str;
550
- }
551
- }
552
- return $ret;
553
- }
554
-
555
- /**
556
- * Table rows extractor
557
- *
558
- * @param string $tableName Name of table to export
559
- *
560
- * @return null
561
- */
562
- private function listValues($tableName)
563
- {
564
- if (!$this->state->getInprogress()) {
565
- $this->prepareListValues($tableName);
566
- }
567
-
568
- $onlyOnce = true;
569
- $lineSize = 0;
570
- $offset = 0;
571
- if ($this->state->getInprogress()) {
572
- $onlyOnce = false;
573
- $offset = $this->state->getOffset();
574
- $lineSize = $this->state->getLineSize();
575
- }
576
-
577
- $colStmt = $this->getColumnStmt($tableName);
578
- $stmt = "SELECT $colStmt FROM `$tableName`";
579
-
580
- if ($this->dumpSettings['where']) {
581
- $stmt .= " WHERE {$this->dumpSettings['where']}";
582
- }
583
-
584
- $limit = SGConfig::get('SG_BACKUP_DATABASE_INSERT_LIMIT')?SGConfig::get('SG_BACKUP_DATABASE_INSERT_LIMIT'):SG_BACKUP_DATABASE_INSERT_LIMIT;
585
-
586
- while (true) {
587
- $st = $this->dbHandler->exec($stmt.' LIMIT '.$offset.','.$limit);
588
-
589
- $row = $this->dbHandler->fetch($st);
590
-
591
- $this->inprogress = true;
592
- if (!$row) {
593
- $this->inprogress = false;
594
- $this->cursor += 1;
595
- $this->delegate->saveStateData(0, $this->cursor, $this->inprogress, 0, $this->backedUpTables);
596
- break;
597
- }
598
-
599
- while ($row) {
600
- $vals = $this->escape($tableName, $row);
601
-
602
- if ($onlyOnce) {
603
- $lineSize += $this->compressManager->write(
604
- "INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
605
- );
606
- $onlyOnce = false;
607
- }
608
- else {
609
- $lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
610
- }
611
- if ($lineSize > self::MAXLINESIZE) {
612
- $onlyOnce = true;
613
- $this->compressManager->write(";/*SGEnd*/" . PHP_EOL);
614
- $lineSize = 0;
615
- }
616
-
617
- if ($this->delegate) {
618
- $this->delegate->didExportRow();
619
- }
620
-
621
- $row = $this->dbHandler->fetch($st);
622
- }
623
-
624
- $offset += $limit;
625
- if ($this->shouldReload()) {
626
- $this->delegate->saveStateData($offset, $this->cursor, $this->inprogress, $lineSize, $this->backedUpTables);
627
-
628
- if (backupGuardIsReloadEnabled()) {
629
- $this->delegate->reload();
630
- }
631
- }
632
- }
633
-
634
- if (!$onlyOnce) {
635
- $this->compressManager->write(";/*SGEnd*/" . PHP_EOL);
636
- }
637
-
638
- $this->endListValues($tableName);
639
- }
640
-
641
- /**
642
- * Table rows extractor, append information prior to dump
643
- *
644
- * @param string $tableName Name of table to export
645
- *
646
- * @return null
647
- */
648
- function prepareListValues($tableName)
649
- {
650
- if (!$this->dumpSettings['skip-comments']) {
651
- $this->compressManager->write(
652
- "--" . PHP_EOL .
653
- "-- Dumping data for table `$tableName`" . PHP_EOL .
654
- "--" . PHP_EOL . PHP_EOL
655
- );
656
- }
657
-
658
- if ($this->dumpSettings['single-transaction']) {
659
- $this->dbHandler->query($this->typeAdapter->setup_transaction());
660
- $this->dbHandler->query($this->typeAdapter->start_transaction());
661
- }
662
-
663
- if ($this->dumpSettings['lock-tables']) {
664
- $this->typeAdapter->lock_table($tableName);
665
- }
666
-
667
- if ($this->dumpSettings['add-locks']) {
668
- $this->compressManager->write(
669
- $this->typeAdapter->start_add_lock_table($tableName)
670
- );
671
- }
672
-
673
- if ($this->dumpSettings['disable-keys']) {
674
- $this->compressManager->write(
675
- $this->typeAdapter->start_add_disable_keys($tableName)
676
- );
677
- }
678
-
679
- // Disable autocommit for faster reload
680
- if ($this->dumpSettings['no-autocommit']) {
681
- $this->compressManager->write(
682
- $this->typeAdapter->start_disable_autocommit()
683
- );
684
- }
685
-
686
- return;
687
- }
688
-
689
- /**
690
- * Table rows extractor, close locks and commits after dump
691
- *
692
- * @param string $tableName Name of table to export
693
- *
694
- * @return null
695
- */
696
- function endListValues($tableName)
697
- {
698
- if ($this->dumpSettings['disable-keys']) {
699
- $this->compressManager->write(
700
- $this->typeAdapter->end_add_disable_keys($tableName)
701
- );
702
- }
703
-
704
- if ($this->dumpSettings['add-locks']) {
705
- $this->compressManager->write(
706
- $this->typeAdapter->end_add_lock_table($tableName)
707
- );
708
- }
709
-
710
- if ($this->dumpSettings['single-transaction']) {
711
- $this->dbHandler->query($this->typeAdapter->commit_transaction());
712
- }
713
-
714
- if ($this->dumpSettings['lock-tables']) {
715
- $this->typeAdapter->unlock_table($tableName);
716
- }
717
-
718
- // Commit to enable autocommit
719
- if ($this->dumpSettings['no-autocommit']) {
720
- $this->compressManager->write(
721
- $this->typeAdapter->end_disable_autocommit()
722
- );
723
- }
724
-
725
- $this->compressManager->write(PHP_EOL);
726
-
727
- return;
728
- }
729
-
730
- /**
731
- * Build SQL List of all columns on current table
732
- *
733
- * @param string $tableName Name of table to get columns
734
- *
735
- * @return string SQL sentence with columns
736
- */
737
- function getColumnStmt($tableName)
738
- {
739
- $colStmt = array();
740
- foreach($this->tableColumnTypes[$tableName] as $colName => $colType) {
741
- if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) {
742
- $colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`";
743
- } else if ($colType['is_blob'] && $this->dumpSettings['hex-blob']) {
744
- $colStmt[] = "HEX(`${colName}`) AS `${colName}`";
745
- } else {
746
- $colStmt[] = "`${colName}`";
747
- }
748
- }
749
- $colStmt = implode(",", $colStmt);
750
-
751
- return $colStmt;
752
- }
753
- }
754
-
755
- /**
756
- * Enum with all available compression methods
757
- *
758
- */
759
- abstract class CompressMethod
760
- {
761
- public static $enums = array(
762
- "None",
763
- "Gzip",
764
- "Bzip2"
765
- );
766
-
767
- /**
768
- * @param string $c
769
- * @return boolean
770
- */
771
- public static function isValid($c)
772
- {
773
- return in_array($c, self::$enums);
774
- }
775
- }
776
-
777
- abstract class CompressManagerFactory
778
- {
779
- /**
780
- * @param string $c
781
- * @return CompressBzip2|CompressGzip|CompressNone
782
- */
783
- public static function create($c)
784
- {
785
- $c = ucfirst(strtolower($c));
786
- if (! CompressMethod::isValid($c)) {
787
- throw new Exception("Compression method ($c) is not defined yet");
788
- }
789
-
790
- $method = __NAMESPACE__ . "\\" . "Compress" . $c;
791
-
792
- return new $method;
793
- }
794
-
795
- public static function prepareToWrite($str)
796
- {
797
- return $str;
798
- }
799
- }
800
-
801
- class CompressBzip2 extends CompressManagerFactory
802
- {
803
- private $fileHandler = null;
804
-
805
- public function __construct()
806
- {
807
- if (! function_exists("bzopen")) {
808
- throw new Exception("Compression is enabled, but bzip2 lib is not installed or configured properly");
809
- }
810
- }
811
-
812
- public function open($filename)
813
- {
814
- $this->fileHandler = bzopen($filename, 'a');
815
- if (false === $this->fileHandler) {
816
- throw new Exception("Output file is not writable");
817
- }
818
-
819
- return true;
820
- }
821
-
822
- public function write($str)
823
- {
824
- $str = self::prepareToWrite($str);
825
-
826
- if (false === ($bytesWritten = bzwrite($this->fileHandler, $str))) {
827
- throw new Exception("Writting to file failed! Probably, there is no more free space left?");
828
- }
829
- return $bytesWritten;
830
- }
831
-
832
- public function close()
833
- {
834
- return bzclose($this->fileHandler);
835
- }
836
- }
837
-
838
- class CompressGzip extends CompressManagerFactory
839
- {
840
- private $fileHandler = null;
841
-
842
- public function __construct()
843
- {
844
- if (! function_exists("gzopen")) {
845
- throw new Exception("Compression is enabled, but gzip lib is not installed or configured properly");
846
- }
847
- }
848
-
849
- public function open($filename)
850
- {
851
- $this->fileHandler = gzopen($filename, "ab");
852
- if (false === $this->fileHandler) {
853
- throw new Exception("Output file is not writable");
854
- }
855
-
856
- return true;
857
- }
858
-
859
- public function write($str)
860
- {
861
- $str = self::prepareToWrite($str);
862
- if (false === ($bytesWritten = gzwrite($this->fileHandler, $str))) {
863
- throw new Exception("Writting to file failed! Probably, there is no more free space left?");
864
- }
865
- return $bytesWritten;
866
- }
867
-
868
- public function close()
869
- {
870
- return gzclose($this->fileHandler);
871
- }
872
- }
873
-
874
- class CompressNone extends CompressManagerFactory
875
- {
876
- private $fileHandler = null;
877
-
878
- public function open($filename)
879
- {
880
- $this->fileHandler = fopen($filename, "ab");
881
-
882
- if (false === $this->fileHandler) {
883
- throw new Exception("Output file is not writable");
884
- }
885
-
886
- return true;
887
- }
888
-
889
- public function write($str)
890
- {
891
- $str = self::prepareToWrite($str);
892
- if (false === ($bytesWritten = fwrite($this->fileHandler, $str))) {
893
- throw new Exception("Writting to file failed! Probably, there is no more free space left?");
894
- }
895
- return $bytesWritten;
896
- }
897
-
898
- public function close()
899
- {
900
- return fclose($this->fileHandler);
901
- }
902
- }
903
-
904
- /**
905
- * Enum with all available TypeAdapter implementations
906
- *
907
- */
908
- abstract class TypeAdapter
909
- {
910
- public static $enums = array(
911
- "Sqlite",
912
- "Mysql"
913
- );
914
-
915
- /**
916
- * @param string $c
917
- * @return boolean
918
- */
919
- public static function isValid($c)
920
- {
921
- return in_array($c, self::$enums);
922
- }
923
- }
924
-
925
- /**
926
- * TypeAdapter Factory
927
- *
928
- */
929
- abstract class TypeAdapterFactory
930
- {
931
- /**
932
- * @param string $c Type of database factory to create (Mysql, Sqlite,...)
933
- * @param PDO $dbHandler
934
- */
935
- public static function create($c, $dbHandler = null)
936
- {
937
- $c = ucfirst(strtolower($c));
938
- if (! TypeAdapter::isValid($c)) {
939
- throw new Exception("Database type support for ($c) not yet available");
940
- }
941
- $method = __NAMESPACE__ . "\\" . "TypeAdapter" . $c;
942
- return new $method($dbHandler);
943
- }
944
-
945
- /**
946
- * function databases Add sql to create and use database
947
- * @todo make it do something with sqlite
948
- */
949
- public function databases()
950
- {
951
- return "";
952
- }
953
-
954
- public function show_create_table($tableName)
955
- {
956
- return "SELECT tbl_name as 'Table', sql as 'Create Table' " .
957
- "FROM sqlite_master " .
958
- "WHERE type='table' AND tbl_name='$tableName'";
959
- }
960
-
961
- /**
962
- * function create_table Get table creation code from database
963
- * @todo make it do something with sqlite
964
- */
965
- public function create_table($row, $dumpSettings)
966
- {
967
- return "";
968
- }
969
-
970
- public function show_create_view($viewName)
971
- {
972
- return "SELECT tbl_name as 'View', sql as 'Create View' " .
973
- "FROM sqlite_master " .
974
- "WHERE type='view' AND tbl_name='$viewName'";
975
- }
976
-
977
- /**
978
- * function create_view Get view creation code from database
979
- * @todo make it do something with sqlite
980
- */
981
- public function create_view($row)
982
- {
983
- return "";
984
- }
985
-
986
- /**
987
- * function show_create_trigger Get trigger creation code from database
988
- * @todo make it do something with sqlite
989
- */
990
- public function show_create_trigger($triggerName)
991
- {
992
- return "";
993
- }
994
-
995
- /**
996
- * function create_trigger Modify trigger code, add delimiters, etc
997
- * @todo make it do something with sqlite
998
- */
999
- public function create_trigger($triggerName)
1000
- {
1001
- return "";
1002
- }
1003
-
1004
- public function show_tables()
1005
- {
1006
- return "SELECT tbl_name FROM sqlite_master WHERE type='table'";
1007
- }
1008
-
1009
- public function show_views()
1010
- {
1011
- return "SELECT tbl_name FROM sqlite_master WHERE type='view'";
1012
- }
1013
-
1014
- public function show_triggers()
1015
- {
1016
- return "SELECT Trigger FROM sqlite_master WHERE type='trigger'";
1017
- }
1018
-
1019
- public function show_columns()
1020
- {
1021
- if (func_num_args() != 1) {
1022
- return "";
1023
- }
1024
-
1025
- $args = func_get_args();
1026
-
1027
- return "pragma table_info(${args[0]})";
1028
- }
1029
-
1030
- public function setup_transaction()
1031
- {
1032
- return "";
1033
- }
1034
-
1035
- public function start_transaction()
1036
- {
1037
- return "BEGIN EXCLUSIVE";
1038
- }
1039
-
1040
- public function commit_transaction()
1041
- {
1042
- return "COMMIT";
1043
- }
1044
-
1045
- public function lock_table()
1046
- {
1047
- return "";
1048
- }
1049
-
1050
- public function unlock_table()
1051
- {
1052
- return "";
1053
- }
1054
-
1055
- public function start_add_lock_table()
1056
- {
1057
- return PHP_EOL;
1058
- }
1059
-
1060
- public function end_add_lock_table()
1061
- {
1062
- return PHP_EOL;
1063
- }
1064
-
1065
- public function start_add_disable_keys()
1066
- {
1067
- return PHP_EOL;
1068
- }
1069
-
1070
- public function end_add_disable_keys()
1071
- {
1072
- return PHP_EOL;
1073
- }
1074
-
1075
- public function start_disable_foreign_keys_check()
1076
- {
1077
- return PHP_EOL;
1078
- }
1079
-
1080
- public function end_disable_foreign_keys_check()
1081
- {
1082
- return PHP_EOL;
1083
- }
1084
-
1085
- public function add_drop_database()
1086
- {
1087
- return PHP_EOL;
1088
- }
1089
-
1090
- public function add_drop_trigger()
1091
- {
1092
- return PHP_EOL;
1093
- }
1094
-
1095
- public function drop_table()
1096
- {
1097
- return PHP_EOL;
1098
- }
1099
-
1100
- public function drop_view()
1101
- {
1102
- return PHP_EOL;
1103
- }
1104
-
1105
- /**
1106
- * Decode column metadata and fill info structure.
1107
- * type, is_numeric and is_blob will always be available.
1108
- *
1109
- * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
1110
- * @return array
1111
- */
1112
- public function parseColumnType($colType)
1113
- {
1114
- return array();
1115
- }
1116
-
1117
- public function backup_parameters()
1118
- {
1119
- return PHP_EOL;
1120
- }
1121
-
1122
- public function restore_parameters()
1123
- {
1124
- return PHP_EOL;
1125
- }
1126
- }
1127
-
1128
- class TypeAdapterPgsql extends TypeAdapterFactory
1129
- {
1130
- }
1131
-
1132
- class TypeAdapterDblib extends TypeAdapterFactory
1133
- {
1134
- }
1135
-
1136
- class TypeAdapterSqlite extends TypeAdapterFactory
1137
- {
1138
- }
1139
-
1140
- class TypeAdapterMysql extends TypeAdapterFactory
1141
- {
1142
-
1143
- private $dbHandler = null;
1144
-
1145
- // Numerical Mysql types
1146
- public $mysqlTypes = array(
1147
- 'numerical' => array(
1148
- 'bit',
1149
- 'tinyint',
1150
- 'smallint',
1151
- 'mediumint',
1152
- 'int',
1153
- 'integer',
1154
- 'bigint',
1155
- 'real',
1156
- 'double',
1157
- 'float',
1158
- 'decimal',
1159
- 'numeric'
1160
- ),
1161
- 'blob' => array(
1162
- 'tinyblob',
1163
- 'blob',
1164
- 'mediumblob',
1165
- 'longblob',
1166
- 'binary',
1167
- 'varbinary',
1168
- 'bit'
1169
- )
1170
- );
1171
-
1172
- public function __construct ($dbHandler)
1173
- {
1174
- $this->dbHandler = $dbHandler;
1175
- }
1176
-
1177
- public function databases()
1178
- {
1179
- if (func_num_args() != 1) {
1180
- throw new Exception("Unexpected parameter passed to " . __METHOD__);
1181
- }
1182
-
1183
- $args = func_get_args();
1184
- $databaseName = $args[0];
1185
-
1186
- $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'character_set_database';");
1187
- $characterSet = $resultSet[0]['Value'];
1188
-
1189
- $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'collation_database';");
1190
- $collationDb = $resultSet[0]['Value'];
1191
- $ret = "";
1192
-
1193
- $ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `${databaseName}`".
1194
- " /*!40100 DEFAULT CHARACTER SET ${characterSet} " .
1195
- " COLLATE ${collationDb} */;/*SGEnd*/" . PHP_EOL . PHP_EOL .
1196
- "USE `${databaseName}`;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1197
-
1198
- return $ret;
1199
- }
1200
-
1201
- public function show_create_table($tableName)
1202
- {
1203
- return "SHOW CREATE TABLE `$tableName`";
1204
- }
1205
-
1206
- public function show_create_view($viewName)
1207
- {
1208
- return "SHOW CREATE VIEW `$viewName`";
1209
- }
1210
-
1211
- public function show_create_trigger($triggerName)
1212
- {
1213
- return "SHOW CREATE TRIGGER `$triggerName`";
1214
- }
1215
-
1216
- public function create_table($row, $dumpSettings)
1217
- {
1218
- if (!isset($row['Create Table'])) {
1219
- throw new Exception("Error getting table code, unknown output");
1220
- }
1221
-
1222
- $ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;/*SGEnd*/" . PHP_EOL .
1223
- "/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;/*SGEnd*/" . PHP_EOL .
1224
- $row['Create Table'] . ";/*SGEnd*/" . PHP_EOL .
1225
- "/*!40101 SET character_set_client = @saved_cs_client */;/*SGEnd*/" . PHP_EOL .
1226
- PHP_EOL;
1227
- return $ret;
1228
- }
1229
-
1230
- public function create_view($row)
1231
- {
1232
- $ret = "";
1233
- if (!isset($row['Create View'])) {
1234
- throw new Exception("Error getting view structure, unknown output");
1235
- }
1236
-
1237
- $triggerStmt = $row['Create View'];
1238
- $triggerStmtReplaced1 = str_replace(
1239
- "CREATE ALGORITHM",
1240
- "/*!50001 CREATE ALGORITHM",
1241
- $triggerStmt
1242
- );
1243
- $triggerStmtReplaced2 = str_replace(
1244
- " DEFINER=",
1245
- " */" . PHP_EOL . "/*!50013 DEFINER=",
1246
- $triggerStmtReplaced1
1247
- );
1248
- $triggerStmtReplaced3 = str_replace(
1249
- " VIEW ",
1250
- " */" . PHP_EOL . "/*!50001 VIEW ",
1251
- $triggerStmtReplaced2
1252
- );
1253
- if (false === $triggerStmtReplaced1 ||
1254
- false === $triggerStmtReplaced2 ||
1255
- false === $triggerStmtReplaced3) {
1256
- $triggerStmtReplaced = $triggerStmt;
1257
- } else {
1258
- $triggerStmtReplaced = $triggerStmtReplaced3 . " */;/*SGEnd*/";
1259
- }
1260
-
1261
- $ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
1262
- return $ret;
1263
- }
1264
-
1265
- public function create_trigger($row)
1266
- {
1267
- $ret = "";
1268
- if (!isset($row['SQL Original Statement'])) {
1269
- throw new Exception("Error getting trigger code, unknown output");
1270
- }
1271
-
1272
- $triggerStmt = $row['SQL Original Statement'];
1273
- $triggerStmtReplaced = str_replace(
1274
- "CREATE DEFINER",
1275
- "/*!50003 CREATE*/ /*!50017 DEFINER",
1276
- $triggerStmt
1277
- );
1278
- $triggerStmtReplaced = str_replace(
1279
- " TRIGGER",
1280
- "*/ /*!50003 TRIGGER",
1281
- $triggerStmtReplaced
1282
- );
1283
- if ( false === $triggerStmtReplaced ) {
1284
- $triggerStmtReplaced = $triggerStmt;
1285
- }
1286
-
1287
- $ret .= "DELIMITER ;;/*SGEnd*/" . PHP_EOL .
1288
- $triggerStmtReplaced . "*/;;/*SGEnd*/" . PHP_EOL .
1289
- "DELIMITER ;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1290
- return $ret;
1291
- }
1292
-
1293
- public function show_tables()
1294
- {
1295
- if (func_num_args() != 1) {
1296
- return "";
1297
- }
1298
-
1299
- $args = func_get_args();
1300
-
1301
- return "SELECT TABLE_NAME AS tbl_name " .
1302
- "FROM INFORMATION_SCHEMA.TABLES " .
1303
- "WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='${args[0]}'";
1304
- }
1305
-
1306
- public function show_views()
1307
- {
1308
- if (func_num_args() != 1) {
1309
- return "";
1310
- }
1311
-
1312
- $args = func_get_args();
1313
-
1314
- return "SELECT TABLE_NAME AS tbl_name " .
1315
- "FROM INFORMATION_SCHEMA.TABLES " .
1316
- "WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='${args[0]}'";
1317
- }
1318
-
1319
- public function show_triggers()
1320
- {
1321
- if (func_num_args() != 1) {
1322
- return "";
1323
- }
1324
-
1325
- $args = func_get_args();
1326
-
1327
- return "SHOW TRIGGERS FROM `${args[0]}`;";
1328
- }
1329
-
1330
-
1331
- public function show_columns()
1332
- {
1333
- if (func_num_args() != 1) {
1334
- return "";
1335
- }
1336
-
1337
- $args = func_get_args();
1338
-
1339
- return "SHOW COLUMNS FROM `${args[0]}`;";
1340
- }
1341
-
1342
- public function setup_transaction()
1343
- {
1344
- return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
1345
- }
1346
-
1347
- public function start_transaction()
1348
- {
1349
- return "START TRANSACTION";
1350
- }
1351
-
1352
- public function commit_transaction()
1353
- {
1354
- return "COMMIT";
1355
- }
1356
-
1357
- public function lock_table()
1358
- {
1359
- if (func_num_args() != 1) {
1360
- return "";
1361
- }
1362
-
1363
- $args = func_get_args();
1364
- //$tableName = $args[0];
1365
- //return "LOCK TABLES `$tableName` READ LOCAL";
1366
- return $this->dbHandler->query("LOCK TABLES `${args[0]}` READ LOCAL");
1367
-
1368
- }
1369
-
1370
- public function unlock_table()
1371
- {
1372
- return $this->dbHandler->query("UNLOCK TABLES");
1373
- }
1374
-
1375
- public function start_add_lock_table()
1376
- {
1377
- if (func_num_args() != 1) {
1378
- return "";
1379
- }
1380
-
1381
- $args = func_get_args();
1382
-
1383
- return "LOCK TABLES `${args[0]}` WRITE;/*SGEnd*/" . PHP_EOL;
1384
- }
1385
-
1386
- public function end_add_lock_table()
1387
- {
1388
- return "UNLOCK TABLES;/*SGEnd*/" . PHP_EOL;
1389
- }
1390
-
1391
- public function start_add_disable_keys()
1392
- {
1393
- if (func_num_args() != 1) {
1394
- return "";
1395
- }
1396
- $args = func_get_args();
1397
- return "/*!40000 ALTER TABLE `${args[0]}` DISABLE KEYS */;/*SGEnd*/" .
1398
- PHP_EOL;
1399
- }
1400
-
1401
- public function end_add_disable_keys()
1402
- {
1403
- if (func_num_args() != 1) {
1404
- return "";
1405
- }
1406
- $args = func_get_args();
1407
- return "/*!40000 ALTER TABLE `${args[0]}` ENABLE KEYS */;/*SGEnd*/" .
1408
- PHP_EOL;
1409
- }
1410
-
1411
- public function start_disable_autocommit()
1412
- {
1413
- return "SET autocommit=0;/*SGEnd*/" . PHP_EOL;
1414
- }
1415
-
1416
- public function end_disable_autocommit()
1417
- {
1418
- return "COMMIT;/*SGEnd*/" . PHP_EOL;
1419
- }
1420
-
1421
- public function add_drop_database()
1422
- {
1423
- if (func_num_args() != 1) {
1424
- return "";
1425
- }
1426
-
1427
- $args = func_get_args();
1428
-
1429
- return "/*!40000 DROP DATABASE IF EXISTS `${args[0]}`*/;/*SGEnd*/" .
1430
- PHP_EOL . PHP_EOL;
1431
- }
1432
-
1433
- public function add_drop_trigger()
1434
- {
1435
- if (func_num_args() != 1) {
1436
- return "";
1437
- }
1438
-
1439
- $args = func_get_args();
1440
-
1441
- return "DROP TRIGGER IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL;
1442
- }
1443
-
1444
- public function drop_table()
1445
- {
1446
- if (func_num_args() != 1) {
1447
- return "";
1448
- }
1449
-
1450
- $args = func_get_args();
1451
-
1452
- return "DROP TABLE IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL;
1453
- }
1454
-
1455
- public function drop_view()
1456
- {
1457
- if (func_num_args() != 1) {
1458
- return "";
1459
- }
1460
-
1461
- $args = func_get_args();
1462
-
1463
- return "DROP TABLE IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL .
1464
- "/*!50001 DROP VIEW IF EXISTS `${args[0]}`*/;/*SGEnd*/" . PHP_EOL;
1465
- }
1466
-
1467
- public function getDatabaseHeader()
1468
- {
1469
- if (func_num_args() != 1) {
1470
- return "";
1471
- }
1472
-
1473
- $args = func_get_args();
1474
-
1475
- return "--" . PHP_EOL .
1476
- "-- Current Database: `${args[0]}`" . PHP_EOL .
1477
- "--" . PHP_EOL . PHP_EOL;
1478
- }
1479
-
1480
- /**
1481
- * Decode column metadata and fill info structure.
1482
- * type, is_numeric and is_blob will always be available.
1483
- *
1484
- * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
1485
- * @return array
1486
- */
1487
- public function parseColumnType($colType)
1488
- {
1489
- $colInfo = array();
1490
- $colParts = explode(" ", $colType['Type']);
1491
-
1492
- if($fparen = strpos($colParts[0], "("))
1493
- {
1494
- $colInfo['type'] = substr($colParts[0], 0, $fparen);
1495
- $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
1496
- $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
1497
- }
1498
- else
1499
- {
1500
- $colInfo['type'] = $colParts[0];
1501
- }
1502
- $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
1503
- $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
1504
-
1505
- return $colInfo;
1506
- }
1507
-
1508
- public function backup_parameters()
1509
- {
1510
- if (func_num_args() != 1) {
1511
- throw new Exception("Unexpected parameter passed to " . __METHOD__);
1512
- }
1513
-
1514
- $args = func_get_args();
1515
- $dumpSettings = $args[0];
1516
- $ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*SGEnd*/" . PHP_EOL .
1517
- "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*SGEnd*/" . PHP_EOL .
1518
- "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*SGEnd*/" . PHP_EOL .
1519
- "/*!40101 SET NAMES " . $dumpSettings['default-character-set'] . " */;/*SGEnd*/" . PHP_EOL;
1520
-
1521
- if (false === $dumpSettings['skip-tz-utz']) {
1522
- $ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*SGEnd*/" . PHP_EOL .
1523
- "/*!40103 SET TIME_ZONE='+00:00' */;/*SGEnd*/" . PHP_EOL;
1524
- }
1525
-
1526
- $ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*SGEnd*/" . PHP_EOL .
1527
- "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*SGEnd*/" . PHP_EOL .
1528
- "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*SGEnd*/" . PHP_EOL .
1529
- "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;/*SGEnd*/" . PHP_EOL .PHP_EOL;
1530
-
1531
- return $ret;
1532
- }
1533
-
1534
- public function restore_parameters()
1535
- {
1536
- if (func_num_args() != 1) {
1537
- throw new Exception("Unexpected parameter passed to " . __METHOD__);
1538
- }
1539
-
1540
- $args = func_get_args();
1541
- $dumpSettings = $args[0];
1542
- $ret = "";
1543
-
1544
- if (false === $dumpSettings['skip-tz-utz']) {
1545
- $ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*SGEnd*/" . PHP_EOL;
1546
- }
1547
-
1548
- $ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*SGEnd*/" . PHP_EOL .
1549
- "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*SGEnd*/" . PHP_EOL .
1550
- "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*SGEnd*/" . PHP_EOL .
1551
- "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*SGEnd*/" . PHP_EOL .
1552
- "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*SGEnd*/" . PHP_EOL .
1553
- "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;/*SGEnd*/" . PHP_EOL .
1554
- "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1555
-
1556
- return $ret;
1557
- }
1558
- }
1
+ <?php
2
+ /**
3
+ * SGMysqldump Class Doc Comment
4
+ *
5
+ * @category Library
6
+ * @package Ifsnop\Mysqldump
7
+ * @author Michael J. Calkins <clouddueling@github.com>
8
+ * @author Diego Torres <ifsnop@github.com>
9
+ * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10
+ * @link https://github.com/ifsnop/mysqldump-php
11
+ *
12
+ */
13
+
14
+ interface SGIMysqldumpDelegate
15
+ {
16
+ public function didExportRow();
17
+ }
18
+
19
+ class SGMysqldump
20
+ {
21
+
22
+ // Same as mysqldump
23
+ const MAXLINESIZE = 1000000;
24
+
25
+ // Available compression methods as constants
26
+ const GZIP = 'Gzip';
27
+ const BZIP2 = 'Bzip2';
28
+ const NONE = 'None';
29
+
30
+ // Available connection strings
31
+ const UTF8 = 'utf8';
32
+ const UTF8MB4 = 'utf8mb4';
33
+
34
+ // This can be set both on constructor or manually
35
+ public $db;
36
+ public $fileName;
37
+
38
+ // Internal stuff
39
+ private $tables = array();
40
+ private $views = array();
41
+ private $triggers = array();
42
+ private $dbHandler;
43
+ private $dbType;
44
+ private $compressManager;
45
+ private $typeAdapter;
46
+ private $dumpSettings = array();
47
+ private $version;
48
+ private $tableColumnTypes = array();
49
+ private $delegate = null;
50
+ private $excludeTables = array();
51
+
52
+ private $cursor = 0;
53
+ private $state = null;
54
+ private $inprogress = false;
55
+ private $backedUpTables = array();
56
+
57
+ /**
58
+ * Constructor of SGMysqldump. Note that in the case of an SQLite database
59
+ * connection, the filename must be in the $db parameter.
60
+ *
61
+ * @param string $db Database name
62
+ * @param string $type SQL database type
63
+ * @param array $dumpSettings SQL database settings
64
+ */
65
+ public function __construct(
66
+ $dbHandler,
67
+ $db = '',
68
+ $type = 'mysql',
69
+ $dumpSettings = array()
70
+ ) {
71
+ $dumpSettingsDefault = array(
72
+ 'include-tables' => array(),
73
+ 'exclude-tables' => array(),
74
+ 'compress' => SGMysqldump::NONE,
75
+ 'no-data' => false,
76
+ 'add-drop-table' => false,
77
+ 'single-transaction' => true,
78
+ 'lock-tables' => true,
79
+ 'add-locks' => true,
80
+ 'extended-insert' => true,
81
+ 'disable-keys' => true,
82
+ 'where' => '',
83
+ 'no-create-info' => false,
84
+ 'skip-triggers' => false,
85
+ 'add-drop-trigger' => true,
86
+ 'hex-blob' => true,
87
+ 'databases' => false,
88
+ 'add-drop-database' => false,
89
+ 'skip-tz-utz' => false,
90
+ 'no-autocommit' => true,
91
+ 'default-character-set' => SGMysqldump::UTF8,
92
+ 'skip-comments' => false,
93
+ 'skip-dump-date' => false,
94
+ /* deprecated */
95
+ 'disable-foreign-keys-check' => true
96
+ );
97
+
98
+ $this->db = $db;
99
+ $this->dbHandler = $dbHandler;
100
+ $this->dbType = strtolower($type);
101
+ $this->dumpSettings = self::array_replace_recursive($dumpSettingsDefault, $dumpSettings);
102
+ $this->excludeTables = $dumpSettings['exclude-tables'];
103
+
104
+ $diff = array_diff(array_keys($this->dumpSettings), array_keys($dumpSettingsDefault));
105
+ if (count($diff)>0) {
106
+ throw new Exception("Unexpected value in dumpSettings: (" . implode(",", $diff) . ")");
107
+ }
108
+
109
+ // Create a new compressManager to manage compressed output
110
+ $this->compressManager = CompressManagerFactory::create($this->dumpSettings['compress']);
111
+ }
112
+
113
+ public function setDelegate(SGIMysqldumpDelegate $delegate)
114
+ {
115
+ $this->delegate = $delegate;
116
+ }
117
+
118
+ private function getState()
119
+ {
120
+ return $this->delegate->getState();
121
+ }
122
+
123
+ private function shouldReload()
124
+ {
125
+ return $this->delegate->shouldReload();
126
+ }
127
+
128
+ /**
129
+ * Custom array_replace_recursive to be used if PHP < 5.3
130
+ * Replaces elements from passed arrays into the first array recursively
131
+ *
132
+ * @param array $array1 The array in which elements are replaced
133
+ * @param array $array2 The array from which elements will be extracted
134
+ *
135
+ * @return array Returns an array, or NULL if an error occurs.
136
+ */
137
+ public static function array_replace_recursive($array1, $array2)
138
+ {
139
+ if (function_exists('array_replace_recursive')) {
140
+ return array_replace_recursive($array1, $array2);
141
+ }
142
+
143
+ foreach ($array2 as $key => $value) {
144
+ if (is_array($value)) {
145
+ $array1[$key] = self::array_replace_recursive($array1[$key], $value);
146
+ } else {
147
+ $array1[$key] = $value;
148
+ }
149
+ }
150
+ return $array1;
151
+ }
152
+
153
+ /**
154
+ * Connect with PDO
155
+ *
156
+ * @return null
157
+ */
158
+ private function connect()
159
+ {
160
+ $this->dbHandler->query("SET NAMES " . $this->dumpSettings['default-character-set']);
161
+ $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler);
162
+ }
163
+
164
+ /**
165
+ * Main call
166
+ *
167
+ * @param string $filename Name of file to write sql dump to
168
+ * @return null
169
+ */
170
+ public function start($filename)
171
+ {
172
+ $this->state = $this->getState();
173
+ $this->fileName = $filename;
174
+
175
+ // Connect to database
176
+ $this->connect();
177
+
178
+ // Create output file
179
+ $this->compressManager->open($this->fileName);
180
+
181
+ if ($this->state->getAction() == SG_STATE_ACTION_PREPARING_STATE_FILE) {
182
+ // Write some basic info to output file
183
+ $this->compressManager->write($this->getDumpFileHeader());
184
+
185
+ // Store server settings and use sanner defaults to dump
186
+ $this->compressManager->write(
187
+ $this->typeAdapter->backup_parameters($this->dumpSettings)
188
+ );
189
+
190
+ if ($this->dumpSettings['databases']) {
191
+ $this->compressManager->write(
192
+ $this->typeAdapter->getDatabaseHeader($this->db)
193
+ );
194
+ if ($this->dumpSettings['add-drop-database']) {
195
+ $this->compressManager->write(
196
+ $this->typeAdapter->add_drop_database($this->db)
197
+ );
198
+ }
199
+ }
200
+ }
201
+
202
+ // Get table, view and trigger structures from database
203
+ $this->getDatabaseStructure();
204
+
205
+ if ($this->state->getAction() == SG_STATE_ACTION_PREPARING_STATE_FILE) {
206
+ if ($this->dumpSettings['databases']) {
207
+ $this->compressManager->write(
208
+ $this->typeAdapter->databases($this->db)
209
+ );
210
+ }
211
+
212
+ // If there still are some tables/views in include-tables array,
213
+ // that means that some tables or views weren't found.
214
+ // Give proper error and exit.
215
+ if (0 < count($this->dumpSettings['include-tables'])) {
216
+ $name = implode(",", $this->dumpSettings['include-tables']);
217
+ throw new SGException("Table or View (" . $name . ") not found in database");
218
+ }
219
+ }
220
+
221
+ $this->exportTables();
222
+ $this->exportViews();
223
+ $this->exportTriggers();
224
+
225
+ // Restore saved parameters
226
+ $this->compressManager->write(
227
+ $this->typeAdapter->restore_parameters($this->dumpSettings)
228
+ );
229
+ // Write some stats to output file
230
+ $this->compressManager->write($this->getDumpFileFooter());
231
+ // Close output file
232
+ $this->compressManager->close();
233
+ }
234
+
235
+ /**
236
+ * Returns header for dump file
237
+ *
238
+ * @return string
239
+ */
240
+ private function getDumpFileHeader()
241
+ {
242
+ $header = '';
243
+ if (!$this->dumpSettings['skip-comments']) {
244
+ // Some info about software, source and time
245
+ $header = '';
246
+
247
+ if (!empty($this->version)) {
248
+ $header .= "-- Server version \t" . $this->version . PHP_EOL;
249
+ }
250
+
251
+ $header .= "-- Date: " . @date('r') . PHP_EOL . PHP_EOL;
252
+ }
253
+ return $header;
254
+ }
255
+
256
+ /**
257
+ * Returns footer for dump file
258
+ *
259
+ * @return string
260
+ */
261
+ private function getDumpFileFooter()
262
+ {
263
+ $footer = '';
264
+ if (!$this->dumpSettings['skip-comments']) {
265
+ $footer .= '-- Dump completed';
266
+ if (!$this->dumpSettings['skip-dump-date']) {
267
+ $footer .= ' on: ' . @date('r');
268
+ }
269
+ $footer .= PHP_EOL;
270
+ }
271
+
272
+ return $footer;
273
+ }
274
+
275
+ /**
276
+ * Reads table and views names from database.
277
+ * Fills $this->tables array so they will be dumped later.
278
+ *
279
+ * @return null
280
+ */
281
+ private function getDatabaseStructure()
282
+ {
283
+ // Listing all tables from database
284
+ if (empty($this->dumpSettings['include-tables'])) {
285
+ // include all tables for now, blacklisting happens later
286
+ $arr = $this->dbHandler->query($this->typeAdapter->show_tables($this->db));
287
+ foreach ($arr as $row) {
288
+ // Push wp_options table to front to solve restore related bug
289
+ if ($row['tbl_name'] != SG_ENV_DB_PREFIX.'options') {
290
+ array_push($this->tables, $row['tbl_name']);
291
+ }
292
+ else {
293
+ array_unshift($this->tables, $row['tbl_name']);
294
+ }
295
+ }
296
+ } else {
297
+ // include only the tables mentioned in include-tables
298
+ $arr = $this->dbHandler->query($this->typeAdapter->show_tables($this->db));
299
+ foreach ($arr as $row) {
300
+ if (in_array($row['tbl_name'], $this->dumpSettings['include-tables'], true)) {
301
+ array_push($this->tables, $row['tbl_name']);
302
+ $elem = array_search(
303
+ $row['tbl_name'],
304
+ $this->dumpSettings['include-tables']
305
+ );
306
+ unset($this->dumpSettings['include-tables'][$elem]);
307
+ }
308
+ }
309
+ }
310
+
311
+ // Listing all views from database
312
+ if (empty($this->dumpSettings['include-tables'])) {
313
+ // include all views for now, blacklisting happens later
314
+ $arr = $this->dbHandler->query($this->typeAdapter->show_views($this->db));
315
+ foreach ($arr as $row) {
316
+ array_push($this->views, $row['tbl_name']);
317
+ }
318
+ } else {
319
+ // include only the tables mentioned in include-tables
320
+ $arr = $this->dbHandler->query($this->typeAdapter->show_views($this->db));
321
+ foreach ($arr as $row) {
322
+ if (in_array($row['tbl_name'], $this->dumpSettings['include-tables'], true)) {
323
+ array_push($this->views, $row['tbl_name']);
324
+ $elem = array_search(
325
+ $row['tbl_name'],
326
+ $this->dumpSettings['include-tables']
327
+ );
328
+ unset($this->dumpSettings['include-tables'][$elem]);
329
+ }
330
+ }
331
+ }
332
+
333
+ // Listing all triggers from database
334
+ if (false === $this->dumpSettings['skip-triggers']) {
335
+ $arr = $this->dbHandler->query($this->typeAdapter->show_triggers($this->db));
336
+ foreach ($arr as $row) {
337
+ array_push($this->triggers, $row['Trigger']);
338
+ }
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Exports all the tables selected from database
344
+ *
345
+ * @return null
346
+ */
347
+ private function exportTables()
348
+ {
349
+ if ($this->state->getAction() != SG_STATE_ACTION_PREPARING_STATE_FILE) {
350
+ $this->cursor = $this->state->getCursor();
351
+ $this->inprogress = $this->state->getInprogress();
352
+ $this->backedUpTables = $this->state->getBackedUpTables();
353
+ }
354
+ else {
355
+ $this->cursor = 0;
356
+ $this->inprogress = false;
357
+ $this->backedUpTables = array();
358
+ }
359
+
360
+ // Exporting tables one by one
361
+ for($i = $this->cursor; $i < count($this->tables); $i++) {
362
+ $table = $this->tables[$i];
363
+ if (in_array($table, $this->dumpSettings['exclude-tables'], true)) {
364
+ $this->cursor += 1;
365
+ continue;
366
+ }
367
+
368
+ if (!$this->inprogress) {
369
+ SGBackupLog::writeAction('backup table: '.$table, SG_BACKUP_LOG_POS_START);
370
+ $this->getTableStructure($table, false);
371
+ }
372
+ else {
373
+ $this->getTableStructure($table, true);
374
+ }
375
+
376
+ if (false === $this->dumpSettings['no-data']) {
377
+ $this->listValues($table);
378
+ }
379
+
380
+ $this->backedUpTables[] = $table;
381
+ SGBackupLog::writeAction('backup table: '.$table, SG_BACKUP_LOG_POS_END);
382
+ }
383
+
384
+ SGConfig::set('SG_BACKUPED_TABLES', json_encode($this->backedUpTables));
385
+ }
386
+
387
+ /**
388
+ * Exports all the views found in database
389
+ *
390
+ * @return null
391
+ */
392
+ private function exportViews()
393
+ {
394
+ if (false === $this->dumpSettings['no-create-info']) {
395
+ // Exporting views one by one
396
+ foreach ($this->views as $view) {
397
+ if (in_array($view, $this->dumpSettings['exclude-tables'], true)) {
398
+ continue;
399
+ }
400
+ $this->getViewStructure($view);
401
+ }
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Exports all the triggers found in database
407
+ *
408
+ * @return null
409
+ */
410
+ private function exportTriggers()
411
+ {
412
+ // Exporting triggers one by one
413
+ foreach ($this->triggers as $trigger) {
414
+ $this->getTriggerStructure($trigger);
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Table structure extractor
420
+ *
421
+ * @todo move specific mysql code to typeAdapter
422
+ * @param string $tableName Name of table to export
423
+ * @return null
424
+ */
425
+ private function getTableStructure($tableName, $skipCreate = false)
426
+ {
427
+ if (!$skipCreate && !$this->dumpSettings['no-create-info']) {
428
+ $ret = '';
429
+ if (!$this->dumpSettings['skip-comments']) {
430
+ $ret = "--" . PHP_EOL .
431
+ "-- Table structure for table `$tableName`" . PHP_EOL .
432
+ "--" . PHP_EOL . PHP_EOL;
433
+ }
434
+ $stmt = $this->typeAdapter->show_create_table($tableName);
435
+ $arr = $this->dbHandler->query($stmt);
436
+ foreach ($arr as $r) {
437
+ $this->compressManager->write($ret);
438
+ if ($this->dumpSettings['add-drop-table']) {
439
+ $this->compressManager->write(
440
+ $this->typeAdapter->drop_table($tableName)
441
+ );
442
+ }
443
+ $this->compressManager->write(
444
+ $this->typeAdapter->create_table($r, $this->dumpSettings)
445
+ );
446
+ break;
447
+ }
448
+ }
449
+
450
+ $columnTypes = array();
451
+ $columns = $this->dbHandler->query(
452
+ $this->typeAdapter->show_columns($tableName)
453
+ );
454
+
455
+ foreach($columns as $key => $col) {
456
+ $types = $this->typeAdapter->parseColumnType($col);
457
+ $columnTypes[$col['Field']] = array(
458
+ 'is_numeric'=> $types['is_numeric'],
459
+ 'is_blob' => $types['is_blob'],
460
+ 'type' => $types['type']
461
+ );
462
+ }
463
+ $this->tableColumnTypes[$tableName] = $columnTypes;
464
+ return;
465
+ }
466
+
467
+ /**
468
+ * View structure extractor
469
+ *
470
+ * @todo move mysql specific code to typeAdapter
471
+ * @param string $viewName Name of view to export
472
+ * @return null
473
+ */
474
+ private function getViewStructure($viewName)
475
+ {
476
+ $ret = '';
477
+ if (!$this->dumpSettings['skip-comments']) {
478
+ $ret = "--" . PHP_EOL .
479
+ "-- Table structure for view `${viewName}`" . PHP_EOL .
480
+ "--" . PHP_EOL . PHP_EOL;
481
+ }
482
+ $this->compressManager->write($ret);
483
+ $stmt = $this->typeAdapter->show_create_view($viewName);
484
+ $arr = $this->dbHandler->query($stmt);
485
+ foreach ($arr as $r) {
486
+ if ($this->dumpSettings['add-drop-table']) {
487
+ $this->compressManager->write(
488
+ $this->typeAdapter->drop_view($viewName)
489
+ );
490
+ }
491
+ $this->compressManager->write(
492
+ $this->typeAdapter->create_view($r)
493
+ );
494
+ break;
495
+ }
496
+ }
497
+
498
+ /**
499
+ * Trigger structure extractor
500
+ *
501
+ * @param string $triggerName Name of trigger to export
502
+ * @return null
503
+ */
504
+ private function getTriggerStructure($triggerName)
505
+ {
506
+ $stmt = $this->typeAdapter->show_create_trigger($triggerName);
507
+ $arr = $this->dbHandler->query($stmt);
508
+ foreach ($arr as $r) {
509
+ if ($this->dumpSettings['add-drop-trigger']) {
510
+ $this->compressManager->write(
511
+ $this->typeAdapter->add_drop_trigger($triggerName)
512
+ );
513
+ }
514
+ $this->compressManager->write(
515
+ $this->typeAdapter->create_trigger($r)
516
+ );
517
+ return;
518
+ }
519
+
520
+ }
521
+
522
+
523
+ /**
524
+ * Escape values with quotes when needed
525
+ *
526
+ * @param string $tableName Name of table which contains rows
527
+ * @param array $row Associative array of column names and values to be quoted
528
+ *
529
+ * @return string
530
+ */
531
+ private function escape($tableName, $row)
532
+ {
533
+ $ret = array();
534
+ $columnTypes = $this->tableColumnTypes[$tableName];
535
+ foreach ($row as $colName => $colValue) {
536
+ if (is_null($colValue)) {
537
+ $ret[] = "NULL";
538
+ } elseif ($this->dumpSettings['hex-blob'] && $columnTypes[$colName]['is_blob']) {
539
+ if ($columnTypes[$colName]['type'] == 'bit' || !empty($colValue)) {
540
+ $ret[] = "0x${colValue}";
541
+ } else {
542
+ $ret[] = "''";
543
+ }
544
+ } elseif ($columnTypes[$colName]['is_numeric']) {
545
+ $ret[] = $colValue;
546
+ } else {
547
+ $str = "'".str_replace("'", "''", $colValue)."'";
548
+ $str = str_replace("\\", "\\\\", $str);
549
+ $ret[] = $str;
550
+ }
551
+ }
552
+ return $ret;
553
+ }
554
+
555
+ /**
556
+ * Table rows extractor
557
+ *
558
+ * @param string $tableName Name of table to export
559
+ *
560
+ * @return null
561
+ */
562
+ private function listValues($tableName)
563
+ {
564
+ if (!$this->state->getInprogress()) {
565
+ $this->prepareListValues($tableName);
566
+ }
567
+
568
+ $onlyOnce = true;
569
+ $lineSize = 0;
570
+ $offset = 0;
571
+ if ($this->state->getInprogress()) {
572
+ $onlyOnce = false;
573
+ $offset = $this->state->getOffset();
574
+ $lineSize = $this->state->getLineSize();
575
+ }
576
+
577
+ $colStmt = $this->getColumnStmt($tableName);
578
+ $stmt = "SELECT $colStmt FROM `$tableName`";
579
+
580
+ if ($this->dumpSettings['where']) {
581
+ $stmt .= " WHERE {$this->dumpSettings['where']}";
582
+ }
583
+
584
+ $limit = SGConfig::get('SG_BACKUP_DATABASE_INSERT_LIMIT')?SGConfig::get('SG_BACKUP_DATABASE_INSERT_LIMIT'):SG_BACKUP_DATABASE_INSERT_LIMIT;
585
+
586
+ while (true) {
587
+ $st = $this->dbHandler->exec($stmt.' LIMIT '.$offset.','.$limit);
588
+
589
+ $row = $this->dbHandler->fetch($st);
590
+
591
+ $this->inprogress = true;
592
+ if (!$row) {
593
+ $this->inprogress = false;
594
+ $this->cursor += 1;
595
+ $this->delegate->saveStateData(0, $this->cursor, $this->inprogress, 0, $this->backedUpTables);
596
+ break;
597
+ }
598
+
599
+ while ($row) {
600
+ $vals = $this->escape($tableName, $row);
601
+
602
+ if ($onlyOnce) {
603
+ $lineSize += $this->compressManager->write(
604
+ "INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
605
+ );
606
+ $onlyOnce = false;
607
+ }
608
+ else {
609
+ $lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
610
+ }
611
+ if ($lineSize > self::MAXLINESIZE) {
612
+ $onlyOnce = true;
613
+ $this->compressManager->write(";/*SGEnd*/" . PHP_EOL);
614
+ $lineSize = 0;
615
+ }
616
+
617
+ if ($this->delegate) {
618
+ $this->delegate->didExportRow();
619
+ }
620
+
621
+ $row = $this->dbHandler->fetch($st);
622
+ }
623
+
624
+ $offset += $limit;
625
+ if ($this->shouldReload()) {
626
+ $this->delegate->saveStateData($offset, $this->cursor, $this->inprogress, $lineSize, $this->backedUpTables);
627
+
628
+ if (backupGuardIsReloadEnabled()) {
629
+ $this->delegate->reload();
630
+ }
631
+ }
632
+ }
633
+
634
+ if (!$onlyOnce) {
635
+ $this->compressManager->write(";/*SGEnd*/" . PHP_EOL);
636
+ }
637
+
638
+ $this->endListValues($tableName);
639
+ }
640
+
641
+ /**
642
+ * Table rows extractor, append information prior to dump
643
+ *
644
+ * @param string $tableName Name of table to export
645
+ *
646
+ * @return null
647
+ */
648
+ function prepareListValues($tableName)
649
+ {
650
+ if (!$this->dumpSettings['skip-comments']) {
651
+ $this->compressManager->write(
652
+ "--" . PHP_EOL .
653
+ "-- Dumping data for table `$tableName`" . PHP_EOL .
654
+ "--" . PHP_EOL . PHP_EOL
655
+ );
656
+ }
657
+
658
+ if ($this->dumpSettings['single-transaction']) {
659
+ $this->dbHandler->query($this->typeAdapter->setup_transaction());
660
+ $this->dbHandler->query($this->typeAdapter->start_transaction());
661
+ }
662
+
663
+ if ($this->dumpSettings['lock-tables']) {
664
+ $this->typeAdapter->lock_table($tableName);
665
+ }
666
+
667
+ if ($this->dumpSettings['add-locks']) {
668
+ $this->compressManager->write(
669
+ $this->typeAdapter->start_add_lock_table($tableName)
670
+ );
671
+ }
672
+
673
+ if ($this->dumpSettings['disable-keys']) {
674
+ $this->compressManager->write(
675
+ $this->typeAdapter->start_add_disable_keys($tableName)
676
+ );
677
+ }
678
+
679
+ // Disable autocommit for faster reload
680
+ if ($this->dumpSettings['no-autocommit']) {
681
+ $this->compressManager->write(
682
+ $this->typeAdapter->start_disable_autocommit()
683
+ );
684
+ }
685
+
686
+ return;
687
+ }
688
+
689
+ /**
690
+ * Table rows extractor, close locks and commits after dump
691
+ *
692
+ * @param string $tableName Name of table to export
693
+ *
694
+ * @return null
695
+ */
696
+ function endListValues($tableName)
697
+ {
698
+ if ($this->dumpSettings['disable-keys']) {
699
+ $this->compressManager->write(
700
+ $this->typeAdapter->end_add_disable_keys($tableName)
701
+ );
702
+ }
703
+
704
+ if ($this->dumpSettings['add-locks']) {
705
+ $this->compressManager->write(
706
+ $this->typeAdapter->end_add_lock_table($tableName)
707
+ );
708
+ }
709
+
710
+ if ($this->dumpSettings['single-transaction']) {
711
+ $this->dbHandler->query($this->typeAdapter->commit_transaction());
712
+ }
713
+
714
+ if ($this->dumpSettings['lock-tables']) {
715
+ $this->typeAdapter->unlock_table($tableName);
716
+ }
717
+
718
+ // Commit to enable autocommit
719
+ if ($this->dumpSettings['no-autocommit']) {
720
+ $this->compressManager->write(
721
+ $this->typeAdapter->end_disable_autocommit()
722
+ );
723
+ }
724
+
725
+ $this->compressManager->write(PHP_EOL);
726
+
727
+ return;
728
+ }
729
+
730
+ /**
731
+ * Build SQL List of all columns on current table
732
+ *
733
+ * @param string $tableName Name of table to get columns
734
+ *
735
+ * @return string SQL sentence with columns
736
+ */
737
+ function getColumnStmt($tableName)
738
+ {
739
+ $colStmt = array();
740
+ foreach($this->tableColumnTypes[$tableName] as $colName => $colType) {
741
+ if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) {
742
+ $colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`";
743
+ } else if ($colType['is_blob'] && $this->dumpSettings['hex-blob']) {
744
+ $colStmt[] = "HEX(`${colName}`) AS `${colName}`";
745
+ } else {
746
+ $colStmt[] = "`${colName}`";
747
+ }
748
+ }
749
+ $colStmt = implode(",", $colStmt);
750
+
751
+ return $colStmt;
752
+ }
753
+ }
754
+
755
+ /**
756
+ * Enum with all available compression methods
757
+ *
758
+ */
759
+ abstract class CompressMethod
760
+ {
761
+ public static $enums = array(
762
+ "None",
763
+ "Gzip",
764
+ "Bzip2"
765
+ );
766
+
767
+ /**
768
+ * @param string $c
769
+ * @return boolean
770
+ */
771
+ public static function isValid($c)
772
+ {
773
+ return in_array($c, self::$enums);
774
+ }
775
+ }
776
+
777
+ abstract class CompressManagerFactory
778
+ {
779
+ /**
780
+ * @param string $c
781
+ * @return CompressBzip2|CompressGzip|CompressNone
782
+ */
783
+ public static function create($c)
784
+ {
785
+ $c = ucfirst(strtolower($c));
786
+ if (! CompressMethod::isValid($c)) {
787
+ throw new Exception("Compression method ($c) is not defined yet");
788
+ }
789
+
790
+ $method = __NAMESPACE__ . "\\" . "Compress" . $c;
791
+
792
+ return new $method;
793
+ }
794
+
795
+ public static function prepareToWrite($str)
796
+ {
797
+ return $str;
798
+ }
799
+ }
800
+
801
+ class CompressBzip2 extends CompressManagerFactory
802
+ {
803
+ private $fileHandler = null;
804
+
805
+ public function __construct()
806
+ {
807
+ if (! function_exists("bzopen")) {
808
+ throw new Exception("Compression is enabled, but bzip2 lib is not installed or configured properly");
809
+ }
810
+ }
811
+
812
+ public function open($filename)
813
+ {
814
+ $this->fileHandler = bzopen($filename, 'a');
815
+ if (false === $this->fileHandler) {
816
+ throw new Exception("Output file is not writable");
817
+ }
818
+
819
+ return true;
820
+ }
821
+
822
+ public function write($str)
823
+ {
824
+ $str = self::prepareToWrite($str);
825
+
826
+ if (false === ($bytesWritten = bzwrite($this->fileHandler, $str))) {
827
+ throw new Exception("Writting to file failed! Probably, there is no more free space left?");
828
+ }
829
+ return $bytesWritten;
830
+ }
831
+
832
+ public function close()
833
+ {
834
+ return bzclose($this->fileHandler);
835
+ }
836
+ }
837
+
838
+ class CompressGzip extends CompressManagerFactory
839
+ {
840
+ private $fileHandler = null;
841
+
842
+ public function __construct()
843
+ {
844
+ if (! function_exists("gzopen")) {
845
+ throw new Exception("Compression is enabled, but gzip lib is not installed or configured properly");
846
+ }
847
+ }
848
+
849
+ public function open($filename)
850
+ {
851
+ $this->fileHandler = gzopen($filename, "ab");
852
+ if (false === $this->fileHandler) {
853
+ throw new Exception("Output file is not writable");
854
+ }
855
+
856
+ return true;
857
+ }
858
+
859
+ public function write($str)
860
+ {
861
+ $str = self::prepareToWrite($str);
862
+ if (false === ($bytesWritten = gzwrite($this->fileHandler, $str))) {
863
+ throw new Exception("Writting to file failed! Probably, there is no more free space left?");
864
+ }
865
+ return $bytesWritten;
866
+ }
867
+
868
+ public function close()
869
+ {
870
+ return gzclose($this->fileHandler);
871
+ }
872
+ }
873
+
874
+ class CompressNone extends CompressManagerFactory
875
+ {
876
+ private $fileHandler = null;
877
+
878
+ public function open($filename)
879
+ {
880
+ $this->fileHandler = fopen($filename, "ab");
881
+
882
+ if (false === $this->fileHandler) {
883
+ throw new Exception("Output file is not writable");
884
+ }
885
+
886
+ return true;
887
+ }
888
+
889
+ public function write($str)
890
+ {
891
+ $str = self::prepareToWrite($str);
892
+ if (false === ($bytesWritten = fwrite($this->fileHandler, $str))) {
893
+ throw new Exception("Writting to file failed! Probably, there is no more free space left?");
894
+ }
895
+ return $bytesWritten;
896
+ }
897
+
898
+ public function close()
899
+ {
900
+ return fclose($this->fileHandler);
901
+ }
902
+ }
903
+
904
+ /**
905
+ * Enum with all available TypeAdapter implementations
906
+ *
907
+ */
908
+ abstract class TypeAdapter
909
+ {
910
+ public static $enums = array(
911
+ "Sqlite",
912
+ "Mysql"
913
+ );
914
+
915
+ /**
916
+ * @param string $c
917
+ * @return boolean
918
+ */
919
+ public static function isValid($c)
920
+ {
921
+ return in_array($c, self::$enums);
922
+ }
923
+ }
924
+
925
+ /**
926
+ * TypeAdapter Factory
927
+ *
928
+ */
929
+ abstract class TypeAdapterFactory
930
+ {
931
+ /**
932
+ * @param string $c Type of database factory to create (Mysql, Sqlite,...)
933
+ * @param PDO $dbHandler
934
+ */
935
+ public static function create($c, $dbHandler = null)
936
+ {
937
+ $c = ucfirst(strtolower($c));
938
+ if (! TypeAdapter::isValid($c)) {
939
+ throw new Exception("Database type support for ($c) not yet available");
940
+ }
941
+ $method = __NAMESPACE__ . "\\" . "TypeAdapter" . $c;
942
+ return new $method($dbHandler);
943
+ }
944
+
945
+ /**
946
+ * function databases Add sql to create and use database
947
+ * @todo make it do something with sqlite
948
+ */
949
+ public function databases()
950
+ {
951
+ return "";
952
+ }
953
+
954
+ public function show_create_table($tableName)
955
+ {
956
+ return "SELECT tbl_name as 'Table', sql as 'Create Table' " .
957
+ "FROM sqlite_master " .
958
+ "WHERE type='table' AND tbl_name='$tableName'";
959
+ }
960
+
961
+ /**
962
+ * function create_table Get table creation code from database
963
+ * @todo make it do something with sqlite
964
+ */
965
+ public function create_table($row, $dumpSettings)
966
+ {
967
+ return "";
968
+ }
969
+
970
+ public function show_create_view($viewName)
971
+ {
972
+ return "SELECT tbl_name as 'View', sql as 'Create View' " .
973
+ "FROM sqlite_master " .
974
+ "WHERE type='view' AND tbl_name='$viewName'";
975
+ }
976
+
977
+ /**
978
+ * function create_view Get view creation code from database
979
+ * @todo make it do something with sqlite
980
+ */
981
+ public function create_view($row)
982
+ {
983
+ return "";
984
+ }
985
+
986
+ /**
987
+ * function show_create_trigger Get trigger creation code from database
988
+ * @todo make it do something with sqlite
989
+ */
990
+ public function show_create_trigger($triggerName)
991
+ {
992
+ return "";
993
+ }
994
+
995
+ /**
996
+ * function create_trigger Modify trigger code, add delimiters, etc
997
+ * @todo make it do something with sqlite
998
+ */
999
+ public function create_trigger($triggerName)
1000
+ {
1001
+ return "";
1002
+ }
1003
+
1004
+ public function show_tables()
1005
+ {
1006
+ return "SELECT tbl_name FROM sqlite_master WHERE type='table'";
1007
+ }
1008
+
1009
+ public function show_views()
1010
+ {
1011
+ return "SELECT tbl_name FROM sqlite_master WHERE type='view'";
1012
+ }
1013
+
1014
+ public function show_triggers()
1015
+ {
1016
+ return "SELECT Trigger FROM sqlite_master WHERE type='trigger'";
1017
+ }
1018
+
1019
+ public function show_columns()
1020
+ {
1021
+ if (func_num_args() != 1) {
1022
+ return "";
1023
+ }
1024
+
1025
+ $args = func_get_args();
1026
+
1027
+ return "pragma table_info(${args[0]})";
1028
+ }
1029
+
1030
+ public function setup_transaction()
1031
+ {
1032
+ return "";
1033
+ }
1034
+
1035
+ public function start_transaction()
1036
+ {
1037
+ return "BEGIN EXCLUSIVE";
1038
+ }
1039
+
1040
+ public function commit_transaction()
1041
+ {
1042
+ return "COMMIT";
1043
+ }
1044
+
1045
+ public function lock_table()
1046
+ {
1047
+ return "";
1048
+ }
1049
+
1050
+ public function unlock_table()
1051
+ {
1052
+ return "";
1053
+ }
1054
+
1055
+ public function start_add_lock_table()
1056
+ {
1057
+ return PHP_EOL;
1058
+ }
1059
+
1060
+ public function end_add_lock_table()
1061
+ {
1062
+ return PHP_EOL;
1063
+ }
1064
+
1065
+ public function start_add_disable_keys()
1066
+ {
1067
+ return PHP_EOL;
1068
+ }
1069
+
1070
+ public function end_add_disable_keys()
1071
+ {
1072
+ return PHP_EOL;
1073
+ }
1074
+
1075
+ public function start_disable_foreign_keys_check()
1076
+ {
1077
+ return PHP_EOL;
1078
+ }
1079
+
1080
+ public function end_disable_foreign_keys_check()
1081
+ {
1082
+ return PHP_EOL;
1083
+ }
1084
+
1085
+ public function add_drop_database()
1086
+ {
1087
+ return PHP_EOL;
1088
+ }
1089
+
1090
+ public function add_drop_trigger()
1091
+ {
1092
+ return PHP_EOL;
1093
+ }
1094
+
1095
+ public function drop_table()
1096
+ {
1097
+ return PHP_EOL;
1098
+ }
1099
+
1100
+ public function drop_view()
1101
+ {
1102
+ return PHP_EOL;
1103
+ }
1104
+
1105
+ /**
1106
+ * Decode column metadata and fill info structure.
1107
+ * type, is_numeric and is_blob will always be available.
1108
+ *
1109
+ * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
1110
+ * @return array
1111
+ */
1112
+ public function parseColumnType($colType)
1113
+ {
1114
+ return array();
1115
+ }
1116
+
1117
+ public function backup_parameters()
1118
+ {
1119
+ return PHP_EOL;
1120
+ }
1121
+
1122
+ public function restore_parameters()
1123
+ {
1124
+ return PHP_EOL;
1125
+ }
1126
+ }
1127
+
1128
+ class TypeAdapterPgsql extends TypeAdapterFactory
1129
+ {
1130
+ }
1131
+
1132
+ class TypeAdapterDblib extends TypeAdapterFactory
1133
+ {
1134
+ }
1135
+
1136
+ class TypeAdapterSqlite extends TypeAdapterFactory
1137
+ {
1138
+ }
1139
+
1140
+ class TypeAdapterMysql extends TypeAdapterFactory
1141
+ {
1142
+
1143
+ private $dbHandler = null;
1144
+
1145
+ // Numerical Mysql types
1146
+ public $mysqlTypes = array(
1147
+ 'numerical' => array(
1148
+ 'bit',
1149
+ 'tinyint',
1150
+ 'smallint',
1151
+ 'mediumint',
1152
+ 'int',
1153
+ 'integer',
1154
+ 'bigint',
1155
+ 'real',
1156
+ 'double',
1157
+ 'float',
1158
+ 'decimal',
1159
+ 'numeric'
1160
+ ),
1161
+ 'blob' => array(
1162
+ 'tinyblob',
1163
+ 'blob',
1164
+ 'mediumblob',
1165
+ 'longblob',
1166
+ 'binary',
1167
+ 'varbinary',
1168
+ 'bit'
1169
+ )
1170
+ );
1171
+
1172
+ public function __construct ($dbHandler)
1173
+ {
1174
+ $this->dbHandler = $dbHandler;
1175
+ }
1176
+
1177
+ public function databases()
1178
+ {
1179
+ if (func_num_args() != 1) {
1180
+ throw new Exception("Unexpected parameter passed to " . __METHOD__);
1181
+ }
1182
+
1183
+ $args = func_get_args();
1184
+ $databaseName = $args[0];
1185
+
1186
+ $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'character_set_database';");
1187
+ $characterSet = $resultSet[0]['Value'];
1188
+
1189
+ $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'collation_database';");
1190
+ $collationDb = $resultSet[0]['Value'];
1191
+ $ret = "";
1192
+
1193
+ $ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `${databaseName}`".
1194
+ " /*!40100 DEFAULT CHARACTER SET ${characterSet} " .
1195
+ " COLLATE ${collationDb} */;/*SGEnd*/" . PHP_EOL . PHP_EOL .
1196
+ "USE `${databaseName}`;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1197
+
1198
+ return $ret;
1199
+ }
1200
+
1201
+ public function show_create_table($tableName)
1202
+ {
1203
+ return "SHOW CREATE TABLE `$tableName`";
1204
+ }
1205
+
1206
+ public function show_create_view($viewName)
1207
+ {
1208
+ return "SHOW CREATE VIEW `$viewName`";
1209
+ }
1210
+
1211
+ public function show_create_trigger($triggerName)
1212
+ {
1213
+ return "SHOW CREATE TRIGGER `$triggerName`";
1214
+ }
1215
+
1216
+ public function create_table($row, $dumpSettings)
1217
+ {
1218
+ if (!isset($row['Create Table'])) {
1219
+ throw new Exception("Error getting table code, unknown output");
1220
+ }
1221
+
1222
+ $ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;/*SGEnd*/" . PHP_EOL .
1223
+ "/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;/*SGEnd*/" . PHP_EOL .
1224
+ $row['Create Table'] . ";/*SGEnd*/" . PHP_EOL .
1225
+ "/*!40101 SET character_set_client = @saved_cs_client */;/*SGEnd*/" . PHP_EOL .
1226
+ PHP_EOL;
1227
+ return $ret;
1228
+ }
1229
+
1230
+ public function create_view($row)
1231
+ {
1232
+ $ret = "";
1233
+ if (!isset($row['Create View'])) {
1234
+ throw new Exception("Error getting view structure, unknown output");
1235
+ }
1236
+
1237
+ $triggerStmt = $row['Create View'];
1238
+ $triggerStmtReplaced1 = str_replace(
1239
+ "CREATE ALGORITHM",
1240
+ "/*!50001 CREATE ALGORITHM",
1241
+ $triggerStmt
1242
+ );
1243
+ $triggerStmtReplaced2 = str_replace(
1244
+ " DEFINER=",
1245
+ " */" . PHP_EOL . "/*!50013 DEFINER=",
1246
+ $triggerStmtReplaced1
1247
+ );
1248
+ $triggerStmtReplaced3 = str_replace(
1249
+ " VIEW ",
1250
+ " */" . PHP_EOL . "/*!50001 VIEW ",
1251
+ $triggerStmtReplaced2
1252
+ );
1253
+ if (false === $triggerStmtReplaced1 ||
1254
+ false === $triggerStmtReplaced2 ||
1255
+ false === $triggerStmtReplaced3) {
1256
+ $triggerStmtReplaced = $triggerStmt;
1257
+ } else {
1258
+ $triggerStmtReplaced = $triggerStmtReplaced3 . " */;/*SGEnd*/";
1259
+ }
1260
+
1261
+ $ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
1262
+ return $ret;
1263
+ }
1264
+
1265
+ public function create_trigger($row)
1266
+ {
1267
+ $ret = "";
1268
+ if (!isset($row['SQL Original Statement'])) {
1269
+ throw new Exception("Error getting trigger code, unknown output");
1270
+ }
1271
+
1272
+ $triggerStmt = $row['SQL Original Statement'];
1273
+ $triggerStmtReplaced = str_replace(
1274
+ "CREATE DEFINER",
1275
+ "/*!50003 CREATE*/ /*!50017 DEFINER",
1276
+ $triggerStmt
1277
+ );
1278
+ $triggerStmtReplaced = str_replace(
1279
+ " TRIGGER",
1280
+ "*/ /*!50003 TRIGGER",
1281
+ $triggerStmtReplaced
1282
+ );
1283
+ if ( false === $triggerStmtReplaced ) {
1284
+ $triggerStmtReplaced = $triggerStmt;
1285
+ }
1286
+
1287
+ $ret .= "DELIMITER ;;/*SGEnd*/" . PHP_EOL .
1288
+ $triggerStmtReplaced . "*/;;/*SGEnd*/" . PHP_EOL .
1289
+ "DELIMITER ;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1290
+ return $ret;
1291
+ }
1292
+
1293
+ public function show_tables()
1294
+ {
1295
+ if (func_num_args() != 1) {
1296
+ return "";
1297
+ }
1298
+
1299
+ $args = func_get_args();
1300
+
1301
+ return "SELECT TABLE_NAME AS tbl_name " .
1302
+ "FROM INFORMATION_SCHEMA.TABLES " .
1303
+ "WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='${args[0]}'";
1304
+ }
1305
+
1306
+ public function show_views()
1307
+ {
1308
+ if (func_num_args() != 1) {
1309
+ return "";
1310
+ }
1311
+
1312
+ $args = func_get_args();
1313
+
1314
+ return "SELECT TABLE_NAME AS tbl_name " .
1315
+ "FROM INFORMATION_SCHEMA.TABLES " .
1316
+ "WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='${args[0]}'";
1317
+ }
1318
+
1319
+ public function show_triggers()
1320
+ {
1321
+ if (func_num_args() != 1) {
1322
+ return "";
1323
+ }
1324
+
1325
+ $args = func_get_args();
1326
+
1327
+ return "SHOW TRIGGERS FROM `${args[0]}`;";
1328
+ }
1329
+
1330
+
1331
+ public function show_columns()
1332
+ {
1333
+ if (func_num_args() != 1) {
1334
+ return "";
1335
+ }
1336
+
1337
+ $args = func_get_args();
1338
+
1339
+ return "SHOW COLUMNS FROM `${args[0]}`;";
1340
+ }
1341
+
1342
+ public function setup_transaction()
1343
+ {
1344
+ return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
1345
+ }
1346
+
1347
+ public function start_transaction()
1348
+ {
1349
+ return "START TRANSACTION";
1350
+ }
1351
+
1352
+ public function commit_transaction()
1353
+ {
1354
+ return "COMMIT";
1355
+ }
1356
+
1357
+ public function lock_table()
1358
+ {
1359
+ if (func_num_args() != 1) {
1360
+ return "";
1361
+ }
1362
+
1363
+ $args = func_get_args();
1364
+ //$tableName = $args[0];
1365
+ //return "LOCK TABLES `$tableName` READ LOCAL";
1366
+ return $this->dbHandler->query("LOCK TABLES `${args[0]}` READ LOCAL");
1367
+
1368
+ }
1369
+
1370
+ public function unlock_table()
1371
+ {
1372
+ return $this->dbHandler->query("UNLOCK TABLES");
1373
+ }
1374
+
1375
+ public function start_add_lock_table()
1376
+ {
1377
+ if (func_num_args() != 1) {
1378
+ return "";
1379
+ }
1380
+
1381
+ $args = func_get_args();
1382
+
1383
+ return "LOCK TABLES `${args[0]}` WRITE;/*SGEnd*/" . PHP_EOL;
1384
+ }
1385
+
1386
+ public function end_add_lock_table()
1387
+ {
1388
+ return "UNLOCK TABLES;/*SGEnd*/" . PHP_EOL;
1389
+ }
1390
+
1391
+ public function start_add_disable_keys()
1392
+ {
1393
+ if (func_num_args() != 1) {
1394
+ return "";
1395
+ }
1396
+ $args = func_get_args();
1397
+ return "/*!40000 ALTER TABLE `${args[0]}` DISABLE KEYS */;/*SGEnd*/" .
1398
+ PHP_EOL;
1399
+ }
1400
+
1401
+ public function end_add_disable_keys()
1402
+ {
1403
+ if (func_num_args() != 1) {
1404
+ return "";
1405
+ }
1406
+ $args = func_get_args();
1407
+ return "/*!40000 ALTER TABLE `${args[0]}` ENABLE KEYS */;/*SGEnd*/" .
1408
+ PHP_EOL;
1409
+ }
1410
+
1411
+ public function start_disable_autocommit()
1412
+ {
1413
+ return "SET autocommit=0;/*SGEnd*/" . PHP_EOL;
1414
+ }
1415
+
1416
+ public function end_disable_autocommit()
1417
+ {
1418
+ return "COMMIT;/*SGEnd*/" . PHP_EOL;
1419
+ }
1420
+
1421
+ public function add_drop_database()
1422
+ {
1423
+ if (func_num_args() != 1) {
1424
+ return "";
1425
+ }
1426
+
1427
+ $args = func_get_args();
1428
+
1429
+ return "/*!40000 DROP DATABASE IF EXISTS `${args[0]}`*/;/*SGEnd*/" .
1430
+ PHP_EOL . PHP_EOL;
1431
+ }
1432
+
1433
+ public function add_drop_trigger()
1434
+ {
1435
+ if (func_num_args() != 1) {
1436
+ return "";
1437
+ }
1438
+
1439
+ $args = func_get_args();
1440
+
1441
+ return "DROP TRIGGER IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL;
1442
+ }
1443
+
1444
+ public function drop_table()
1445
+ {
1446
+ if (func_num_args() != 1) {
1447
+ return "";
1448
+ }
1449
+
1450
+ $args = func_get_args();
1451
+
1452
+ return "DROP TABLE IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL;
1453
+ }
1454
+
1455
+ public function drop_view()
1456
+ {
1457
+ if (func_num_args() != 1) {
1458
+ return "";
1459
+ }
1460
+
1461
+ $args = func_get_args();
1462
+
1463
+ return "DROP TABLE IF EXISTS `${args[0]}`;/*SGEnd*/" . PHP_EOL .
1464
+ "/*!50001 DROP VIEW IF EXISTS `${args[0]}`*/;/*SGEnd*/" . PHP_EOL;
1465
+ }
1466
+
1467
+ public function getDatabaseHeader()
1468
+ {
1469
+ if (func_num_args() != 1) {
1470
+ return "";
1471
+ }
1472
+
1473
+ $args = func_get_args();
1474
+
1475
+ return "--" . PHP_EOL .
1476
+ "-- Current Database: `${args[0]}`" . PHP_EOL .
1477
+ "--" . PHP_EOL . PHP_EOL;
1478
+ }
1479
+
1480
+ /**
1481
+ * Decode column metadata and fill info structure.
1482
+ * type, is_numeric and is_blob will always be available.
1483
+ *
1484
+ * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
1485
+ * @return array
1486
+ */
1487
+ public function parseColumnType($colType)
1488
+ {
1489
+ $colInfo = array();
1490
+ $colParts = explode(" ", $colType['Type']);
1491
+
1492
+ if($fparen = strpos($colParts[0], "("))
1493
+ {
1494
+ $colInfo['type'] = substr($colParts[0], 0, $fparen);
1495
+ $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
1496
+ $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
1497
+ }
1498
+ else
1499
+ {
1500
+ $colInfo['type'] = $colParts[0];
1501
+ }
1502
+ $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
1503
+ $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
1504
+
1505
+ return $colInfo;
1506
+ }
1507
+
1508
+ public function backup_parameters()
1509
+ {
1510
+ if (func_num_args() != 1) {
1511
+ throw new Exception("Unexpected parameter passed to " . __METHOD__);
1512
+ }
1513
+
1514
+ $args = func_get_args();
1515
+ $dumpSettings = $args[0];
1516
+ $ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*SGEnd*/" . PHP_EOL .
1517
+ "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*SGEnd*/" . PHP_EOL .
1518
+ "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*SGEnd*/" . PHP_EOL .
1519
+ "/*!40101 SET NAMES " . $dumpSettings['default-character-set'] . " */;/*SGEnd*/" . PHP_EOL;
1520
+
1521
+ if (false === $dumpSettings['skip-tz-utz']) {
1522
+ $ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*SGEnd*/" . PHP_EOL .
1523
+ "/*!40103 SET TIME_ZONE='+00:00' */;/*SGEnd*/" . PHP_EOL;
1524
+ }
1525
+
1526
+ $ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*SGEnd*/" . PHP_EOL .
1527
+ "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*SGEnd*/" . PHP_EOL .
1528
+ "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*SGEnd*/" . PHP_EOL .
1529
+ "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;/*SGEnd*/" . PHP_EOL .PHP_EOL;
1530
+
1531
+ return $ret;
1532
+ }
1533
+
1534
+ public function restore_parameters()
1535
+ {
1536
+ if (func_num_args() != 1) {
1537
+ throw new Exception("Unexpected parameter passed to " . __METHOD__);
1538
+ }
1539
+
1540
+ $args = func_get_args();
1541
+ $dumpSettings = $args[0];
1542
+ $ret = "";
1543
+
1544
+ if (false === $dumpSettings['skip-tz-utz']) {
1545
+ $ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*SGEnd*/" . PHP_EOL;
1546
+ }
1547
+
1548
+ $ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*SGEnd*/" . PHP_EOL .
1549
+ "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*SGEnd*/" . PHP_EOL .
1550
+ "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*SGEnd*/" . PHP_EOL .
1551
+ "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*SGEnd*/" . PHP_EOL .
1552
+ "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*SGEnd*/" . PHP_EOL .
1553
+ "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;/*SGEnd*/" . PHP_EOL .
1554
+ "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;/*SGEnd*/" . PHP_EOL . PHP_EOL;
1555
+
1556
+ return $ret;
1557
+ }
1558
+ }
com/lib/SGUploadHandler.php CHANGED
@@ -1,38 +1,46 @@
1
- <?php
2
-
3
- namespace BackupGuard\Upload;
4
-
5
- class Handler
6
- {
7
- private $data = null;
8
- private $fileName = "";
9
- private $tmpFileName = "";
10
-
11
- public function __construct($data)
12
- {
13
- $this->data = $data;
14
- $this->import();
15
- }
16
-
17
- private function import()
18
- {
19
- $this->fileName = $this->data['files']['name'][0];
20
- $this->tmpFileName = $this->data['files']['tmp_name'][0];
21
-
22
- $dirPath = $this->getDestinationDirPath();
23
- $file = $dirPath.$this->fileName;
24
-
25
- $data = file_get_contents($this->tmpFileName);
26
- file_put_contents($file, $data, FILE_APPEND);
27
- }
28
-
29
- private function getDestinationDirPath()
30
- {
31
- return SG_BACKUP_DIRECTORY;
32
- }
33
-
34
- private function getDestinationDirUrl()
35
- {
36
- return SG_BACKUP_DIRECTORY_URL;
37
- }
38
- }
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace BackupGuard\Upload;
4
+
5
+ require_once(SG_LIB_PATH . 'SGArchive.php');
6
+
7
+ use SGArchive;
8
+
9
+ class Handler
10
+ {
11
+ private $data = null;
12
+ private $fileName = "";
13
+ private $tmpFileName = "";
14
+
15
+ public function __construct($data)
16
+ {
17
+ $this->data = $data;
18
+ $this->import();
19
+ }
20
+
21
+ private function import()
22
+ {
23
+ $this->fileName = $this->data['files']['name'][0];
24
+ $this->tmpFileName = $this->data['files']['tmp_name'][0];
25
+
26
+ if (substr($this->fileName, -5) != '.sgbp') {
27
+ $this->fileName .= '.sgbp';
28
+ }
29
+
30
+ $dirPath = $this->getDestinationDirPath();
31
+ $file = $dirPath . $this->fileName;
32
+
33
+ $data = file_get_contents($this->tmpFileName);
34
+ file_put_contents($file, $data, FILE_APPEND);
35
+ }
36
+
37
+ private function getDestinationDirPath()
38
+ {
39
+ return SG_BACKUP_DIRECTORY;
40
+ }
41
+
42
+ private function getDestinationDirUrl()
43
+ {
44
+ return SG_BACKUP_DIRECTORY_URL;
45
+ }
46
+ }
public/ajax/importBackup.php CHANGED
@@ -1,18 +1,24 @@
1
- <?php
2
- require_once(dirname(__FILE__).'/../boot.php');
3
- require_once(SG_BACKUP_PATH.'SGBackup.php');
4
- require_once(SG_LIB_PATH.'SGUploadHandler.php');
5
-
6
- $error = array();
7
- $success = array('success'=>1);
8
-
9
- try {
10
- $sgUploadHandler = new BackupGuard\Upload\Handler($_FILES);
11
- }
12
- catch (SGException $exception) {
13
- array_push($error, $exception->getMessage());
14
- die(json_encode($error));
15
- }
16
-
17
- echo json_encode($success);
18
- die();
 
 
 
 
 
 
1
+ <?php
2
+
3
+ require_once(dirname(__FILE__).'/../boot.php');
4
+ require_once(SG_BACKUP_PATH.'SGBackup.php');
5
+ require_once(SG_LIB_PATH.'SGUploadHandler.php');
6
+
7
+ $error = array();
8
+ $success = array('success'=>1);
9
+
10
+ try {
11
+
12
+ if (!current_user_can('administrator')) {
13
+ die();
14
+ }
15
+
16
+ $sgUploadHandler = new BackupGuard\Upload\Handler($_FILES);
17
+ }
18
+ catch (SGException $exception) {
19
+ array_push($error, $exception->getMessage());
20
+ die(json_encode($error));
21
+ }
22
+
23
+ echo json_encode($success);
24
+ die();
public/ajax/modalImport.php CHANGED
@@ -1,105 +1,105 @@
1
- <?php
2
- require_once(dirname(__FILE__).'/../boot.php');
3
- $backupDirectory = SGConfig::get('SG_BACKUP_DIRECTORY');
4
- $maxUploadSize = ini_get('upload_max_filesize');
5
- $dropbox = SGConfig::get('SG_DROPBOX_ACCESS_TOKEN');
6
- $gdrive = SGConfig::get('SG_GOOGLE_DRIVE_REFRESH_TOKEN');
7
- $ftp = SGConfig::get('SG_STORAGE_FTP_CONNECTED');
8
- $amazon = SGConfig::get('SG_AMAZON_KEY');
9
- $oneDrive = SGConfig::get('SG_ONE_DRIVE_REFRESH_TOKEN');
10
- $backupGuard = SGConfig::get('SG_BACKUPGUARD_UPLOAD_ACCESS_TOKEN');
11
- ?>
12
- <div class="modal-dialog">
13
- <div class="modal-content">
14
- <div class="modal-header">
15
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
16
- <h4 class="modal-title"><?php _backupGuardT('Import from')?></h4>
17
- </div>
18
- <div class="modal-body sg-modal-body" id="sg-modal-inport-from">
19
- <div class="col-md-12" id="modal-import-1">
20
- <div class="form-group">
21
- <table class="table table-striped paginated sg-backup-table">
22
- <tbody>
23
- <tr>
24
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="local-pc" checked></td>
25
- <td></td>
26
- <td><?php _backupGuardT('Local PC')?></td>
27
- </tr>
28
- <?php if (SGBoot::isFeatureAvailable('DOWNLOAD_FROM_CLOUD')): ?>
29
- <?php if (SGBoot::isFeatureAvailable('BACKUP_GUARD') && SG_SHOW_BACKUPGUARD_CLOUD): ?>
30
- <tr>
31
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_BACKUP_GUARD?>" <?php echo empty($backupGuard)?'disabled="disabled"':''?>></td>
32
- <td><span class="btn-xs sg-status-icon sg-status-36 active">&nbsp;</span></td>
33
- <td><?php echo 'BackupGuard' ?></td>
34
- </tr>
35
- <?php endif; ?>
36
- <tr>
37
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_FTP?>" <?php echo empty($ftp)?'disabled="disabled"':''?>></td>
38
- <td><span class="btn-xs sg-status-icon sg-status-31 active">&nbsp;</span></td>
39
- <td><?php echo 'FTP' ?></td>
40
- </tr>
41
- <tr>
42
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_DROPBOX?>" <?php echo empty($dropbox)?'disabled="disabled"':''?>></td>
43
- <td><span class="btn-xs sg-status-icon sg-status-32 active">&nbsp;</span></td>
44
- <td><?php echo 'Dropbox' ?></td>
45
- </tr>
46
- <tr>
47
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_GOOGLE_DRIVE?>" <?php echo empty($gdrive)?'disabled="disabled"':''?>></td>
48
- <td><span class="btn-xs sg-status-icon sg-status-33 active">&nbsp;</span></td>
49
- <td><?php echo 'Google Drive' ?></td>
50
- </tr>
51
- <tr>
52
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_AMAZON?>" <?php echo empty($amazon)?'disabled="disabled"':''?>></td>
53
- <td><span class="btn-xs sg-status-icon sg-status-34 active">&nbsp;</span></td>
54
- <td><?php echo (backupGuardIsAccountGold()? 'Amazon ':'').'S3' ?></td>
55
- </tr>
56
- <tr>
57
- <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_ONE_DRIVE?>" <?php echo empty($oneDrive)?'disabled="disabled"':''?>></td>
58
- <td><span class="btn-xs sg-status-icon sg-status-35 active">&nbsp;</span></td>
59
- <td><?php echo 'One Drive' ?></td>
60
- </tr>
61
- <?php endif; ?>
62
- </tbody>
63
- </table>
64
- </div>
65
- </div>
66
- <div class="col-md-12" id="modal-import-2">
67
- <div class="form-group import-modal-popup-content">
68
- <div class="col-md-9">
69
- <input type="text" id="sg-import-file-name" class="form-control sg-backup-input" placeholder="<?php _backupGuardT('SGBP file')?>" readonly>
70
- </div>
71
- <div class="col-lg-3">
72
- <span class="input-group-btn">
73
- <span class="btn btn-primary btn-file backup-browse-btn">
74
- <?php _backupGuardT('Browse')?>&hellip; <input class="sg-backup-upload-input" type="file" name="files[]" data-url="<?php echo admin_url('admin-ajax.php')."?action=backup_guard_importBackup&token=".wp_create_nonce('backupGuardAjaxNonce') ?>" data-max-file-size="<?php echo backupGuardConvertToBytes($maxUploadSize.'B'); ?>">
75
- </span>
76
- </span>
77
- </div>
78
- </div>
79
- </div>
80
- <?php if (SGBoot::isFeatureAvailable('DOWNLOAD_FROM_CLOUD')): ?>
81
- <div class="col-md-12" id="modal-import-3">
82
- <table class="table table-striped paginated sg-backup-table" id="sg-archive-list-table">
83
- <thead>
84
- <tr>
85
- <th></th>
86
- <th><?php _backupGuardT('Filename')?></th>
87
- <th><?php _backupGuardT('Size')?></th>
88
- <th><?php _backupGuardT('Date')?></th>
89
- </tr>
90
- </thead>
91
- <tbody>
92
- </tbody>
93
- </table>
94
- </div>
95
- <?php endif; ?>
96
- <div class="clearfix"></div>
97
- </div>
98
- <div class="modal-footer">
99
- <button type="button" class="pull-left btn btn-primary" id="switch-modal-import-pages-back" onclick="sgBackup.previousPage()"><?php _backupGuardT('Back')?></button>
100
- <span class="modal-close-button" id="sg-close-modal-import" data-dismiss="modal"><?php _backupGuardT("Close")?></span>
101
- <button type="button" class="btn btn-success" id="switch-modal-import-pages-next" data-remote="importBackup" onclick="sgBackup.nextPage()"><?php _backupGuardT('Next')?></button>
102
- <button type="button" data-remote="importBackup" id="uploadSgbpFile" class="btn btn-success"><?php _backupGuardT('Import')?></button>
103
- </div>
104
- </div>
105
- </div>
1
+ <?php
2
+ require_once(dirname(__FILE__).'/../boot.php');
3
+ $backupDirectory = SGConfig::get('SG_BACKUP_DIRECTORY');
4
+ $maxUploadSize = ini_get('upload_max_filesize');
5
+ $dropbox = SGConfig::get('SG_DROPBOX_ACCESS_TOKEN');
6
+ $gdrive = SGConfig::get('SG_GOOGLE_DRIVE_REFRESH_TOKEN');
7
+ $ftp = SGConfig::get('SG_STORAGE_FTP_CONNECTED');
8
+ $amazon = SGConfig::get('SG_AMAZON_KEY');
9
+ $oneDrive = SGConfig::get('SG_ONE_DRIVE_REFRESH_TOKEN');
10
+ $backupGuard = SGConfig::get('SG_BACKUPGUARD_UPLOAD_ACCESS_TOKEN');
11
+ ?>
12
+ <div class="modal-dialog">
13
+ <div class="modal-content">
14
+ <div class="modal-header">
15
+ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
16
+ <h4 class="modal-title"><?php _backupGuardT('Import from')?></h4>
17
+ </div>
18
+ <div class="modal-body sg-modal-body" id="sg-modal-inport-from">
19
+ <div class="col-md-12" id="modal-import-1">
20
+ <div class="form-group">
21
+ <table class="table table-striped paginated sg-backup-table">
22
+ <tbody>
23
+ <tr>
24
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="local-pc" checked></td>
25
+ <td></td>
26
+ <td><?php _backupGuardT('Local PC')?></td>
27
+ </tr>
28
+ <?php if (SGBoot::isFeatureAvailable('DOWNLOAD_FROM_CLOUD')): ?>
29
+ <?php if (SGBoot::isFeatureAvailable('BACKUP_GUARD') && SG_SHOW_BACKUPGUARD_CLOUD): ?>
30
+ <tr>
31
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_BACKUP_GUARD?>" <?php echo empty($backupGuard)?'disabled="disabled"':''?>></td>
32
+ <td><span class="btn-xs sg-status-icon sg-status-36 active">&nbsp;</span></td>
33
+ <td><?php echo 'BackupGuard' ?></td>
34
+ </tr>
35
+ <?php endif; ?>
36
+ <tr>
37
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_FTP?>" <?php echo empty($ftp)?'disabled="disabled"':''?>></td>
38
+ <td><span class="btn-xs sg-status-icon sg-status-31 active">&nbsp;</span></td>
39
+ <td><?php echo 'FTP' ?></td>
40
+ </tr>
41
+ <tr>
42
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_DROPBOX?>" <?php echo empty($dropbox)?'disabled="disabled"':''?>></td>
43
+ <td><span class="btn-xs sg-status-icon sg-status-32 active">&nbsp;</span></td>
44
+ <td><?php echo 'Dropbox' ?></td>
45
+ </tr>
46
+ <tr>
47
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_GOOGLE_DRIVE?>" <?php echo empty($gdrive)?'disabled="disabled"':''?>></td>
48
+ <td><span class="btn-xs sg-status-icon sg-status-33 active">&nbsp;</span></td>
49
+ <td><?php echo 'Google Drive' ?></td>
50
+ </tr>
51
+ <tr>
52
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_AMAZON?>" <?php echo empty($amazon)?'disabled="disabled"':''?>></td>
53
+ <td><span class="btn-xs sg-status-icon sg-status-34 active">&nbsp;</span></td>
54
+ <td><?php echo (backupGuardIsAccountGold()? 'Amazon ':'').'S3' ?></td>
55
+ </tr>
56
+ <tr>
57
+ <td class="file-select-radio"><input name="storage-radio" type="radio" value="<?php echo SG_STORAGE_ONE_DRIVE?>" <?php echo empty($oneDrive)?'disabled="disabled"':''?>></td>
58
+ <td><span class="btn-xs sg-status-icon sg-status-35 active">&nbsp;</span></td>
59
+ <td><?php echo 'One Drive' ?></td>
60
+ </tr>
61
+ <?php endif; ?>
62
+ </tbody>
63
+ </table>
64
+ </div>
65
+ </div>
66
+ <div class="col-md-12" id="modal-import-2">
67
+ <div class="form-group import-modal-popup-content">
68
+ <div class="col-md-9">
69
+ <input type="text" id="sg-import-file-name" class="form-control sg-backup-input" placeholder="<?php _backupGuardT('SGBP file')?>" readonly>
70
+ </div>
71
+ <div class="col-lg-3">
72
+ <span class="input-group-btn">
73
+ <span class="btn btn-primary btn-file backup-browse-btn">
74
+ <?php _backupGuardT('Browse')?>&hellip; <input class="sg-backup-upload-input" type="file" name="files[]" data-url="<?php echo admin_url('admin-ajax.php')."?action=backup_guard_importBackup&token=".wp_create_nonce('backupGuardAjaxNonce') ?>" data-max-file-size="<?php echo backupGuardConvertToBytes($maxUploadSize.'B'); ?>" accept=".sgbp">
75
+ </span>
76
+ </span>
77
+ </div>
78
+ </div>
79
+ </div>
80
+ <?php if (SGBoot::isFeatureAvailable('DOWNLOAD_FROM_CLOUD')): ?>
81
+ <div class="col-md-12" id="modal-import-3">
82
+ <table class="table table-striped paginated sg-backup-table" id="sg-archive-list-table">
83
+ <thead>
84
+ <tr>
85
+ <th></th>
86
+ <th><?php _backupGuardT('Filename')?></th>
87
+ <th><?php _backupGuardT('Size')?></th>
88
+ <th><?php _backupGuardT('Date')?></th>
89
+ </tr>
90
+ </thead>
91
+ <tbody>
92
+ </tbody>
93
+ </table>
94
+ </div>
95
+ <?php endif; ?>
96
+ <div class="clearfix"></div>
97
+ </div>
98
+ <div class="modal-footer">
99
+ <button type="button" class="pull-left btn btn-primary" id="switch-modal-import-pages-back" onclick="sgBackup.previousPage()"><?php _backupGuardT('Back')?></button>
100
+ <span class="modal-close-button" id="sg-close-modal-import" data-dismiss="modal"><?php _backupGuardT("Close")?></span>
101
+ <button type="button" class="btn btn-success" id="switch-modal-import-pages-next" data-remote="importBackup" onclick="sgBackup.nextPage()"><?php _backupGuardT('Next')?></button>
102
+ <button type="button" data-remote="importBackup" id="uploadSgbpFile" class="btn btn-success"><?php _backupGuardT('Import')?></button>
103
+ </div>
104
+ </div>
105
+ </div>
public/include/sidebar.php CHANGED
@@ -1,125 +1,125 @@
1
- <?php
2
- $extensionAdapter = SGExtension::getInstance();
3
- $page = $_GET['page'];
4
-
5
- $isDisabelAdsEnabled = SGConfig::get('SG_DISABLE_ADS');
6
- $showUpgradeButton = SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE');
7
- $buttonText = 'Buy now!';
8
- $upgradeText = 'Website migration, Backup to cloud, automatization, mail notifications, and more in our PRO package!';
9
- $buttonUrl = SG_BACKUP_SITE_URL;
10
-
11
- $pluginCapabilities = backupGuardGetCapabilities();
12
-
13
- if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
14
- $buttonText = 'Upgrade to ';
15
- $buttonUrl = SG_BACKUP_PRODUCTS_URL;
16
-
17
- $upgradeTo = "";
18
- if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_GOLD) {
19
- $upgradeTo = 'Platinum';
20
- }
21
- else if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_SILVER) {
22
- $upgradeTo = 'Gold';
23
- }
24
-
25
- $upgradeText = $buttonText.$upgradeTo.' by paying only difference between plans.';
26
- $buttonText = $buttonText.$upgradeTo;
27
- }
28
-
29
- $supportUrl = network_admin_url('admin.php?page=backup_guard_support');
30
- $openContent = 1;
31
- if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_FREE) {
32
- $openContent = 0;
33
- $supportUrl = BACKUP_GUARD_WORDPRESS_SUPPORT_URL;
34
- }
35
- ?>
36
- <div id="sg-sidebar-wrapper" class="metro">
37
- <a class="sg-site-url" href="<?php echo network_admin_url('admin.php?page=backup_guard_backups'); ?>">
38
- <div class="title">
39
- <span class="sg-action-menu-arrow"></span>
40
- </div>
41
- </a>
42
- <nav class="sidebar dark sg-backup-sidebar-nav">
43
- <ul>
44
- <li class="<?php echo strpos($page,'backups')?'active':''?>">
45
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_backups'); ?>" data-page-key="backups">
46
- <span class="glyphicon glyphicon-hdd"></span><?php _backupGuardT('Backups')?>
47
- </a>
48
- <span class="sg-action-menu-arrow"></span>
49
- </li>
50
- <li class="<?php echo strpos($page,'cloud')?'active':''?>">
51
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_cloud'); ?>" data-page-key="cloud">
52
- <span class="glyphicon glyphicon-cloud" aria-hidden="true"></span><?php _backupGuardT('Cloud')?>
53
- </a>
54
- <span class="sg-action-menu-arrow"></span>
55
- </li>
56
- <?php if (SGBoot::isFeatureAvailable('SCHEDULE')):?>
57
- <li class="<?php echo strpos($page,'schedule')?'active':''?>">
58
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_schedule'); ?>" data-page-key="schedule">
59
- <span class="glyphicon glyphicon-time" aria-hidden="true"></span><?php _backupGuardT('Schedule')?>
60
- </a>
61
- <span class="sg-action-menu-arrow"></span>
62
- </li>
63
- <?php endif;?>
64
- <li class="<?php echo strpos($page,'settings')?'active':''?>">
65
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_settings'); ?>" data-page-key="settings">
66
- <span class="glyphicon glyphicon-cog" aria-hidden="true"></span><?php _backupGuardT('Settings')?>
67
- </a>
68
- <span class="sg-action-menu-arrow"></span>
69
- </li>
70
- <li class="<?php echo strpos($page,'system_info')?'active':''?>">
71
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_system_info'); ?>" data-page-key="system_info">
72
- <span class="glyphicon glyphicon-equalizer" aria-hidden="true"></span><?php _backupGuardT('System Info.')?>
73
- </a>
74
- <span class="sg-action-menu-arrow"></span>
75
- </li>
76
- <li class="<?php echo strpos($page,'services')?'active':''?>">
77
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_services'); ?>" data-page-key="services">
78
- <span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span><?php _backupGuardT('Services')?>
79
- </a>
80
- <span class="sg-action-menu-arrow"></span>
81
- </li>
82
- <li class="<?php echo strpos($page,'videoTutorials')?'active':''?>">
83
- <a href="<?php echo $supportUrl; ?>" data-page-key="videoTutorials">
84
- <span class="sg-backup-menu-video" aria-hidden="true"></span><?php _backupGuardT('Video Tutorials')?>
85
- </a>
86
- <span class="sg-action-menu-arrow"></span>
87
- </li>
88
- <li class="<?php echo strpos($page,'support')?'active':''?>">
89
- <a href="<?php echo $supportUrl; ?>" data-page-key="support" data-open-content="<?php echo $openContent; ?>">
90
- <span class="glyphicon glyphicon-envelope" aria-hidden="true"></span><?php _backupGuardT('Support')?>
91
- </a>
92
- <span class="sg-action-menu-arrow"></span>
93
- </li>
94
- <?php if (SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE')):?>
95
- <li class="<?php echo strpos($page,'pro_features')?'active':''?>">
96
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_pro_features'); ?>" data-page-key="pro_features">
97
- <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span><?php _backupGuardT('Why upgrade?')?>
98
- </a>
99
- <span class="sg-action-menu-arrow"></span>
100
- </li>
101
- <?php endif; ?>
102
- <!-- Will be added in the future release -->
103
- <!-- <?php if ($extensionAdapter->isExtensionActive(SG_BACKUP_GUARD_SECURITY_EXTENSION)):?>
104
- <li class="<?php echo strpos($page,'security')?'active':''?>">
105
- <a href="<?php echo network_admin_url('admin.php?page=backup_guard_security'); ?>">
106
- <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>Security
107
- <span class="badge badge-info">New</span>
108
- </a>
109
- </li>
110
- <?php endif; ?> -->
111
- </ul>
112
- </nav>
113
- <?php if ($showUpgradeButton && !$isDisabelAdsEnabled):?>
114
- <div class="sg-alert-pro">
115
- <p class="sg-upgrade-text">
116
- <?php _backupGuardT($upgradeText); ?>
117
- </p>
118
- <p>
119
- <a class="btn btn-success" target="_blank" href="<?php echo $buttonUrl; ?>">
120
- <?php _backupGuardT($buttonText); ?>
121
- </a>
122
- </p>
123
- </div>
124
- <?php endif; ?>
125
- </div>
1
+ <?php
2
+ $extensionAdapter = SGExtension::getInstance();
3
+ $page = $_GET['page'];
4
+
5
+ $isDisabelAdsEnabled = SGConfig::get('SG_DISABLE_ADS');
6
+ $showUpgradeButton = SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE');
7
+ $buttonText = 'Buy now!';
8
+ $upgradeText = 'Website migration, Backup to cloud, automatization, mail notifications, and more in our PRO package!';
9
+ $buttonUrl = SG_BACKUP_SITE_URL;
10
+
11
+ $pluginCapabilities = backupGuardGetCapabilities();
12
+
13
+ if ($pluginCapabilities != BACKUP_GUARD_CAPABILITIES_FREE) {
14
+ $buttonText = 'Upgrade to ';
15
+ $buttonUrl = SG_BACKUP_PRODUCTS_URL;
16
+
17
+ $upgradeTo = "";
18
+ if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_GOLD) {
19
+ $upgradeTo = 'Platinum';
20
+ }
21
+ else if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_SILVER) {
22
+ $upgradeTo = 'Gold';
23
+ }
24
+
25
+ $upgradeText = $buttonText.$upgradeTo.' by paying only difference between plans.';
26
+ $buttonText = $buttonText.$upgradeTo;
27
+ }
28
+
29
+ $supportUrl = network_admin_url('admin.php?page=backup_guard_support');
30
+ $openContent = 1;
31
+ if ($pluginCapabilities == BACKUP_GUARD_CAPABILITIES_FREE) {
32
+ $openContent = 0;
33
+ $supportUrl = BACKUP_GUARD_WORDPRESS_SUPPORT_URL;
34
+ }
35
+ ?>
36
+ <div id="sg-sidebar-wrapper" class="metro">
37
+ <a class="sg-site-url" href="<?php echo network_admin_url('admin.php?page=backup_guard_backups'); ?>">
38
+ <div class="title">
39
+ <span class="sg-action-menu-arrow"></span>
40
+ </div>
41
+ </a>
42
+ <nav class="sidebar dark sg-backup-sidebar-nav" id="sg-main-sidebar">
43
+ <ul>
44
+ <li class="<?php echo strpos($page,'backups')?'active':''?>">
45
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_backups'); ?>" data-page-key="backups">
46
+ <span class="glyphicon glyphicon-hdd"></span><?php _backupGuardT('Backups')?>
47
+ </a>
48
+ <span class="sg-action-menu-arrow"></span>
49
+ </li>
50
+ <li class="<?php echo strpos($page,'cloud')?'active':''?>">
51
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_cloud'); ?>" data-page-key="cloud">
52
+ <span class="glyphicon glyphicon-cloud" aria-hidden="true"></span><?php _backupGuardT('Cloud')?>
53
+ </a>
54
+ <span class="sg-action-menu-arrow"></span>
55
+ </li>
56
+ <?php if (SGBoot::isFeatureAvailable('SCHEDULE')):?>
57
+ <li class="<?php echo strpos($page,'schedule')?'active':''?>">
58
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_schedule'); ?>" data-page-key="schedule">
59
+ <span class="glyphicon glyphicon-time" aria-hidden="true"></span><?php _backupGuardT('Schedule')?>
60
+ </a>
61
+ <span class="sg-action-menu-arrow"></span>
62
+ </li>
63
+ <?php endif;?>
64
+ <li class="<?php echo strpos($page,'settings')?'active':''?>">
65
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_settings'); ?>" data-page-key="settings">
66
+ <span class="glyphicon glyphicon-cog" aria-hidden="true"></span><?php _backupGuardT('Settings')?>
67
+ </a>
68
+ <span class="sg-action-menu-arrow"></span>
69
+ </li>
70
+ <li class="<?php echo strpos($page,'system_info')?'active':''?>">
71
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_system_info'); ?>" data-page-key="system_info">
72
+ <span class="glyphicon glyphicon-equalizer" aria-hidden="true"></span><?php _backupGuardT('System Info.')?>
73
+ </a>
74
+ <span class="sg-action-menu-arrow"></span>
75
+ </li>
76
+ <li class="<?php echo strpos($page,'services')?'active':''?>">
77
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_services'); ?>" data-page-key="services">
78
+ <span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span><?php _backupGuardT('Services')?>
79
+ </a>
80
+ <span class="sg-action-menu-arrow"></span>
81
+ </li>
82
+ <li class="<?php echo strpos($page,'videoTutorials')?'active':''?>">
83
+ <a href="<?php echo $supportUrl; ?>" data-page-key="videoTutorials">
84
+ <span class="sg-backup-menu-video" aria-hidden="true"></span><?php _backupGuardT('Video Tutorials')?>
85
+ </a>
86
+ <span class="sg-action-menu-arrow"></span>
87
+ </li>
88
+ <li class="<?php echo strpos($page,'support')?'active':''?>">
89
+ <a href="<?php echo $supportUrl; ?>" data-page-key="support" data-open-content="<?php echo $openContent; ?>">
90
+ <span class="glyphicon glyphicon-envelope" aria-hidden="true"></span><?php _backupGuardT('Support')?>
91
+ </a>
92
+ <span class="sg-action-menu-arrow"></span>
93
+ </li>
94
+ <?php if (SGBoot::isFeatureAvailable('SHOW_UPGRADE_PAGE')):?>
95
+ <li class="<?php echo strpos($page,'pro_features')?'active':''?>">
96
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_pro_features'); ?>" data-page-key="pro_features">
97
+ <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span><?php _backupGuardT('Why upgrade?')?>
98
+ </a>
99
+ <span class="sg-action-menu-arrow"></span>
100
+ </li>
101
+ <?php endif; ?>
102
+ <!-- Will be added in the future release -->
103
+ <!-- <?php if ($extensionAdapter->isExtensionActive(SG_BACKUP_GUARD_SECURITY_EXTENSION)):?>
104
+ <li class="<?php echo strpos($page,'security')?'active':''?>">
105
+ <a href="<?php echo network_admin_url('admin.php?page=backup_guard_security'); ?>">
106
+ <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>Security
107
+ <span class="badge badge-info">New</span>
108
+ </a>
109
+ </li>
110
+ <?php endif; ?> -->
111
+ </ul>
112
+ </nav>
113
+ <?php if ($showUpgradeButton && !$isDisabelAdsEnabled):?>
114
+ <div class="sg-alert-pro">
115
+ <p class="sg-upgrade-text">
116
+ <?php _backupGuardT($upgradeText); ?>
117
+ </p>
118
+ <p>
119
+ <a class="btn btn-success" target="_blank" href="<?php echo $buttonUrl; ?>">
120
+ <?php _backupGuardT($buttonText); ?>
121
+ </a>
122
+ </p>
123
+ </div>
124
+ <?php endif; ?>
125
+ </div>
public/js/main.js CHANGED
@@ -1,563 +1,575 @@
1
- sgBackup = {};
2
- sgBackup.isModalOpen = false;
3
- SG_CURRENT_ACTIVE_AJAX = '';
4
- SG_NOTICE_EXECUTION_TIMEOUT = 'timeout_error';
5
- SG_NOTICE_EXECUTION_FREE_TIMEOUT = 'timeout_free_error';
6
- SG_NOTICE_MIGRATION_ERROR = 'migration_error';
7
- SG_NOTICE_NOT_WRITABLE_ERROR = 'restore_notwritable_error';
8
-
9
- jQuery(window).on('load', function() {
10
- if (jQuery('.sg-active-action-id').length == 0) {
11
- sgBackup.showReviewModal();
12
- }
13
- });
14
-
15
- jQuery(document).ready( function() {
16
- jQuery('span[data-toggle=tooltip]').tooltip();
17
-
18
- sgBackup.init();
19
-
20
- jQuery('.sg-badge-warning').on('click', function () {
21
- var url = jQuery(this).attr('target-url');
22
- if (url) {
23
- window.open(url, '_blank');
24
- }
25
- });
26
-
27
- jQuery("#rateYo").rateYo({
28
- rating: 5,
29
- fullStar: true,
30
- spacing: "3px",
31
- starWidth: "16px",
32
- starHeight: "16px",
33
- rating: 4.5,
34
- ratedFill: "#ffffff"
35
- });
36
-
37
- if (typeof SG_AJAX_REQUEST_FREQUENCY === 'undefined'){
38
- SG_AJAX_REQUEST_FREQUENCY = 2000;
39
- }
40
-
41
- sgBackup.hideAjaxSpinner();
42
- var notice = "";
43
- jQuery('.notice-dismiss').on('click', function() {
44
- if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_EXECUTION_TIMEOUT) {
45
- notice = SG_NOTICE_EXECUTION_TIMEOUT;
46
- }
47
- else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_EXECUTION_FREE_TIMEOUT) {
48
- notice = SG_NOTICE_EXECUTION_TIMEOUT;
49
- }
50
- else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_MIGRATION_ERROR) {
51
- notice = SG_NOTICE_MIGRATION_ERROR;
52
- }
53
- else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_NOT_WRITABLE_ERROR) {
54
- notice = SG_NOTICE_NOT_WRITABLE_ERROR
55
- }
56
- var sgNoticeClosedHandler = new sgRequestHandler('hideNotice', {notice: notice, token: BG_BACKUP_STRINGS.nonce});
57
- sgNoticeClosedHandler.run();
58
- });
59
-
60
- //send awake requests only if there is an active action
61
- if (jQuery('.sg-active-action-id').length>0) {
62
- setInterval(sgBackup.awake, SG_AJAX_REQUEST_FREQUENCY);
63
- }
64
- });
65
-
66
- sgBackup.awake = function(){
67
- var awakeAjaxHandler = new sgRequestHandler('awake', {token: BG_BACKUP_STRINGS.nonce});
68
- awakeAjaxHandler.run();
69
- }
70
-
71
- //SG init
72
- sgBackup.init = function(){
73
- sgBackup.initModals();
74
- sgBackup.downloadButton();
75
- sgBackup.navMenu();
76
- sgBackup.sendUsageDataStatus();
77
- };
78
-
79
- sgBackup.sendUsageDataStatus = function ()
80
- {
81
- var checkbox = jQuery('.backup-send-usage-data-status');
82
-
83
- if (!checkbox.length) {
84
- return false;
85
- }
86
-
87
- checkbox.bind('switchChange.bootstrapSwitch', function () {
88
- var currentStatus = jQuery(this).is(':checked');
89
- var action = 'send_usage_status';
90
- jQuery(this).prop('disabled', true);
91
- var ajaxHandler = new sgRequestHandler(action, {currentStatus: currentStatus, token: BG_BACKUP_STRINGS.nonce});
92
- ajaxHandler.callback = function(data, error) {
93
- jQuery(this).prop('disabled', false);
94
- }
95
-
96
- ajaxHandler.run();
97
- });
98
- };
99
-
100
- sgBackup.navMenu = function ()
101
- {
102
- var navMenu = jQuery('.sg-backup-sidebar-nav a');
103
-
104
- if (!navMenu.length) {
105
- return false;
106
- }
107
-
108
- navMenu.unbind('click').bind('click', function (event) {
109
- event.preventDefault();
110
- sgBackup.init();
111
-
112
- var currentUrl = jQuery(this).attr('href');
113
- var openContent = jQuery(this).data('open-content');
114
-
115
- if (typeof openContent != 'undefined' && openContent == 0) {
116
- window.open(currentUrl);
117
- return true;
118
- }
119
- jQuery('.sg-backup-page-content').addClass('sg-visibility-hidden');
120
- jQuery('.sg-backup-sidebar-nav li').removeClass('active');
121
-
122
- var currentKey = jQuery(this).data('page-key');
123
- var currentPageContent = jQuery('#sg-backup-page-content-'+currentKey);
124
-
125
- if (!currentPageContent.length) {
126
- return false;
127
- }
128
- jQuery(this).parent().addClass('active');
129
- currentPageContent.removeClass('sg-visibility-hidden');
130
- });
131
- };
132
-
133
- sgBackup.downloadButton = function()
134
- {
135
- var downloadButtons = jQuery('.sg-bg-download-button');
136
-
137
- if (!downloadButtons.length) {
138
- return false;
139
- }
140
- var isOPen = false;
141
- jQuery(window).bind('click', function () {
142
- if (isOPen) {
143
- jQuery('.sg-backup-table .dropdown-menu').removeClass('sg-bg-show');
144
- isOPen = false;
145
- }
146
- });
147
-
148
- downloadButtons.bind('click', function () {
149
- var currentButton = jQuery(this);
150
-
151
- if (!currentButton.length) {
152
- return false;
153
- }
154
- setTimeout(function () {
155
- currentButton.next().addClass('sg-bg-show');
156
- isOPen = true;
157
- }, 0);
158
- });
159
- };
160
-
161
- //SG Modal popup logic
162
- sgBackup.initModals = function(){
163
-
164
- jQuery('[data-toggle="modal"][href], [data-toggle="modal"][data-remote]').off('click').on('click', function(e) {
165
- var param = '';
166
- if (typeof jQuery(this).attr('data-sgbp-params') !== 'undefined'){
167
- param = jQuery(this).attr('data-sgbp-params');
168
- }
169
-
170
- e.preventDefault();
171
- var btn = jQuery(this),
172
- url = btn.attr('data-remote'),
173
- modalName = btn.attr('data-modal-name'),
174
- backupType = btn.attr('sg-data-backup-type'),
175
- modal = jQuery('#sg-modal');
176
- if( modal.length == 0 ) {
177
- modal = jQuery('' +
178
- '<div class="modal fade" id="sg-modal" tabindex="-1" role="dialog" aria-hidden="true"></div>' +
179
- '');
180
- body.append(modal);
181
- }
182
- sgBackup.showAjaxSpinner('#sg-content-wrapper');
183
- if (typeof sgBackup.disableUi == 'function') {
184
- sgBackup.disableUi();
185
- }
186
-
187
- var ajaxHandler = new sgRequestHandler(url, {
188
- param: param,
189
- backupType: backupType,
190
- token: BG_BACKUP_STRINGS.nonce
191
- });
192
-
193
- if (modalName == 'backup-guard-details') {
194
- modal.modal({
195
- backdrop: 'static',
196
- keyboard: false
197
- });
198
- }
199
-
200
- ajaxHandler.type = 'GET';
201
- ajaxHandler.dataType = 'html';
202
- ajaxHandler.callback = function(data, error) {
203
- sgBackup.hideAjaxSpinner();
204
- if (typeof sgBackup.enableUi == 'function') {
205
- sgBackup.enableUi();
206
- }
207
- if (error===false) {
208
- jQuery('#sg-modal').append(data);
209
- }
210
- modal.on('hide.bs.modal', function() {
211
- if(SG_CURRENT_ACTIVE_AJAX != '') {
212
- if (!confirm(BG_MAIN_STRINGS.confirmCancel)) {
213
- return false;
214
- }
215
- SG_CURRENT_ACTIVE_AJAX.abort();
216
- SG_CURRENT_ACTIVE_AJAX = '';
217
- }
218
- });
219
- modal.one('hidden.bs.modal', function() {
220
- modal.html('');
221
- }).modal('show');
222
- sgBackup.didOpenModal(modalName, param);
223
- };
224
-
225
- if (modalName == 'ftp-settings' || modalName == 'amazon-settings') {
226
- var storage = 'FTP';
227
- if (modalName == 'amazon-settings') {
228
- storage = 'AMAZON';
229
- }
230
- error = false;
231
- var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: storage});
232
- isFeatureAvailable.callback = function(response) {
233
- if (typeof response.error !== 'undefined') {
234
- var alert = sgBackup.alertGenerator(response.error, 'alert-warning');
235
- jQuery('.sg-cloud-container legend').after(alert);
236
- that.bootstrapSwitch('state', false);
237
- sgBackup.hideAjaxSpinner();
238
- }
239
- else {
240
- ajaxHandler.run();
241
- }
242
- }
243
-
244
- isFeatureAvailable.run();
245
- }
246
- else {
247
- ajaxHandler.run();
248
- }
249
- });
250
- };
251
-
252
- sgBackup.toggleSftpSettings = function() {
253
- jQuery('#ftpPort').val('22');
254
- jQuery('#sg-sftp-key-file-block').show();
255
- jQuery('#sg-browse-key-file-block').hide();
256
-
257
- if (jQuery('#sg-connect-with-key-file').is(':checked') && connectioType=='sftp') {
258
- jQuery('#sg-browse-key-file-block').show();
259
- }
260
- }
261
-
262
- sgBackup.toggleFtpSettings = function() {
263
- jQuery('#ftpPort').val('21');
264
- jQuery('#sg-sftp-key-file-block').hide();
265
- }
266
-
267
- // Show/hide some fields that are needed/not needed for ftp/sftp
268
- sgBackup.toggleNeededFtpFields = function(connectioType) {
269
- if(connectioType == 'sftp') {
270
- sgBackup.toggleSftpSettings();
271
-
272
- }
273
- else if(connectioType == 'ftp') {
274
- sgBackup.toggleFtpSettings();
275
- }
276
- }
277
-
278
- sgBackup.didOpenModal = function(modalName, param){
279
- if(modalName == 'manual-backup' || modalName == 'manual-restore'){
280
- sgBackup.initManulBackupRadioInputs();
281
- sgBackup.initManualBackupTooltips();
282
- jQuery('#fileSystemTreeContainer').jstree({ 'core' : {
283
-
284
- 'data' : {
285
- 'url' : function (node) {
286
- return getAjaxUrl();
287
- },
288
- 'data' : function (node) {
289
- var path = node.id;
290
- return { action:"backup_guard_getBackupContent", path:path, backupName:param, token: BG_BACKUP_STRINGS.nonce };
291
- }
292
- }
293
- },
294
- "plugins" : ["wholerow", "checkbox", "types"],
295
- "checkbox" : {
296
- "keep_selected_style" : false
297
- },
298
- "types": {
299
- "file": {
300
- "icon": "bg-file-icon"
301
- },
302
- "folder": {
303
- "icon": "bg-folder-icon"
304
- },
305
- "default":{
306
- "icon": "bg-no-icon"
307
- }
308
- }
309
- });
310
- }
311
- else if(modalName == 'import'){
312
- sgBackup.initImportTooltips();
313
- jQuery('#modal-import-2').hide();
314
- jQuery('#modal-import-3').hide();
315
- jQuery('#switch-modal-import-pages-back').hide();
316
- jQuery('#uploadSgbpFile').hide();
317
- if(jQuery('#modal-import-1').length == 0) {
318
- sgBackup.toggleDownloadFromPCPage();
319
- }
320
- sgBackup.initFileUpload();
321
- }
322
- else if(modalName == 'ftp-settings'){
323
- connectioType = jQuery('#sg-connection-method').val();
324
- sgBackup.toggleNeededFtpFields(connectioType);
325
-
326
- jQuery('#sg-connection-method').on('change', function(){
327
- connectioType = jQuery(this).val();
328
- sgBackup.toggleNeededFtpFields(connectioType);
329
- });
330
-
331
- jQuery('#sg-connect-with-key-file').on('click', function(){
332
- if(jQuery(this).is(':checked')) {
333
- jQuery('#sg-browse-key-file-block').show();
334
- }
335
- else {
336
- jQuery('#sg-browse-key-file-block').hide();
337
- }
338
- })
339
-
340
- sgBackup.initSFTPKeyFileSelection();
341
-
342
- jQuery('#sg-modal').on('hidden.bs.modal', function () {
343
- if(sgBackup.isFtpConnected != true) {
344
- jQuery('input[data-storage=FTP]').bootstrapSwitch('state', false);
345
- }
346
- })
347
- }
348
- else if(modalName == 'amazon-settings') {
349
- jQuery('#sg-modal').on('hidden.bs.modal', function () {
350
- if(sgBackup.isAmazonConnected != true) {
351
- jQuery('input[data-storage=AMAZON]').bootstrapSwitch('state', false);
352
- }
353
- });
354
- jQuery("#bucketType").on("change", function(){
355
- jQuery("#bucketType option").each(function()
356
- {
357
- var name = jQuery(this).val();
358
- jQuery(".form-group-"+name).css("display","none");
359
- // Add $(this).val() to your list
360
- });
361
- var selected = jQuery("#bucketType").val();
362
- jQuery(".form-group-"+selected).css("display","block");
363
- })
364
- }
365
- else if(modalName == 'manual-review'){
366
- var action = 'setReviewPopupState';
367
- jQuery('#sgLeaveReview').click(function(){
368
- var reviewUrl = jQuery(this).attr('data-review-url');
369
- //Never show again
370
- var reviewState = 2;
371
- var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
372
- ajaxHandler.run();
373
- window.open(reviewUrl);
374
- });
375
-
376
- jQuery('#sgDontAskAgain').click(function(){
377
- //Never show again
378
- var reviewState = 2;
379
- var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
380
- ajaxHandler.run();
381
- });
382
-
383
- jQuery('#sgAskLater').click(function(){
384
- var reviewState = 0;
385
- var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
386
- ajaxHandler.run();
387
- });
388
- }
389
- else if(modalName == 'create-schedule') {
390
- sgBackup.initScheduleCreation();
391
- }
392
- };
393
-
394
- sgBackup.isAnyOpenModal = function(){
395
- return jQuery('#sg-modal').length;
396
- };
397
-
398
- sgBackup.alertGenerator = function(content, alertClass){
399
- var sgalert = '';
400
- sgalert+='<div class="alert alert-dismissible '+alertClass+'">';
401
- sgalert+='<button type="button" class="close" data-dismiss="alert">×</button>';
402
- if(jQuery.isArray(content)){
403
- jQuery.each(content, function(index, value) {
404
- sgalert+=value+'<br/>';
405
- });
406
- }
407
- else if(content != ''){
408
- sgalert+=content.replace('[','').replace(']','').replace('"','');
409
- }
410
- sgalert+='</div>';
411
- return sgalert;
412
- };
413
-
414
- sgBackup.scrollToElement = function(id){
415
- if(jQuery(id).position()){
416
- if(jQuery(id).position().top < jQuery(window).scrollTop()){
417
- //scroll up
418
- jQuery('html,body').animate({scrollTop:jQuery(id).position().top}, 1000);
419
- }
420
- else if(jQuery(id).position().top + jQuery(id).height() > jQuery(window).scrollTop() + (window.innerHeight || document.documentElement.clientHeight)){
421
- //scroll down
422
- jQuery('html,body').animate({scrollTop:jQuery(id).position().top - (window.innerHeight || document.documentElement.clientHeight) + jQuery(id).height() + 15}, 1000);
423
- }
424
- }
425
- };
426
-
427
- sgBackup.showAjaxSpinner = function(appendToElement){
428
- if(typeof appendToElement == 'undefined'){
429
- appendToElement = '#sg-wrapper';
430
- }
431
- jQuery('<div class="sg-spinner"></div>').appendTo(appendToElement);
432
- };
433
-
434
- sgBackup.hideAjaxSpinner = function(){
435
- jQuery('.sg-spinner').remove();
436
- };
437
-
438
- sgBackup.showReviewModal = function(){
439
- if(typeof sgShowReview != 'undefined') {
440
- jQuery('#sg-review').trigger("click");
441
- }
442
- };
443
-
444
- sgBackup.initTablePagination = function(pageName){
445
- var callBack = pageName+'';
446
- jQuery.fn.sgTablePagination = function(opts){
447
- var jQuerythis = this,
448
- defaults = {
449
- perPage: 7,
450
- showPrevNext: false,
451
- hidePageNumbers: false,
452
- pagerSelector: '.'+pageName+' .pagination'
453
- },
454
- settings = jQuery.extend(defaults, opts);
455
-
456
- var listElement = jQuerythis.children('tbody');
457
- var perPage = settings.perPage;
458
- var children = listElement.children();
459
- var pager = jQuery('.'+pageName+'.pager');
460
-
461
- if (typeof settings.childSelector!="undefined") {
462
- children = listElement.find(settings.childSelector);
463
- }
464
-
465
- if (typeof settings.pagerSelector!="undefined") {
466
- pager = jQuery(settings.pagerSelector);
467
- }
468
-
469
- var numItems = children.length;
470
- var numPages = Math.ceil(numItems/perPage);
471
-
472
- pager.data("curr",0);
473
-
474
- if (settings.showPrevNext){
475
- jQuery('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
476
- }
477
-
478
- var curr = 0;
479
- while(numPages > curr && (settings.hidePageNumbers==false)){
480
- jQuery('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
481
- curr++;
482
- }
483
-
484
- if(curr<=1){
485
- jQuery(settings.pagerSelector).parent('div').hide();
486
- jQuery('.'+pageName+'.page_link').hide();
487
- }
488
-
489
- if (settings.showPrevNext){
490
- jQuery('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
491
- }
492
-
493
- pager.find('.page_link:first').addClass('active');
494
- pager.find('.prev_link').hide();
495
- if (numPages<=1) {
496
- pager.find('.next_link').hide();
497
- }
498
- pager.children().eq(1).addClass("active");
499
-
500
- children.hide();
501
- children.slice(0, perPage).show();
502
-
503
- pager.find('li .page_link').click(function(){
504
- var clickedPage = jQuery(this).html().valueOf()-1;
505
- goTo(clickedPage,perPage);
506
- return false;
507
- });
508
- pager.find('li .prev_link').click(function(){
509
- previous();
510
- return false;
511
- });
512
- pager.find('li .next_link').click(function(){
513
- next();
514
- return false;
515
- });
516
-
517
- function previous(){
518
- var goToPage = parseInt(pager.data("curr")) - 1;
519
- goTo(goToPage);
520
- }
521
-
522
- function next(){
523
- goToPage = parseInt(pager.data("curr")) + 1;
524
- goTo(goToPage);
525
- }
526
-
527
- function goTo(page){
528
- var startAt = page * perPage,
529
- endOn = startAt + perPage;
530
-
531
- children.css('display','none').slice(startAt, endOn).show();
532
-
533
- if (page>=1) {
534
- pager.find('.prev_link').show();
535
- }
536
- else {
537
- pager.find('.prev_link').hide();
538
- }
539
-
540
- if (page<(numPages-1)) {
541
- pager.find('.next_link').show();
542
- }
543
- else {
544
- pager.find('.next_link').hide();
545
- }
546
-
547
- pager.data("curr",page);
548
- pager.children().removeClass("active");
549
- pager.children().eq(page+1).addClass("active");
550
-
551
- }
552
- };
553
- jQuery('table.paginated.'+pageName).sgTablePagination({pagerSelector:'.'+pageName+' .pagination',showPrevNext:true,hidePageNumbers:false,perPage:7});
554
- };
555
-
556
- sgBackup.logout = function()
557
- {
558
- var ajaxHandler = new sgRequestHandler('logout', {token: BG_BACKUP_STRINGS.nonce});
559
- ajaxHandler.callback = function(response){
560
- location.reload();
561
- };
562
- ajaxHandler.run();
563
- };
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sgBackup = {};
2
+ sgBackup.isModalOpen = false;
3
+ SG_CURRENT_ACTIVE_AJAX = '';
4
+ SG_NOTICE_EXECUTION_TIMEOUT = 'timeout_error';
5
+ SG_NOTICE_EXECUTION_FREE_TIMEOUT = 'timeout_free_error';
6
+ SG_NOTICE_MIGRATION_ERROR = 'migration_error';
7
+ SG_NOTICE_NOT_WRITABLE_ERROR = 'restore_notwritable_error';
8
+
9
+ jQuery(window).on('load', function() {
10
+ if (jQuery('.sg-active-action-id').length == 0) {
11
+ sgBackup.showReviewModal();
12
+ }
13
+ sgBackup.changeMainUrl();
14
+ });
15
+
16
+ jQuery(document).ready( function() {
17
+ jQuery('span[data-toggle=tooltip]').tooltip();
18
+
19
+ sgBackup.init();
20
+
21
+ jQuery('.sg-badge-warning').on('click', function () {
22
+ var url = jQuery(this).attr('target-url');
23
+ if (url) {
24
+ window.open(url, '_blank');
25
+ }
26
+ });
27
+
28
+ jQuery("#rateYo").rateYo({
29
+ rating: 5,
30
+ fullStar: true,
31
+ spacing: "3px",
32
+ starWidth: "16px",
33
+ starHeight: "16px",
34
+ rating: 4.5,
35
+ ratedFill: "#ffffff"
36
+ });
37
+
38
+ if (typeof SG_AJAX_REQUEST_FREQUENCY === 'undefined'){
39
+ SG_AJAX_REQUEST_FREQUENCY = 2000;
40
+ }
41
+
42
+ sgBackup.hideAjaxSpinner();
43
+ var notice = "";
44
+ jQuery('.notice-dismiss').on('click', function() {
45
+ if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_EXECUTION_TIMEOUT) {
46
+ notice = SG_NOTICE_EXECUTION_TIMEOUT;
47
+ }
48
+ else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_EXECUTION_FREE_TIMEOUT) {
49
+ notice = SG_NOTICE_EXECUTION_TIMEOUT;
50
+ }
51
+ else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_MIGRATION_ERROR) {
52
+ notice = SG_NOTICE_MIGRATION_ERROR;
53
+ }
54
+ else if (jQuery(this).parent().attr('data-notice-id') == SG_NOTICE_NOT_WRITABLE_ERROR) {
55
+ notice = SG_NOTICE_NOT_WRITABLE_ERROR
56
+ }
57
+ var sgNoticeClosedHandler = new sgRequestHandler('hideNotice', {notice: notice, token: BG_BACKUP_STRINGS.nonce});
58
+ sgNoticeClosedHandler.run();
59
+ });
60
+
61
+ //send awake requests only if there is an active action
62
+ if (jQuery('.sg-active-action-id').length>0) {
63
+ setInterval(sgBackup.awake, SG_AJAX_REQUEST_FREQUENCY);
64
+ }
65
+ });
66
+
67
+ sgBackup.awake = function(){
68
+ var awakeAjaxHandler = new sgRequestHandler('awake', {token: BG_BACKUP_STRINGS.nonce});
69
+ awakeAjaxHandler.run();
70
+ }
71
+
72
+ //SG init
73
+ sgBackup.init = function(){
74
+ sgBackup.initModals();
75
+ sgBackup.downloadButton();
76
+ sgBackup.navMenu();
77
+ sgBackup.sendUsageDataStatus();
78
+ };
79
+
80
+ sgBackup.sendUsageDataStatus = function () {
81
+ var checkbox = jQuery('.backup-send-usage-data-status');
82
+
83
+ if (!checkbox.length) {
84
+ return false;
85
+ }
86
+
87
+ checkbox.bind('switchChange.bootstrapSwitch', function () {
88
+ var currentStatus = jQuery(this).is(':checked');
89
+ var action = 'send_usage_status';
90
+ jQuery(this).prop('disabled', true);
91
+ var ajaxHandler = new sgRequestHandler(action, {currentStatus: currentStatus, token: BG_BACKUP_STRINGS.nonce});
92
+ ajaxHandler.callback = function(data, error) {
93
+ jQuery(this).prop('disabled', false);
94
+ }
95
+
96
+ ajaxHandler.run();
97
+ });
98
+ };
99
+
100
+ sgBackup.navMenu = function () {
101
+ var navMenu = jQuery('.sg-backup-sidebar-nav a');
102
+
103
+ if (!navMenu.length) {
104
+ return false;
105
+ }
106
+
107
+ navMenu.unbind('click').bind('click', function (event) {
108
+ event.preventDefault();
109
+ sgBackup.init();
110
+
111
+ var currentUrl = jQuery(this).attr('href');
112
+ var openContent = jQuery(this).data('open-content');
113
+
114
+ if (typeof openContent != 'undefined' && openContent == 0) {
115
+ window.open(currentUrl);
116
+ return true;
117
+ }
118
+ jQuery('.sg-backup-page-content').addClass('sg-visibility-hidden');
119
+ jQuery('.sg-backup-sidebar-nav li').removeClass('active');
120
+
121
+ var currentKey = jQuery(this).data('page-key');
122
+ var currentPageContent = jQuery('#sg-backup-page-content-'+currentKey);
123
+
124
+ if (!currentPageContent.length) {
125
+ return false;
126
+ }
127
+ jQuery(this).parent().addClass('active');
128
+ currentPageContent.removeClass('sg-visibility-hidden');
129
+ });
130
+ };
131
+
132
+ sgBackup.downloadButton = function() {
133
+ var downloadButtons = jQuery('.sg-bg-download-button');
134
+
135
+ if (!downloadButtons.length) {
136
+ return false;
137
+ }
138
+ var isOPen = false;
139
+ jQuery(window).bind('click', function () {
140
+ if (isOPen) {
141
+ jQuery('.sg-backup-table .dropdown-menu').removeClass('sg-bg-show');
142
+ isOPen = false;
143
+ }
144
+ });
145
+
146
+ downloadButtons.bind('click', function () {
147
+ var currentButton = jQuery(this);
148
+
149
+ if (!currentButton.length) {
150
+ return false;
151
+ }
152
+ setTimeout(function () {
153
+ currentButton.next().addClass('sg-bg-show');
154
+ isOPen = true;
155
+ }, 0);
156
+ });
157
+ };
158
+
159
+ //SG Modal popup logic
160
+ sgBackup.initModals = function(){
161
+
162
+ jQuery('[data-toggle="modal"][href], [data-toggle="modal"][data-remote]').off('click').on('click', function(e) {
163
+ var param = '';
164
+ if (typeof jQuery(this).attr('data-sgbp-params') !== 'undefined'){
165
+ param = jQuery(this).attr('data-sgbp-params');
166
+ }
167
+
168
+ e.preventDefault();
169
+ var btn = jQuery(this),
170
+ url = btn.attr('data-remote'),
171
+ modalName = btn.attr('data-modal-name'),
172
+ backupType = btn.attr('sg-data-backup-type'),
173
+ modal = jQuery('#sg-modal');
174
+ if( modal.length == 0 ) {
175
+ modal = jQuery('' +
176
+ '<div class="modal fade" id="sg-modal" tabindex="-1" role="dialog" aria-hidden="true"></div>' +
177
+ '');
178
+ body.append(modal);
179
+ }
180
+ sgBackup.showAjaxSpinner('#sg-content-wrapper');
181
+ if (typeof sgBackup.disableUi == 'function') {
182
+ sgBackup.disableUi();
183
+ }
184
+
185
+ var ajaxHandler = new sgRequestHandler(url, {
186
+ param: param,
187
+ backupType: backupType,
188
+ token: BG_BACKUP_STRINGS.nonce
189
+ });
190
+
191
+ if (modalName == 'backup-guard-details') {
192
+ modal.modal({
193
+ backdrop: 'static',
194
+ keyboard: false
195
+ });
196
+ }
197
+
198
+ ajaxHandler.type = 'GET';
199
+ ajaxHandler.dataType = 'html';
200
+ ajaxHandler.callback = function(data, error) {
201
+ sgBackup.hideAjaxSpinner();
202
+ if (typeof sgBackup.enableUi == 'function') {
203
+ sgBackup.enableUi();
204
+ }
205
+ if (error===false) {
206
+ jQuery('#sg-modal').append(data);
207
+ }
208
+ modal.on('hide.bs.modal', function() {
209
+ if(SG_CURRENT_ACTIVE_AJAX != '') {
210
+ if (!confirm(BG_MAIN_STRINGS.confirmCancel)) {
211
+ return false;
212
+ }
213
+ SG_CURRENT_ACTIVE_AJAX.abort();
214
+ SG_CURRENT_ACTIVE_AJAX = '';
215
+ }
216
+ });
217
+ modal.one('hidden.bs.modal', function() {
218
+ modal.html('');
219
+ }).modal('show');
220
+ sgBackup.didOpenModal(modalName, param);
221
+ };
222
+
223
+ if (modalName == 'ftp-settings' || modalName == 'amazon-settings') {
224
+ var storage = 'FTP';
225
+ if (modalName == 'amazon-settings') {
226
+ storage = 'AMAZON';
227
+ }
228
+ error = false;
229
+ var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: storage});
230
+ isFeatureAvailable.callback = function(response) {
231
+ if (typeof response.error !== 'undefined') {
232
+ var alert = sgBackup.alertGenerator(response.error, 'alert-warning');
233
+ jQuery('.sg-cloud-container legend').after(alert);
234
+ that.bootstrapSwitch('state', false);
235
+ sgBackup.hideAjaxSpinner();
236
+ }
237
+ else {
238
+ ajaxHandler.run();
239
+ }
240
+ }
241
+
242
+ isFeatureAvailable.run();
243
+ }
244
+ else {
245
+ ajaxHandler.run();
246
+ }
247
+ });
248
+ };
249
+
250
+ sgBackup.toggleSftpSettings = function() {
251
+ jQuery('#ftpPort').val('22');
252
+ jQuery('#sg-sftp-key-file-block').show();
253
+ jQuery('#sg-browse-key-file-block').hide();
254
+
255
+ if (jQuery('#sg-connect-with-key-file').is(':checked') && connectioType=='sftp') {
256
+ jQuery('#sg-browse-key-file-block').show();
257
+ }
258
+ }
259
+
260
+ sgBackup.toggleFtpSettings = function() {
261
+ jQuery('#ftpPort').val('21');
262
+ jQuery('#sg-sftp-key-file-block').hide();
263
+ }
264
+
265
+ // Show/hide some fields that are needed/not needed for ftp/sftp
266
+ sgBackup.toggleNeededFtpFields = function(connectioType) {
267
+ if(connectioType == 'sftp') {
268
+ sgBackup.toggleSftpSettings();
269
+
270
+ }
271
+ else if(connectioType == 'ftp') {
272
+ sgBackup.toggleFtpSettings();
273
+ }
274
+ }
275
+
276
+ sgBackup.didOpenModal = function(modalName, param){
277
+ if(modalName == 'manual-backup' || modalName == 'manual-restore'){
278
+ sgBackup.initManulBackupRadioInputs();
279
+ sgBackup.initManualBackupTooltips();
280
+ jQuery('#fileSystemTreeContainer').jstree({ 'core' : {
281
+
282
+ 'data' : {
283
+ 'url' : function (node) {
284
+ return getAjaxUrl();
285
+ },
286
+ 'data' : function (node) {
287
+ var path = node.id;
288
+ return { action:"backup_guard_getBackupContent", path:path, backupName:param, token: BG_BACKUP_STRINGS.nonce };
289
+ }
290
+ }
291
+ },
292
+ "plugins" : ["wholerow", "checkbox", "types"],
293
+ "checkbox" : {
294
+ "keep_selected_style" : false
295
+ },
296
+ "types": {
297
+ "file": {
298
+ "icon": "bg-file-icon"
299
+ },
300
+ "folder": {
301
+ "icon": "bg-folder-icon"
302
+ },
303
+ "default":{
304
+ "icon": "bg-no-icon"
305
+ }
306
+ }
307
+ });
308
+ }
309
+ else if(modalName == 'import'){
310
+ sgBackup.initImportTooltips();
311
+ jQuery('#modal-import-2').hide();
312
+ jQuery('#modal-import-3').hide();
313
+ jQuery('#switch-modal-import-pages-back').hide();
314
+ jQuery('#uploadSgbpFile').hide();
315
+ if(jQuery('#modal-import-1').length == 0) {
316
+ sgBackup.toggleDownloadFromPCPage();
317
+ }
318
+ sgBackup.initFileUpload();
319
+ }
320
+ else if(modalName == 'ftp-settings'){
321
+ connectioType = jQuery('#sg-connection-method').val();
322
+ sgBackup.toggleNeededFtpFields(connectioType);
323
+
324
+ jQuery('#sg-connection-method').on('change', function(){
325
+ connectioType = jQuery(this).val();
326
+ sgBackup.toggleNeededFtpFields(connectioType);
327
+ });
328
+
329
+ jQuery('#sg-connect-with-key-file').on('click', function(){
330
+ if(jQuery(this).is(':checked')) {
331
+ jQuery('#sg-browse-key-file-block').show();
332
+ }
333
+ else {
334
+ jQuery('#sg-browse-key-file-block').hide();
335
+ }
336
+ })
337
+
338
+ sgBackup.initSFTPKeyFileSelection();
339
+
340
+ jQuery('#sg-modal').on('hidden.bs.modal', function () {
341
+ if(sgBackup.isFtpConnected != true) {
342
+ jQuery('input[data-storage=FTP]').bootstrapSwitch('state', false);
343
+ }
344
+ })
345
+ }
346
+ else if(modalName == 'amazon-settings') {
347
+ jQuery('#sg-modal').on('hidden.bs.modal', function () {
348
+ if(sgBackup.isAmazonConnected != true) {
349
+ jQuery('input[data-storage=AMAZON]').bootstrapSwitch('state', false);
350
+ }
351
+ });
352
+ jQuery("#bucketType").on("change", function(){
353
+ jQuery("#bucketType option").each(function()
354
+ {
355
+ var name = jQuery(this).val();
356
+ jQuery(".form-group-"+name).css("display","none");
357
+ // Add $(this).val() to your list
358
+ });
359
+ var selected = jQuery("#bucketType").val();
360
+ jQuery(".form-group-"+selected).css("display","block");
361
+ })
362
+ }
363
+ else if(modalName == 'manual-review'){
364
+ var action = 'setReviewPopupState';
365
+ jQuery('#sgLeaveReview').click(function(){
366
+ var reviewUrl = jQuery(this).attr('data-review-url');
367
+ //Never show again
368
+ var reviewState = 2;
369
+ var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
370
+ ajaxHandler.run();
371
+ window.open(reviewUrl);
372
+ });
373
+
374
+ jQuery('#sgDontAskAgain').click(function(){
375
+ //Never show again
376
+ var reviewState = 2;
377
+ var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
378
+ ajaxHandler.run();
379
+ });
380
+
381
+ jQuery('#sgAskLater').click(function(){
382
+ var reviewState = 0;
383
+ var ajaxHandler = new sgRequestHandler(action, {reviewState: reviewState, token: BG_BACKUP_STRINGS.nonce});
384
+ ajaxHandler.run();
385
+ });
386
+ }
387
+ else if(modalName == 'create-schedule') {
388
+ sgBackup.initScheduleCreation();
389
+ }
390
+ };
391
+
392
+ sgBackup.isAnyOpenModal = function(){
393
+ return jQuery('#sg-modal').length;
394
+ };
395
+
396
+ sgBackup.alertGenerator = function(content, alertClass){
397
+ var sgalert = '';
398
+ sgalert+='<div class="alert alert-dismissible '+alertClass+'">';
399
+ sgalert+='<button type="button" class="close" data-dismiss="alert">×</button>';
400
+ if(jQuery.isArray(content)){
401
+ jQuery.each(content, function(index, value) {
402
+ sgalert+=value+'<br/>';
403
+ });
404
+ }
405
+ else if(content != ''){
406
+ sgalert+=content.replace('[','').replace(']','').replace('"','');
407
+ }
408
+ sgalert+='</div>';
409
+ return sgalert;
410
+ };
411
+
412
+ sgBackup.scrollToElement = function(id){
413
+ if(jQuery(id).position()){
414
+ if(jQuery(id).position().top < jQuery(window).scrollTop()){
415
+ //scroll up
416
+ jQuery('html,body').animate({scrollTop:jQuery(id).position().top}, 1000);
417
+ }
418
+ else if(jQuery(id).position().top + jQuery(id).height() > jQuery(window).scrollTop() + (window.innerHeight || document.documentElement.clientHeight)){
419
+ //scroll down
420
+ jQuery('html,body').animate({scrollTop:jQuery(id).position().top - (window.innerHeight || document.documentElement.clientHeight) + jQuery(id).height() + 15}, 1000);
421
+ }
422
+ }
423
+ };
424
+
425
+ sgBackup.showAjaxSpinner = function(appendToElement){
426
+ if(typeof appendToElement == 'undefined'){
427
+ appendToElement = '#sg-wrapper';
428
+ }
429
+ jQuery('<div class="sg-spinner"></div>').appendTo(appendToElement);
430
+ };
431
+
432
+ sgBackup.hideAjaxSpinner = function(){
433
+ jQuery('.sg-spinner').remove();
434
+ };
435
+ sgBackup.showReviewModal = function(){
436
+ if(typeof sgShowReview != 'undefined') {
437
+ jQuery('#sg-review').trigger("click");
438
+ }
439
+ };
440
+
441
+ sgBackup.initTablePagination = function(pageName){
442
+ var callBack = pageName+'';
443
+ jQuery.fn.sgTablePagination = function(opts){
444
+ var jQuerythis = this,
445
+ defaults = {
446
+ perPage: 7,
447
+ showPrevNext: false,
448
+ hidePageNumbers: false,
449
+ pagerSelector: '.'+pageName+' .pagination'
450
+ },
451
+ settings = jQuery.extend(defaults, opts);
452
+
453
+ var listElement = jQuerythis.children('tbody');
454
+ var perPage = settings.perPage;
455
+ var children = listElement.children();
456
+ var pager = jQuery('.'+pageName+'.pager');
457
+
458
+ if (typeof settings.childSelector!="undefined") {
459
+ children = listElement.find(settings.childSelector);
460
+ }
461
+
462
+ if (typeof settings.pagerSelector!="undefined") {
463
+ pager = jQuery(settings.pagerSelector);
464
+ }
465
+
466
+ var numItems = children.length;
467
+ var numPages = Math.ceil(numItems/perPage);
468
+
469
+ pager.data("curr",0);
470
+
471
+ if (settings.showPrevNext){
472
+ jQuery('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
473
+ }
474
+
475
+ var curr = 0;
476
+ while(numPages > curr && (settings.hidePageNumbers==false)){
477
+ jQuery('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
478
+ curr++;
479
+ }
480
+
481
+ if(curr<=1){
482
+ jQuery(settings.pagerSelector).parent('div').hide();
483
+ jQuery('.'+pageName+'.page_link').hide();
484
+ }
485
+
486
+ if (settings.showPrevNext){
487
+ jQuery('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
488
+ }
489
+
490
+ pager.find('.page_link:first').addClass('active');
491
+ pager.find('.prev_link').hide();
492
+ if (numPages<=1) {
493
+ pager.find('.next_link').hide();
494
+ }
495
+ pager.children().eq(1).addClass("active");
496
+
497
+ children.hide();
498
+ children.slice(0, perPage).show();
499
+
500
+ pager.find('li .page_link').click(function(){
501
+ var clickedPage = jQuery(this).html().valueOf()-1;
502
+ goTo(clickedPage,perPage);
503
+ return false;
504
+ });
505
+ pager.find('li .prev_link').click(function(){
506
+ previous();
507
+ return false;
508
+ });
509
+ pager.find('li .next_link').click(function(){
510
+ next();
511
+ return false;
512
+ });
513
+
514
+ function previous(){
515
+ var goToPage = parseInt(pager.data("curr")) - 1;
516
+ goTo(goToPage);
517
+ }
518
+
519
+ function next(){
520
+ goToPage = parseInt(pager.data("curr")) + 1;
521
+ goTo(goToPage);
522
+ }
523
+
524
+ function goTo(page){
525
+ var startAt = page * perPage,
526
+ endOn = startAt + perPage;
527
+
528
+ children.css('display','none').slice(startAt, endOn).show();
529
+
530
+ if (page>=1) {
531
+ pager.find('.prev_link').show();
532
+ }
533
+ else {
534
+ pager.find('.prev_link').hide();
535
+ }
536
+
537
+ if (page<(numPages-1)) {
538
+ pager.find('.next_link').show();
539
+ }
540
+ else {
541
+ pager.find('.next_link').hide();
542
+ }
543
+
544
+ pager.data("curr",page);
545
+ pager.children().removeClass("active");
546
+ pager.children().eq(page+1).addClass("active");
547
+
548
+ }
549
+ };
550
+ jQuery('table.paginated.'+pageName).sgTablePagination({pagerSelector:'.'+pageName+' .pagination',showPrevNext:true,hidePageNumbers:false,perPage:7});
551
+ };
552
+
553
+ sgBackup.logout = function(){
554
+ var ajaxHandler = new sgRequestHandler('logout', {token: BG_BACKUP_STRINGS.nonce});
555
+ ajaxHandler.callback = function(response){
556
+ location.reload();
557
+ };
558
+ ajaxHandler.run();
559
+ };
560
+
561
+ sgBackup.changeMainUrl = function(){
562
+ jQuery('nav#sg-main-sidebar li').click(function() {
563
+
564
+ let attr = jQuery(this).children('a').attr('data-page-key');
565
+
566
+ if (typeof attr !== typeof undefined && attr !== false) {
567
+
568
+ let queryParams = new URLSearchParams(window.location.search);
569
+
570
+ queryParams.set('page', 'backup_guard_'+attr);
571
+
572
+ history.replaceState(null, null, "?"+queryParams.toString());
573
+ }
574
+ });
575
+ };
public/js/sgbackup.js CHANGED
@@ -1,847 +1,848 @@
1
- SG_DOWNLOAD_PROGRESS = '';
2
- SG_ACTIVE_DOWNLOAD_AJAX = '';
3
- SG_CHECK_ACTION_STATUS_REQUEST_FREQUENCY = 2500;
4
-
5
- SG_STORAGE_FTP = 1;
6
- SG_STORAGE_DROPBOX = 2;
7
- SG_STORAGE_GOOGLE_DRIVE = 3;
8
- SG_STORAGE_AMAZON = 4;
9
- SG_STORAGE_ONE_DRIVE = 5;
10
- SG_STORAGE_BACKUP_GUARD = 6;
11
-
12
- jQuery(document).on('change', '.btn-file :file', function() {
13
- var input = jQuery(this),
14
- numFiles = input.get(0).files ? input.get(0).files.length : 1,
15
- label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
16
- input.trigger('fileselect', [numFiles, label]);
17
- });
18
-
19
- jQuery(document).ready( function() {
20
- sgBackup.initTablePagination('sg-backups');
21
- sgBackup.initActiveAction();
22
- sgBackup.initBackupDeletion();
23
- sgBackup.toggleMultiDeleteButton();
24
- sgBackup.closeFreeBaner();
25
-
26
- jQuery('span[data-toggle=tooltip]').tooltip();
27
-
28
- jQuery('#sg-checkbox-select-all').on('change', function(){
29
- var checkAll = jQuery('#sg-checkbox-select-all');
30
- jQuery('tbody input[type="checkbox"]:not(:disabled):visible').prop('checked', checkAll.prop('checked'));
31
- sgBackup.toggleMultiDeleteButton();
32
- });
33
-
34
- jQuery('#sg-delete-multi-backups').on('click', function(){
35
- if (!confirm(BG_BACKUP_STRINGS_DEACTIVATE.areYouSure)) {
36
- return false;
37
- }
38
- var backups = jQuery('tbody input[type="checkbox"]:checked');
39
- var backupNames = [];
40
- backups.each(function(i){
41
- backupNames[i] = jQuery(this).val();
42
- });
43
-
44
- if (backupNames.length) {
45
- sgBackup.deleteMultiBackups(backupNames);
46
- }
47
- });
48
-
49
- jQuery('tbody input[type="checkbox"]').on('change', function(){
50
- var numberOfBackups = jQuery('tbody input[type="checkbox"]').length;
51
- var numberOfChoosenBackups = sgBackup.getSelectedBackupsNumber();
52
- var isCheked = jQuery(this).is(':checked');
53
- sgBackup.toggleMultiDeleteButton();
54
-
55
- if(!isCheked) {
56
- jQuery('#sg-checkbox-select-all').prop('checked', false);
57
- }
58
- else {
59
- if (numberOfBackups == numberOfChoosenBackups) {
60
- jQuery('#sg-checkbox-select-all').prop('checked', true);
61
- }
62
- }
63
- });
64
-
65
- var surveyClose = function(e) {
66
- e.preventDefault();
67
-
68
- jQuery('.bg-verify-user-info-container').slideUp();
69
- jQuery('.bg-verify-user-info-overlay').hide();
70
-
71
- var ajaxHandler = new sgRequestHandler('setUserInfoVerificationPopupState', {token: BG_BACKUP_STRINGS.nonce});
72
- ajaxHandler.run();
73
- };
74
-
75
- jQuery('.bg-verify-user-info-overlay').bind('click', surveyClose);
76
-
77
-
78
- jQuery('.bg-verify-user-info-cancel').click(surveyClose);
79
-
80
- jQuery('#bg-verify-user-prioraty').on('change', function () {
81
- if (jQuery(this).val() == "other") {
82
- jQuery('#bg-verify-user-priorati-custom').show();
83
- }
84
- else {
85
- jQuery('#bg-verify-user-priorati-custom').hide();
86
- }
87
- });
88
-
89
- jQuery('.bg-verify-user-info-verify-email').click(function(e) {
90
- e.preventDefault();
91
-
92
- var email = jQuery('#bg-verify-user-info-email').val();
93
- var fname = jQuery('#bg-verify-user-info-name').val();
94
- var lname = jQuery('#bg-verify-user-info-last-name').val();
95
- var priority = jQuery('#bg-verify-user-prioraty').val();
96
-
97
- var sendData = true;
98
- jQuery('.bg-verify-user-info-error-message').hide();
99
-
100
- if (priority == "other") {
101
- priority = jQuery('#bg-verify-user-priorati-custom').val();
102
-
103
- if (!priority) {
104
- jQuery('#bg-verify-user-info-priority-custom-error').show()
105
- sendData = false;
106
- }
107
- }
108
- else if (!priority) {
109
- jQuery('#bg-verify-user-info-priority-error').show()
110
- sendData = false;
111
- }
112
-
113
- if(fname == '') {
114
- jQuery('#bg-verify-user-info-name-error').show();
115
- sendData = false;
116
- }
117
-
118
- if(lname == '') {
119
- jQuery('#bg-verify-user-info-last-name-error').show();
120
- sendData = false;
121
- }
122
-
123
- if (!sgBackup.isValidEmailAddress(email)) {
124
- jQuery('#bg-verify-user-info-email-error').show();
125
- sendData = false;
126
- }
127
-
128
- if(sendData) {
129
- jQuery('.bg-verify-user-info-container').slideUp();
130
- jQuery('.bg-verify-user-info-overlay').hide();
131
- var currentStatus = jQuery('.backup-send-usage-data-status').is(':checked');
132
-
133
- var ajaxHandler = new sgRequestHandler('storeSubscriberInfo', {
134
- email: email,
135
- fname: fname,
136
- lname: lname,
137
- priority: priority,
138
- currentStatus: currentStatus,
139
- token: BG_BACKUP_STRINGS.nonce
140
- });
141
-
142
- ajaxHandler.run();
143
- }
144
- });
145
- });
146
-
147
- sgBackup.isValidEmailAddress = function(emailAddress) {
148
- var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,10}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
149
- return pattern.test(emailAddress);
150
- };
151
-
152
- sgBackup.getSelectedBackupsNumber = function() {
153
- return jQuery('tbody input[type="checkbox"]:checked').length
154
- };
155
-
156
- sgBackup.toggleMultiDeleteButton = function() {
157
- var numberOfChoosenBackups = sgBackup.getSelectedBackupsNumber();
158
- var target = jQuery('#sg-delete-multi-backups');
159
- if (numberOfChoosenBackups > 0) {
160
- target.removeAttr('disabled');
161
- }
162
- else {
163
- target.attr('disabled','disabled');
164
- }
165
- };
166
-
167
- sgBackup.closeFreeBaner = function() {
168
- jQuery('.sg-close-free-banner').bind('click', function () {
169
- var ajaxHandler = new sgRequestHandler('closeFreeBanner', {
170
- token: BG_BACKUP_STRINGS.nonce
171
- });
172
- ajaxHandler.callback = function(response, error) {
173
- jQuery('#sg-banner').remove();
174
- };
175
- ajaxHandler.run();
176
- });
177
- };
178
-
179
- sgBackup.deleteMultiBackups = function(backupNames){
180
- var ajaxHandler = new sgRequestHandler('deleteBackup', {backupName: backupNames, token: BG_BACKUP_STRINGS.nonce});
181
- ajaxHandler.callback = function (response) {
182
- location.reload();
183
- };
184
- ajaxHandler.run();
185
- };
186
-
187
- //SGManual Backup AJAX callback
188
- sgBackup.manualBackup = function(checkedStatus){
189
- var error = [];
190
- //Validation
191
- jQuery('.alert').remove();
192
- if(jQuery('input[type=radio][name=backupType]:checked').val() == 2) {
193
- if(jQuery('.sg-custom-option:checked').length <= 0) {
194
- error.push(BG_BACKUP_STRINGS.invalidBackupOption);
195
- }
196
- //Check if any file is selected
197
- if(jQuery('input[type=checkbox][name=backupFiles]:checked').length > 0) {
198
- if(jQuery('.sg-custom-backup-files input:checkbox:checked').length <= 0) {
199
- error.push(BG_BACKUP_STRINGS.invalidDirectorySelected);
200
- }
201
- }
202
- }
203
- //Check if any cloud is selected
204
- if(jQuery('input[type=checkbox][name=backupCloud]:checked').length > 0) {
205
- if (jQuery('.sg-custom-backup-cloud input:checkbox:checked').length <= 0) {
206
- error.push(BG_BACKUP_STRINGS.invalidCloud);
207
- }
208
- }
209
- //If any error show it and abort ajax
210
- if(error.length){
211
- var sgAlert = sgBackup.alertGenerator(error, 'alert-danger');
212
- jQuery('#sg-modal .modal-header').prepend(sgAlert);
213
- return false;
214
- }
215
-
216
- if (!checkedStatus) {
217
- sgBackup.checkBackupCreation();
218
- }
219
-
220
- //Before all disable buttons...
221
- jQuery('.alert').remove();
222
- jQuery('.modal-footer .btn-primary').attr('disabled','disabled');
223
- jQuery('.modal-footer .btn-primary').html(BG_BACKUP_STRINGS.backupInProgress);
224
-
225
- //Reset Status
226
- var backupName = jQuery("#sg-custom-backup-name").val();
227
- var resetStatusHandler = new sgRequestHandler('resetStatus', {backupName: backupName, token: BG_BACKUP_STRINGS.nonce });
228
- resetStatusHandler.callback = function(response, error){
229
- var manualBackupForm = jQuery('#manualBackup');
230
- var manualBackupHandler = new sgRequestHandler('manualBackup', manualBackupForm.serialize()+'&token='+BG_BACKUP_STRINGS.nonce);
231
- manualBackupHandler.dataIsObject = false;
232
- //If error
233
- if(typeof response.success === 'undefined') {
234
- var sgAlert = sgBackup.alertGenerator(response, 'alert-danger');
235
- jQuery('#sg-modal .modal-header').prepend(sgAlert);
236
-
237
- if (response === 0 || response === false || response === '0' || response === 'false') {
238
- response = BG_BACKUP_STRINGS.errorMessage;
239
- }
240
- sgBackup.restManualBackupModal();
241
- return false;
242
- }
243
- if (checkedStatus) {
244
- sgBackup.hideAndReload();
245
- }
246
- manualBackupHandler.run();
247
- };
248
- resetStatusHandler.run();
249
- };
250
-
251
- sgBackup.hideAndReload = function () {
252
- jQuery('#sg-modal').modal('hide');
253
- location.reload();
254
- };
255
-
256
- sgBackup.restManualBackupModal = function() {
257
- jQuery('.modal-footer .btn-primary').removeAttr('disabled');
258
- jQuery('.modal-footer .btn-primary').html('Backup');
259
- };
260
-
261
- sgBackup.cancelDonwload = function(name) {
262
- var cancelDonwloadHandler = new sgRequestHandler('cancelDownload', {name: name, token: BG_BACKUP_STRINGS.nonce});
263
- cancelDonwloadHandler.callback = function(response){
264
- sgBackup.hideAjaxSpinner();
265
- location.reload();
266
- };
267
- cancelDonwloadHandler.run();
268
- };
269
-
270
- sgBackup.listStorage = function(importFrom) {
271
- var listStorage = new sgRequestHandler('listStorage', {storage: importFrom, token: BG_BACKUP_STRINGS.nonce});
272
- sgBackup.showAjaxSpinner('#sg-modal-inport-from');
273
- jQuery('#sg-archive-list-table tbody').empty();
274
-
275
- jQuery('#sg-modal').off('hide.bs.modal').on('hide.bs.modal', function(e){
276
-
277
- if (SG_ACTIVE_DOWNLOAD_AJAX) {
278
- if (!confirm(BG_BACKUP_STRINGS.confirm)) {
279
- e.preventDefault();
280
- return false;
281
- }
282
- var target = jQuery('input[name="select-archive-to-download"]:checked');
283
- var name = target.attr('file-name');
284
-
285
- sgBackup.cancelDonwload(name);
286
- }
287
- });
288
-
289
- listStorage.callback = function(response, error) {
290
- var cloudName = '';
291
- var cloudId = parseInt(importFrom, 10);
292
-
293
- switch (cloudId) {
294
- case SG_STORAGE_AMAZON:
295
- cloudName = "S3";
296
- break;
297
- case SG_STORAGE_DROPBOX:
298
- cloudName = "Dropbox";
299
- break;
300
- case SG_STORAGE_GOOGLE_DRIVE:
301
- cloudName = "Google Drive";
302
- break;
303
- case SG_STORAGE_FTP:
304
- cloudName = "FTP";
305
- break;
306
- case SG_STORAGE_ONE_DRIVE:
307
- cloudName = "OneDrive";
308
- break;
309
- case SG_STORAGE_BACKUP_GUARD:
310
- cloudName = "BackupGuard";
311
- break;
312
- default:
313
- cloudName = '';
314
- }
315
-
316
- jQuery('.modal-title').html('Import from '+cloudName);
317
-
318
- sgBackup.hideAjaxSpinner();
319
- var content = '';
320
- if ((typeof response.error != "undefined") || response.length == 0 || response === undefined) {
321
- content = '<tr><td colspan="4">'+BG_BACKUP_STRINGS.noBackupsAvailable+'</td></tr>';
322
- }
323
- else {
324
- jQuery.each(response, function( key, value ) {
325
-
326
- var backupId = 0;
327
-
328
- if (typeof value.id != 'undefined') {
329
- backupId = value.id;
330
- value.path = value.name;
331
- }
332
-
333
- content += '<tr>';
334
- content += '<td class="file-select-radio"><input type="radio" file-name="'+value.name+'" name="select-archive-to-download" size="'+value.size+'" backup-id="'+value.id+'" storage="'+importFrom+'" value="'+value.path+'"></td>';
335
- content += '<td>'+value.name+'</td>';
336
- content += '<td>'+sgBackup.convertBytesToMegabytes(value.size)+'</td>';
337
- content += '<td>'+value.date+'</td>';
338
- content += '</tr>';
339
- });
340
- }
341
-
342
- jQuery('#sg-archive-list-table tbody').append(content);
343
- sgBackup.toggleDownloadFromCloudPage();
344
- };
345
-
346
- listStorage.run();
347
- };
348
-
349
-
350
- sgBackup.convertBytesToMegabytes = function ($bytes) {
351
- return ($bytes/(1024*1024)).toFixed(2);
352
- };
353
-
354
- //Init file upload
355
- sgBackup.initFileUpload = function(){
356
- sgBackup.downloadFromPC();
357
-
358
- jQuery('#uploadSgbpFile').click(function(){
359
- if(jQuery('#modal-import-3').is(":visible")) {
360
- var target = jQuery('input[name="select-archive-to-download"]:checked');
361
- var path = target.val();
362
- var name = target.attr('file-name');
363
- var storage = target.attr('storage');
364
- var size = target.attr('size');
365
- var backupId = target.attr('backup-id');
366
- sgBackup.downloadFromCloud(path, name, storage, size, backupId);
367
- }
368
- });
369
- };
370
-
371
- sgBackup.nextPage = function(){
372
- var importFrom = jQuery('input[name="storage-radio"]:checked').val();
373
- jQuery('.alert').remove();
374
-
375
- if (!importFrom) {
376
- var alert = sgBackup.alertGenerator(BG_BACKUP_STRINGS.invalidImportOption, 'alert-danger');
377
- jQuery('#sg-modal .modal-header').prepend(alert);
378
- }
379
- else {
380
- if (importFrom == 'local-pc') {
381
- sgBackup.toggleDownloadFromPCPage();
382
- }
383
- else {
384
- var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: "DOWNLOAD_FROM_CLOUD"});
385
- isFeatureAvailable.callback = function(response) {
386
- if (typeof response.success !== 'undefined') {
387
- sgBackup.listStorage(importFrom);
388
- }
389
- else {
390
- var alert = sgBackup.alertGenerator(response.error, 'alert-danger');
391
- jQuery('#sg-modal .modal-header').prepend(alert);
392
- }
393
- };
394
-
395
- isFeatureAvailable.run();
396
- }
397
- }
398
- };
399
-
400
- sgBackup.previousPage = function(){
401
- if(jQuery('#modal-import-2').is(":visible")){
402
- jQuery('#modal-import-2').hide();
403
- }
404
- else{
405
- jQuery('#modal-import-3').hide();
406
- }
407
-
408
- sgBackup.toggleNavigationButtons();
409
-
410
- jQuery('#modal-import-1').show();
411
- jQuery('#uploadSgbpFile').hide();
412
-
413
- jQuery('.modal-title').html('Import from');
414
- };
415
-
416
- sgBackup.toggleNavigationButtons = function(){
417
- jQuery('#switch-modal-import-pages-next').toggle();
418
- jQuery('#switch-modal-import-pages-back').toggle();
419
- };
420
-
421
- sgBackup.toggleDownloadFromPCPage = function(){
422
- sgBackup.toggleNavigationButtons();
423
- jQuery('#modal-import-1').toggle();
424
- jQuery('#modal-import-2').toggle();
425
- jQuery('#uploadSgbpFile').toggle();
426
- };
427
-
428
- sgBackup.toggleDownloadFromCloudPage = function(){
429
- sgBackup.toggleNavigationButtons();
430
- jQuery('#modal-import-1').toggle();
431
- jQuery('#modal-import-3').toggle();
432
- jQuery('#uploadSgbpFile').toggle();
433
- };
434
-
435
- sgBackup.downloadFromCloud = function (path, name, storage, size) {
436
- sgBackup.showAjaxSpinner('.modal-dialog');
437
- var error = [];
438
- if (!path) {
439
- error.push(BG_BACKUP_STRINGS.invalidDownloadFile);
440
- }
441
-
442
- jQuery('.alert').remove();
443
-
444
- if (error.length) {
445
- sgBackup.hideAjaxSpinner();
446
- var sgAlert = sgBackup.alertGenerator(error, 'alert-danger');
447
- jQuery('#sg-modal .modal-header').prepend(sgAlert);
448
- return false;
449
- }
450
-
451
- var downloadFromCloudHandler = new sgRequestHandler('downloadFromCloud', {
452
- path: path,
453
- storage: storage,
454
- size: size,
455
- token: BG_BACKUP_STRINGS.nonce
456
- });
457
-
458
- jQuery('#switch-modal-import-pages-back').hide();
459
- jQuery('#uploadSgbpFile').attr('disabled', 'disabled');
460
-
461
- downloadFromCloudHandler.callback = function (response, error){
462
- sgBackup.hideAjaxSpinner();
463
- jQuery('.alert').remove();
464
-
465
- clearTimeout(SG_DOWNLOAD_PROGRESS);
466
-
467
- if (typeof response.success !== 'undefined') {
468
- location.reload();
469
- }
470
- else {
471
- jQuery('#uploadSgbpFile').html(BG_BACKUP_STRINGS.import);
472
-
473
- var sgAlert = sgBackup.alertGenerator(response.error, 'alert-danger');
474
-
475
- jQuery('#uploadSgbpFile').attr('disabled', false);
476
- jQuery('#switch-modal-import-pages-back').toggle();
477
- jQuery('#sg-modal .modal-header').prepend(sgAlert);
478
- SG_ACTIVE_DOWNLOAD_AJAX = false;
479
-
480
- return false;
481
- }
482
- };
483
-
484
- SG_ACTIVE_DOWNLOAD_AJAX = true;
485
- downloadFromCloudHandler.run();
486
- sgBackup.fileDownloadProgress(name, size);
487
- };
488
-
489
- sgBackup.downloadFromPC = function(){
490
- var sgData = null;
491
- jQuery('#sg-modal').off('hide.bs.modal').on('hide.bs.modal', function(e){
492
- if (SG_ACTIVE_DOWNLOAD_AJAX) {
493
- if (!confirm(BG_BACKUP_STRINGS.confirm)) {
494
- e.preventDefault();
495
- return false;
496
- }
497
-
498
- sgData.abort();
499
- sgBackup.cancelDonwload(sgData.files[0].name);
500
- }
501
- });
502
-
503
- jQuery('.sg-backup-upload-input').fileupload({
504
- dataType: 'json',
505
- maxChunkSize: 2000000,
506
- add: function (e, data) {
507
- if (data.originalFiles.length) {
508
- var fileName = data.originalFiles[0].name;
509
- jQuery('#sg-import-file-name').val(fileName);
510
- }
511
- jQuery('#uploadSgbpFile').click(function(){
512
- if(jQuery('#modal-import-2').is(":visible")) {
513
- sgData = data;
514
- SG_ACTIVE_DOWNLOAD_AJAX = true;
515
- jQuery('#uploadSgbpFile').attr('disabled','disabled');
516
- jQuery('#switch-modal-import-pages-back').hide();
517
- jQuery('#uploadSgbpFile').html(BG_BACKUP_STRINGS.importInProgress);
518
- data.submit();
519
- }
520
- });
521
- },
522
- done: function (e, data) {
523
- location.reload();
524
- },
525
- progress: function (e, data) {
526
- var progress = parseInt(data.loaded / data.total * 100, 10);
527
- jQuery('#uploadSgbpFile').html('Importing ('+ Math.round(progress)+'%)');
528
- }
529
- }).on('fileuploadfail', function (e, data) {
530
- var alert = sgBackup.alertGenerator(BG_BACKUP_STRINGS.fileUploadFailed, 'alert-danger');
531
- jQuery('#sg-modal .modal-header').prepend(alert);
532
- });
533
- };
534
-
535
- sgBackup.fileDownloadProgress = function(file, size){
536
- var getFileDownloadProgress = new sgRequestHandler('getFileDownloadProgress', {file: file, size: size, token: BG_BACKUP_STRINGS.nonce});
537
-
538
- getFileDownloadProgress.callback = function(response){
539
- if (typeof response.progress !== 'undefined') {
540
- jQuery('#uploadSgbpFile').html('Importing ('+ Math.round(response.progress)+'%)');
541
- SG_DOWNLOAD_PROGRESS = setTimeout(function () {
542
- getFileDownloadProgress.run();
543
- }, SG_AJAX_REQUEST_FREQUENCY);
544
- }
545
- };
546
-
547
- getFileDownloadProgress.run();
548
- };
549
-
550
- sgBackup.fileUploadProgress = function(e){
551
- if(e.lengthComputable){
552
- jQuery('#uploadSgbpFile').html('Importing ('+ Math.round((e.loaded*100.0)/ e.total)+'%)');
553
- }
554
- };
555
-
556
- sgBackup.checkBackupCreation = function(){
557
- jQuery('#manualBackup .btn-success').attr('disabled', true);
558
- var sgBackupCreationHandler = new sgRequestHandler('checkBackupCreation', {token: BG_BACKUP_STRINGS.nonce});
559
- sgBackupCreationHandler.dataType = 'html';
560
- sgBackupCreationHandler.callback = function(response) {
561
- var hideAndReload = function () {
562
- jQuery('#sg-modal').modal('hide');
563
- location.reload();
564
- };
565
- if (response.length) {
566
- var result = jQuery.parseJSON(response);
567
- if (result && result.status == 'cleaned') {
568
- sgBackup.manualBackup('cleaned');
569
- }
570
- else {
571
- hideAndReload();
572
- }
573
- }
574
- else {
575
- hideAndReload();
576
- }
577
- };
578
- sgBackupCreationHandler.run();
579
- };
580
-
581
- sgBackup.checkRestoreCreation = function(){
582
- jQuery('#manualBackup .btn-success').attr('disabled', true);
583
- var sgRestoreCreationHandler = new sgRequestHandler('checkRestoreCreation', {token: BG_BACKUP_STRINGS.nonce});
584
- sgRestoreCreationHandler.callback = function(response){
585
- if (response.status==0 && response.external_enabled==1) {
586
- location.href = response.external_url;
587
- }
588
- else if (response.status == 'cleaned') {
589
- jQuery('#manualBackup .btn-success').click();
590
- }
591
- else {
592
- location.reload();
593
- }
594
- };
595
- sgRestoreCreationHandler.run();
596
- };
597
-
598
- sgBackup.initManulBackupRadioInputs = function(){
599
- jQuery('input[type=radio][name=backupType]').off('change').on('change', function(){
600
- jQuery('.sg-custom-backup').fadeToggle();
601
- });
602
- jQuery('input[type=radio][name=restoreType]').off('change').on('change', function(){
603
- if(jQuery('input[type=radio][name=restoreType]:checked').val() == "files"){
604
- jQuery('.sg-restore-files-options').fadeIn();
605
- }else{
606
- jQuery('.sg-restore-files-options').fadeOut();
607
- }
608
- });
609
-
610
- jQuery('input[type=radio][name=restoreFilesType]').off('change').on('change', function(){
611
- jQuery('.sg-file-selective-restore').fadeToggle();
612
- });
613
-
614
- jQuery('input[type=checkbox][name=backupFiles], input[type=checkbox][name=backupDatabase], input[type=checkbox][name=backupCloud]').off('change').on('change', function(){
615
- var sgCheckBoxWrapper = jQuery(this).closest('.checkbox').find('.sg-checkbox');
616
- sgCheckBoxWrapper.fadeToggle();
617
- if(jQuery(this).attr('name') == 'backupFiles') {
618
- sgCheckBoxWrapper.find('input[type=checkbox]').attr('checked', 'checked');
619
- }
620
- });
621
- jQuery('input[type=radio][name=backupDBType]').off('change').on('change',function(){
622
- var sgCheckBoxWrapper = jQuery(this).closest('.checkbox').find('.sg-custom-backup-tables');
623
- if(jQuery('input[type=radio][name=backupDBType]:checked').val() == '2'){
624
- sgCheckBoxWrapper.find('input[type=checkbox]').not("[disabled]").prop('checked', true)
625
- sgCheckBoxWrapper.fadeIn();
626
- }else{
627
- sgCheckBoxWrapper.fadeOut();
628
- sgCheckBoxWrapper.find('input[type=checkbox][current="true"]').not("[disabled]").prop('checked', true)
629
- sgCheckBoxWrapper.find('input[type=checkbox][current="false"]').prop('checked', false)
630
- }
631
- })
632
- };
633
-
634
- sgBackup.initImportTooltips = function () {
635
- jQuery('a[data-toggle=tooltip]').tooltip();
636
- };
637
-
638
- sgBackup.initManualBackupTooltips = function(){
639
- jQuery('[for=cloud-ftp]').tooltip();
640
- jQuery('[for=cloud-dropbox]').tooltip();
641
- jQuery('[for=cloud-gdrive]').tooltip();
642
- jQuery('[for=cloud-one-drive]').tooltip();
643
- jQuery('[for=cloud-amazon]').tooltip();
644
- jQuery('[for=cloud-backup-guard]').tooltip();
645
-
646
- jQuery('a[data-toggle=tooltip]').tooltip();
647
- };
648
-
649
- sgBackup.startRestore = function(bname)
650
- {
651
- var checkIsItMigration = new sgRequestHandler('checkFreeMigration',{bname: bname, token: BG_BACKUP_STRINGS.nonce});
652
-
653
- checkIsItMigration.callback = function(response) {
654
- if (response) {
655
- jQuery('.modal-body.sg-modal-body').html(response);
656
- return false;
657
- }
658
-
659
- sgBackup.startRestoreAction(bname);
660
- };
661
- checkIsItMigration.dataType = '';
662
- checkIsItMigration.run();
663
- };
664
-
665
- sgBackup.startRestoreAction = function (bname)
666
- {
667
- jQuery('.alert').remove();
668
- var type = jQuery('input[type=radio][name=restoreType]:checked').val();
669
- var restoreFilesType = jQuery('input[type=radio][name=restoreFilesType]:checked').val() || "0";
670
- var paths = restoreFilesType == "0"? "/" : jQuery("#fileSystemTreeContainer").jstree("get_selected");
671
- var checkPHPVersionCompatibility = new sgRequestHandler('checkPHPVersionCompatibility',{bname: bname, token: BG_BACKUP_STRINGS.nonce});
672
-
673
- checkPHPVersionCompatibility.callback = function(response) {
674
- if (typeof response.error != 'undefined') {
675
- alert(response.error);
676
- return false;
677
- }
678
- else if (typeof response.warning != 'undefined') {
679
- if (!confirm(response.warning)) {
680
- return false;
681
- }
682
- }
683
-
684
- sgBackup.showAjaxSpinner('#sg-content-wrapper');
685
- var resetStatusHandler = new sgRequestHandler('resetStatus', {token: BG_BACKUP_STRINGS.nonce});
686
- resetStatusHandler.callback = function(response) {
687
- //If error
688
- if(typeof response.success === 'undefined') {
689
- alert(response);
690
- location.reload();
691
- return false;
692
- }
693
- var restoreHandler = new sgRequestHandler('restore',{bname: bname, type:type, paths:paths});
694
- restoreHandler.run();
695
- sgBackup.checkRestoreCreation();
696
- };
697
- resetStatusHandler.run();
698
- };
699
-
700
- if (type == "files" && restoreFilesType == 1) {
701
- var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: "SLECTIVE_RESTORE"});
702
- isFeatureAvailable.callback = function (response) {
703
- if (typeof response.success != 'undefined') {
704
- checkPHPVersionCompatibility.run();
705
- }
706
- else {
707
- var alert = sgBackup.alertGenerator(response.error, 'alert-warning');
708
- jQuery('#sg-modal .modal-header').prepend(alert);
709
- return false;
710
- }
711
- };
712
-
713
- isFeatureAvailable.run();
714
- }
715
- else {
716
- checkPHPVersionCompatibility.run();
717
- }
718
- };
719
-
720
- sgBackup.initActiveAction = function(){
721
- if(jQuery('.sg-active-action-id').length<=0){
722
- return;
723
- }
724
-
725
- var activeActionsIds = [];
726
- jQuery('.sg-active-action-id').each(function() {
727
- activeActionsIds.push(jQuery(this).val());
728
- });
729
-
730
- //Cancel Button
731
- jQuery('.sg-cancel-backup').click(function(){
732
- if (confirm('Are you sure?')) {
733
- var actionId = jQuery(this).attr('sg-data-backup-id');
734
- var sgCancelHandler = new sgRequestHandler('cancelBackup', {actionId: actionId, token: BG_BACKUP_STRINGS.nonce});
735
- sgCancelHandler.run();
736
- }
737
- });
738
-
739
- for (var i = 0; i < activeActionsIds.length; i++) {
740
- //GetProgress
741
- sgBackup.getActionProgress(activeActionsIds[i]);
742
- }
743
- };
744
-
745
- sgBackup.getActionProgress = function(actionId){
746
- var progressBar = jQuery('.sg-progress .progress-bar', '#sg-status-tabe-data-'+actionId);
747
-
748
- var sgActionHandler = new sgRequestHandler('getAction', {actionId: actionId, token: BG_BACKUP_STRINGS.nonce});
749
- //Init tooltip
750
- var statusTooltip = jQuery('#sg-status-tabe-data-'+actionId+'[data-toggle=tooltip]').tooltip();
751
-
752
- sgActionHandler.callback = function(response){
753
- if(response){
754
- sgBackup.disableUi();
755
- var progressInPercents = response.progress+'%';
756
- progressBar.width(progressInPercents);
757
- sgBackup.statusUpdate(statusTooltip, response, progressInPercents);
758
- setTimeout(function () {
759
- sgActionHandler.run();
760
- }, SG_CHECK_ACTION_STATUS_REQUEST_FREQUENCY);
761
- }
762
- else{
763
- jQuery('[class*=sg-status]').addClass('active');
764
- jQuery('.sg-progress').remove();
765
- jQuery('.sg-active-action-id').remove();
766
- location.reload();
767
- }
768
- };
769
- sgActionHandler.run();
770
- };
771
-
772
- sgBackup.statusUpdate = function(tooltip, response, progressInPercents){
773
- var tooltipText = '';
774
- if(response.type == '1'){
775
- var currentAction = 'Backup';
776
- if (response.status == '1') {
777
- tooltipText = currentAction + ' database - '+progressInPercents;
778
- }
779
- else if (response.status == '2') {
780
- tooltipText = currentAction + ' files - '+progressInPercents;
781
- }
782
- jQuery('.sg-status-'+response.status).prevAll('[class*=sg-status]').addClass('active');
783
- }
784
- else if(response.type == '2'){
785
- var currentAction = 'Restore';
786
- if (response.status == '1') {
787
- tooltipText = currentAction + ' database - '+progressInPercents;
788
- }
789
- else if (response.status == '2') {
790
- tooltipText = currentAction + ' files - '+progressInPercents;
791
- }
792
- jQuery('.sg-status-'+response.type+response.status).prevAll('[class*=sg-status]').addClass('active');
793
- }
794
- else if(response.type == '3'){
795
- var cloudIcon = jQuery('.sg-status-'+response.type+response.subtype);
796
- if(response.subtype == SG_STORAGE_FTP){
797
- tooltipText = 'Uploading to FTP - '+progressInPercents;
798
- }
799
- else if(response.subtype == SG_STORAGE_DROPBOX){
800
- tooltipText = 'Uploading to Dropbox - '+progressInPercents;
801
- }
802
- else if(response.subtype == SG_STORAGE_GOOGLE_DRIVE){
803
- tooltipText = 'Uploading to Google Drive - '+progressInPercents;
804
- }
805
- else if(response.subtype == SG_STORAGE_AMAZON) {
806
- tooltipText = 'Uploading to Amazon S3 - '+progressInPercents;
807
- }
808
- else if(response.subtype == SG_STORAGE_ONE_DRIVE) {
809
- tooltipText = 'Uploading to OneDrive - '+progressInPercents;
810
- }
811
- else if(response.subtype == SG_STORAGE_BACKUP_GUARD) {
812
- tooltipText = 'Uploading to BackupGuard - '+progressInPercents;
813
- }
814
- cloudIcon.prevAll('[class*=sg-status]').addClass('active');
815
- }
816
- tooltip.attr('data-original-title',tooltipText);
817
- };
818
-
819
- sgBackup.disableUi = function(){
820
- jQuery('#sg-manual-backup').attr('disabled','disabled');
821
- jQuery('#sg-backup-with-migration').attr('disabled','disabled');
822
- jQuery('#sg-import').attr('disabled','disabled');
823
- jQuery('.sg-restore').attr('disabled','disabled');
824
- jQuery('.sg-restore-button').attr('disabled','disabled');
825
- };
826
-
827
- sgBackup.enableUi = function(){
828
- jQuery('#sg-manual-backup').removeAttr('disabled');
829
- jQuery('#sg-import').removeAttr('disabled');
830
- jQuery('.sg-restore').removeAttr('disabled');
831
- jQuery('.sg-restore-button').removeAttr('disabled');
832
- };
833
-
834
- sgBackup.initBackupDeletion = function(){
835
- jQuery('.sg-remove-backup').click(function(){
836
- var btn = jQuery(this),
837
- url = btn.attr('data-remote'),
838
- backupName = [btn.attr('data-sgbackup-name')];
839
- if (confirm('Are you sure?')) {
840
- var ajaxHandler = new sgRequestHandler(url, {backupName: backupName, token: BG_BACKUP_STRINGS.nonce});
841
- ajaxHandler.callback = function (response) {
842
- location.reload();
843
- };
844
- ajaxHandler.run();
845
- }
846
- });
847
- };
 
1
+ BG_BACKUP_STRINGS_DEACTIVATE = '';
2
+ SG_DOWNLOAD_PROGRESS = '';
3
+ SG_ACTIVE_DOWNLOAD_AJAX = '';
4
+ SG_CHECK_ACTION_STATUS_REQUEST_FREQUENCY = 2500;
5
+
6
+ SG_STORAGE_FTP = 1;
7
+ SG_STORAGE_DROPBOX = 2;
8
+ SG_STORAGE_GOOGLE_DRIVE = 3;
9
+ SG_STORAGE_AMAZON = 4;
10
+ SG_STORAGE_ONE_DRIVE = 5;
11
+ SG_STORAGE_BACKUP_GUARD = 6;
12
+
13
+ jQuery(document).on('change', '.btn-file :file', function() {
14
+ var input = jQuery(this),
15
+ numFiles = input.get(0).files ? input.get(0).files.length : 1,
16
+ label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
17
+ input.trigger('fileselect', [numFiles, label]);
18
+ });
19
+
20
+ jQuery(document).ready( function() {
21
+ sgBackup.initTablePagination('sg-backups');
22
+ sgBackup.initActiveAction();
23
+ sgBackup.initBackupDeletion();
24
+ sgBackup.toggleMultiDeleteButton();
25
+ sgBackup.closeFreeBaner();
26
+
27
+ jQuery('span[data-toggle=tooltip]').tooltip();
28
+
29
+ jQuery('#sg-checkbox-select-all').on('change', function(){
30
+ var checkAll = jQuery('#sg-checkbox-select-all');
31
+ jQuery('tbody input[type="checkbox"]:not(:disabled):visible').prop('checked', checkAll.prop('checked'));
32
+ sgBackup.toggleMultiDeleteButton();
33
+ });
34
+
35
+ jQuery('#sg-delete-multi-backups').on('click', function(){
36
+ if (!confirm(BG_BACKUP_STRINGS_DEACTIVATE.areYouSure)) {
37
+ return false;
38
+ }
39
+ var backups = jQuery('tbody input[type="checkbox"]:checked');
40
+ var backupNames = [];
41
+ backups.each(function(i){
42
+ backupNames[i] = jQuery(this).val();
43
+ });
44
+
45
+ if (backupNames.length) {
46
+ sgBackup.deleteMultiBackups(backupNames);
47
+ }
48
+ });
49
+
50
+ jQuery('tbody input[type="checkbox"]').on('change', function(){
51
+ var numberOfBackups = jQuery('tbody input[type="checkbox"]').length;
52
+ var numberOfChoosenBackups = sgBackup.getSelectedBackupsNumber();
53
+ var isCheked = jQuery(this).is(':checked');
54
+ sgBackup.toggleMultiDeleteButton();
55
+
56
+ if(!isCheked) {
57
+ jQuery('#sg-checkbox-select-all').prop('checked', false);
58
+ }
59
+ else {
60
+ if (numberOfBackups == numberOfChoosenBackups) {
61
+ jQuery('#sg-checkbox-select-all').prop('checked', true);
62
+ }
63
+ }
64
+ });
65
+
66
+ var surveyClose = function(e) {
67
+ e.preventDefault();
68
+
69
+ jQuery('.bg-verify-user-info-container').slideUp();
70
+ jQuery('.bg-verify-user-info-overlay').hide();
71
+
72
+ var ajaxHandler = new sgRequestHandler('setUserInfoVerificationPopupState', {token: BG_BACKUP_STRINGS.nonce});
73
+ ajaxHandler.run();
74
+ };
75
+
76
+ jQuery('.bg-verify-user-info-overlay').bind('click', surveyClose);
77
+
78
+
79
+ jQuery('.bg-verify-user-info-cancel').click(surveyClose);
80
+
81
+ jQuery('#bg-verify-user-prioraty').on('change', function () {
82
+ if (jQuery(this).val() == "other") {
83
+ jQuery('#bg-verify-user-priorati-custom').show();
84
+ }
85
+ else {
86
+ jQuery('#bg-verify-user-priorati-custom').hide();
87
+ }
88
+ });
89
+
90
+ jQuery('.bg-verify-user-info-verify-email').click(function(e) {
91
+ e.preventDefault();
92
+
93
+ var email = jQuery('#bg-verify-user-info-email').val();
94
+ var fname = jQuery('#bg-verify-user-info-name').val();
95
+ var lname = jQuery('#bg-verify-user-info-last-name').val();
96
+ var priority = jQuery('#bg-verify-user-prioraty').val();
97
+
98
+ var sendData = true;
99
+ jQuery('.bg-verify-user-info-error-message').hide();
100
+
101
+ if (priority == "other") {
102
+ priority = jQuery('#bg-verify-user-priorati-custom').val();
103
+
104
+ if (!priority) {
105
+ jQuery('#bg-verify-user-info-priority-custom-error').show()
106
+ sendData = false;
107
+ }
108
+ }
109
+ else if (!priority) {
110
+ jQuery('#bg-verify-user-info-priority-error').show()
111
+ sendData = false;
112
+ }
113
+
114
+ if(fname == '') {
115
+ jQuery('#bg-verify-user-info-name-error').show();
116
+ sendData = false;
117
+ }
118
+
119
+ if(lname == '') {
120
+ jQuery('#bg-verify-user-info-last-name-error').show();
121
+ sendData = false;
122
+ }
123
+
124
+ if (!sgBackup.isValidEmailAddress(email)) {
125
+ jQuery('#bg-verify-user-info-email-error').show();
126
+ sendData = false;
127
+ }
128
+
129
+ if(sendData) {
130
+ jQuery('.bg-verify-user-info-container').slideUp();
131
+ jQuery('.bg-verify-user-info-overlay').hide();
132
+ var currentStatus = jQuery('.backup-send-usage-data-status').is(':checked');
133
+
134
+ var ajaxHandler = new sgRequestHandler('storeSubscriberInfo', {
135
+ email: email,
136
+ fname: fname,
137
+ lname: lname,
138
+ priority: priority,
139
+ currentStatus: currentStatus,
140
+ token: BG_BACKUP_STRINGS.nonce
141
+ });
142
+
143
+ ajaxHandler.run();
144
+ }
145
+ });
146
+ });
147
+
148
+ sgBackup.isValidEmailAddress = function(emailAddress) {
149
+ var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,10}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
150
+ return pattern.test(emailAddress);
151
+ };
152
+
153
+ sgBackup.getSelectedBackupsNumber = function() {
154
+ return jQuery('tbody input[type="checkbox"]:checked').length
155
+ };
156
+
157
+ sgBackup.toggleMultiDeleteButton = function() {
158
+ var numberOfChoosenBackups = sgBackup.getSelectedBackupsNumber();
159
+ var target = jQuery('#sg-delete-multi-backups');
160
+ if (numberOfChoosenBackups > 0) {
161
+ target.removeAttr('disabled');
162
+ }
163
+ else {
164
+ target.attr('disabled','disabled');
165
+ }
166
+ };
167
+
168
+ sgBackup.closeFreeBaner = function() {
169
+ jQuery('.sg-close-free-banner').bind('click', function () {
170
+ var ajaxHandler = new sgRequestHandler('closeFreeBanner', {
171
+ token: BG_BACKUP_STRINGS.nonce
172
+ });
173
+ ajaxHandler.callback = function(response, error) {
174
+ jQuery('#sg-banner').remove();
175
+ };
176
+ ajaxHandler.run();
177
+ });
178
+ };
179
+
180
+ sgBackup.deleteMultiBackups = function(backupNames){
181
+ var ajaxHandler = new sgRequestHandler('deleteBackup', {backupName: backupNames, token: BG_BACKUP_STRINGS.nonce});
182
+ ajaxHandler.callback = function (response) {
183
+ location.reload();
184
+ };
185
+ ajaxHandler.run();
186
+ };
187
+
188
+ //SGManual Backup AJAX callback
189
+ sgBackup.manualBackup = function(checkedStatus){
190
+ var error = [];
191
+ //Validation
192
+ jQuery('.alert').remove();
193
+ if(jQuery('input[type=radio][name=backupType]:checked').val() == 2) {
194
+ if(jQuery('.sg-custom-option:checked').length <= 0) {
195
+ error.push(BG_BACKUP_STRINGS.invalidBackupOption);
196
+ }
197
+ //Check if any file is selected
198
+ if(jQuery('input[type=checkbox][name=backupFiles]:checked').length > 0) {
199
+ if(jQuery('.sg-custom-backup-files input:checkbox:checked').length <= 0) {
200
+ error.push(BG_BACKUP_STRINGS.invalidDirectorySelected);
201
+ }
202
+ }
203
+ }
204
+ //Check if any cloud is selected
205
+ if(jQuery('input[type=checkbox][name=backupCloud]:checked').length > 0) {
206
+ if (jQuery('.sg-custom-backup-cloud input:checkbox:checked').length <= 0) {
207
+ error.push(BG_BACKUP_STRINGS.invalidCloud);
208
+ }
209
+ }
210
+ //If any error show it and abort ajax
211
+ if(error.length){
212
+ var sgAlert = sgBackup.alertGenerator(error, 'alert-danger');
213
+ jQuery('#sg-modal .modal-header').prepend(sgAlert);
214
+ return false;
215
+ }
216
+
217
+ if (!checkedStatus) {
218
+ sgBackup.checkBackupCreation();
219
+ }
220
+
221
+ //Before all disable buttons...
222
+ jQuery('.alert').remove();
223
+ jQuery('.modal-footer .btn-primary').attr('disabled','disabled');
224
+ jQuery('.modal-footer .btn-primary').html(BG_BACKUP_STRINGS.backupInProgress);
225
+
226
+ //Reset Status
227
+ var backupName = jQuery("#sg-custom-backup-name").val();
228
+ var resetStatusHandler = new sgRequestHandler('resetStatus', {backupName: backupName, token: BG_BACKUP_STRINGS.nonce });
229
+ resetStatusHandler.callback = function(response, error){
230
+ var manualBackupForm = jQuery('#manualBackup');
231
+ var manualBackupHandler = new sgRequestHandler('manualBackup', manualBackupForm.serialize()+'&token='+BG_BACKUP_STRINGS.nonce);
232
+ manualBackupHandler.dataIsObject = false;
233
+ //If error
234
+ if(typeof response.success === 'undefined') {
235
+ var sgAlert = sgBackup.alertGenerator(response, 'alert-danger');
236
+ jQuery('#sg-modal .modal-header').prepend(sgAlert);
237
+
238
+ if (response === 0 || response === false || response === '0' || response === 'false') {
239
+ response = BG_BACKUP_STRINGS.errorMessage;
240
+ }
241
+ sgBackup.restManualBackupModal();
242
+ return false;
243
+ }
244
+ if (checkedStatus) {
245
+ sgBackup.hideAndReload();
246
+ }
247
+ manualBackupHandler.run();
248
+ };
249
+ resetStatusHandler.run();
250
+ };
251
+
252
+ sgBackup.hideAndReload = function () {
253
+ jQuery('#sg-modal').modal('hide');
254
+ location.reload();
255
+ };
256
+
257
+ sgBackup.restManualBackupModal = function() {
258
+ jQuery('.modal-footer .btn-primary').removeAttr('disabled');
259
+ jQuery('.modal-footer .btn-primary').html('Backup');
260
+ };
261
+
262
+ sgBackup.cancelDonwload = function(name) {
263
+ var cancelDonwloadHandler = new sgRequestHandler('cancelDownload', {name: name, token: BG_BACKUP_STRINGS.nonce});
264
+ cancelDonwloadHandler.callback = function(response){
265
+ sgBackup.hideAjaxSpinner();
266
+ location.reload();
267
+ };
268
+ cancelDonwloadHandler.run();
269
+ };
270
+
271
+ sgBackup.listStorage = function(importFrom) {
272
+ var listStorage = new sgRequestHandler('listStorage', {storage: importFrom, token: BG_BACKUP_STRINGS.nonce});
273
+ sgBackup.showAjaxSpinner('#sg-modal-inport-from');
274
+ jQuery('#sg-archive-list-table tbody').empty();
275
+
276
+ jQuery('#sg-modal').off('hide.bs.modal').on('hide.bs.modal', function(e){
277
+
278
+ if (SG_ACTIVE_DOWNLOAD_AJAX) {
279
+ if (!confirm(BG_BACKUP_STRINGS.confirm)) {
280
+ e.preventDefault();
281
+ return false;
282
+ }
283
+ var target = jQuery('input[name="select-archive-to-download"]:checked');
284
+ var name = target.attr('file-name');
285
+
286
+ sgBackup.cancelDonwload(name);
287
+ }
288
+ });
289
+
290
+ listStorage.callback = function(response, error) {
291
+ var cloudName = '';
292
+ var cloudId = parseInt(importFrom, 10);
293
+
294
+ switch (cloudId) {
295
+ case SG_STORAGE_AMAZON:
296
+ cloudName = "S3";
297
+ break;
298
+ case SG_STORAGE_DROPBOX:
299
+ cloudName = "Dropbox";
300
+ break;
301
+ case SG_STORAGE_GOOGLE_DRIVE:
302
+ cloudName = "Google Drive";
303
+ break;
304
+ case SG_STORAGE_FTP:
305
+ cloudName = "FTP";
306
+ break;
307
+ case SG_STORAGE_ONE_DRIVE:
308
+ cloudName = "OneDrive";
309
+ break;
310
+ case SG_STORAGE_BACKUP_GUARD:
311
+ cloudName = "BackupGuard";
312
+ break;
313
+ default:
314
+ cloudName = '';
315
+ }
316
+
317
+ jQuery('.modal-title').html('Import from '+cloudName);
318
+
319
+ sgBackup.hideAjaxSpinner();
320
+ var content = '';
321
+ if ((typeof response.error != "undefined") || response.length == 0 || response === undefined) {
322
+ content = '<tr><td colspan="4">'+BG_BACKUP_STRINGS.noBackupsAvailable+'</td></tr>';
323
+ }
324
+ else {
325
+ jQuery.each(response, function( key, value ) {
326
+
327
+ var backupId = 0;
328
+
329
+ if (typeof value.id != 'undefined') {
330
+ backupId = value.id;
331
+ value.path = value.name;
332
+ }
333
+
334
+ content += '<tr>';
335
+ content += '<td class="file-select-radio"><input type="radio" file-name="'+value.name+'" name="select-archive-to-download" size="'+value.size+'" backup-id="'+value.id+'" storage="'+importFrom+'" value="'+value.path+'"></td>';
336
+ content += '<td>'+value.name+'</td>';
337
+ content += '<td>'+sgBackup.convertBytesToMegabytes(value.size)+'</td>';
338
+ content += '<td>'+value.date+'</td>';
339
+ content += '</tr>';
340
+ });
341
+ }
342
+
343
+ jQuery('#sg-archive-list-table tbody').append(content);
344
+ sgBackup.toggleDownloadFromCloudPage();
345
+ };
346
+
347
+ listStorage.run();
348
+ };
349
+
350
+
351
+ sgBackup.convertBytesToMegabytes = function ($bytes) {
352
+ return ($bytes/(1024*1024)).toFixed(2);
353
+ };
354
+
355
+ //Init file upload
356
+ sgBackup.initFileUpload = function(){
357
+ sgBackup.downloadFromPC();
358
+
359
+ jQuery('#uploadSgbpFile').click(function(){
360
+ if(jQuery('#modal-import-3').is(":visible")) {
361
+ var target = jQuery('input[name="select-archive-to-download"]:checked');
362
+ var path = target.val();
363
+ var name = target.attr('file-name');
364
+ var storage = target.attr('storage');
365
+ var size = target.attr('size');
366
+ var backupId = target.attr('backup-id');
367
+ sgBackup.downloadFromCloud(path, name, storage, size, backupId);
368
+ }
369
+ });
370
+ };
371
+
372
+ sgBackup.nextPage = function(){
373
+ var importFrom = jQuery('input[name="storage-radio"]:checked').val();
374
+ jQuery('.alert').remove();
375
+
376
+ if (!importFrom) {
377
+ var alert = sgBackup.alertGenerator(BG_BACKUP_STRINGS.invalidImportOption, 'alert-danger');
378
+ jQuery('#sg-modal .modal-header').prepend(alert);
379
+ }
380
+ else {
381
+ if (importFrom == 'local-pc') {
382
+ sgBackup.toggleDownloadFromPCPage();
383
+ }
384
+ else {
385
+ var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: "DOWNLOAD_FROM_CLOUD"});
386
+ isFeatureAvailable.callback = function(response) {
387
+ if (typeof response.success !== 'undefined') {
388
+ sgBackup.listStorage(importFrom);
389
+ }
390
+ else {
391
+ var alert = sgBackup.alertGenerator(response.error, 'alert-danger');
392
+ jQuery('#sg-modal .modal-header').prepend(alert);
393
+ }
394
+ };
395
+
396
+ isFeatureAvailable.run();
397
+ }
398
+ }
399
+ };
400
+
401
+ sgBackup.previousPage = function(){
402
+ if(jQuery('#modal-import-2').is(":visible")){
403
+ jQuery('#modal-import-2').hide();
404
+ }
405
+ else{
406
+ jQuery('#modal-import-3').hide();
407
+ }
408
+
409
+ sgBackup.toggleNavigationButtons();
410
+
411
+ jQuery('#modal-import-1').show();
412
+ jQuery('#uploadSgbpFile').hide();
413
+
414
+ jQuery('.modal-title').html('Import from');
415
+ };
416
+
417
+ sgBackup.toggleNavigationButtons = function(){
418
+ jQuery('#switch-modal-import-pages-next').toggle();
419
+ jQuery('#switch-modal-import-pages-back').toggle();
420
+ };
421
+
422
+ sgBackup.toggleDownloadFromPCPage = function(){
423
+ sgBackup.toggleNavigationButtons();
424
+ jQuery('#modal-import-1').toggle();
425
+ jQuery('#modal-import-2').toggle();
426
+ jQuery('#uploadSgbpFile').toggle();
427
+ };
428
+
429
+ sgBackup.toggleDownloadFromCloudPage = function(){
430
+ sgBackup.toggleNavigationButtons();
431
+ jQuery('#modal-import-1').toggle();
432
+ jQuery('#modal-import-3').toggle();
433
+ jQuery('#uploadSgbpFile').toggle();
434
+ };
435
+
436
+ sgBackup.downloadFromCloud = function (path, name, storage, size) {
437
+ sgBackup.showAjaxSpinner('.modal-dialog');
438
+ var error = [];
439
+ if (!path) {
440
+ error.push(BG_BACKUP_STRINGS.invalidDownloadFile);
441
+ }
442
+
443
+ jQuery('.alert').remove();
444
+
445
+ if (error.length) {
446
+ sgBackup.hideAjaxSpinner();
447
+ var sgAlert = sgBackup.alertGenerator(error, 'alert-danger');
448
+ jQuery('#sg-modal .modal-header').prepend(sgAlert);
449
+ return false;
450
+ }
451
+
452
+ var downloadFromCloudHandler = new sgRequestHandler('downloadFromCloud', {
453
+ path: path,
454
+ storage: storage,
455
+ size: size,
456
+ token: BG_BACKUP_STRINGS.nonce
457
+ });
458
+
459
+ jQuery('#switch-modal-import-pages-back').hide();
460
+ jQuery('#uploadSgbpFile').attr('disabled', 'disabled');
461
+
462
+ downloadFromCloudHandler.callback = function (response, error){
463
+ sgBackup.hideAjaxSpinner();
464
+ jQuery('.alert').remove();
465
+
466
+ clearTimeout(SG_DOWNLOAD_PROGRESS);
467
+
468
+ if (typeof response.success !== 'undefined') {
469
+ location.reload();
470
+ }
471
+ else {
472
+ jQuery('#uploadSgbpFile').html(BG_BACKUP_STRINGS.import);
473
+
474
+ var sgAlert = sgBackup.alertGenerator(response.error, 'alert-danger');
475
+
476
+ jQuery('#uploadSgbpFile').attr('disabled', false);
477
+ jQuery('#switch-modal-import-pages-back').toggle();
478
+ jQuery('#sg-modal .modal-header').prepend(sgAlert);
479
+ SG_ACTIVE_DOWNLOAD_AJAX = false;
480
+
481
+ return false;
482
+ }
483
+ };
484
+
485
+ SG_ACTIVE_DOWNLOAD_AJAX = true;
486
+ downloadFromCloudHandler.run();
487
+ sgBackup.fileDownloadProgress(name, size);
488
+ };
489
+
490
+ sgBackup.downloadFromPC = function(){
491
+ var sgData = null;
492
+ jQuery('#sg-modal').off('hide.bs.modal').on('hide.bs.modal', function(e){
493
+ if (SG_ACTIVE_DOWNLOAD_AJAX) {
494
+ if (!confirm(BG_BACKUP_STRINGS.confirm)) {
495
+ e.preventDefault();
496
+ return false;
497
+ }
498
+
499
+ sgData.abort();
500
+ sgBackup.cancelDonwload(sgData.files[0].name);
501
+ }
502
+ });
503
+
504
+ jQuery('.sg-backup-upload-input').fileupload({
505
+ dataType: 'json',
506
+ maxChunkSize: 2000000,
507
+ add: function (e, data) {
508
+ if (data.originalFiles.length) {
509
+ var fileName = data.originalFiles[0].name;
510
+ jQuery('#sg-import-file-name').val(fileName);
511
+ }
512
+ jQuery('#uploadSgbpFile').click(function(){
513
+ if(jQuery('#modal-import-2').is(":visible")) {
514
+ sgData = data;
515
+ SG_ACTIVE_DOWNLOAD_AJAX = true;
516
+ jQuery('#uploadSgbpFile').attr('disabled','disabled');
517
+ jQuery('#switch-modal-import-pages-back').hide();
518
+ jQuery('#uploadSgbpFile').html(BG_BACKUP_STRINGS.importInProgress);
519
+ data.submit();
520
+ }
521
+ });
522
+ },
523
+ done: function (e, data) {
524
+ location.reload();
525
+ },
526
+ progress: function (e, data) {
527
+ var progress = parseInt(data.loaded / data.total * 100, 10);
528
+ jQuery('#uploadSgbpFile').html('Importing ('+ Math.round(progress)+'%)');
529
+ }
530
+ }).on('fileuploadfail', function (e, data) {
531
+ var alert = sgBackup.alertGenerator(BG_BACKUP_STRINGS.fileUploadFailed, 'alert-danger');
532
+ jQuery('#sg-modal .modal-header').prepend(alert);
533
+ });
534
+ };
535
+
536
+ sgBackup.fileDownloadProgress = function(file, size){
537
+ var getFileDownloadProgress = new sgRequestHandler('getFileDownloadProgress', {file: file, size: size, token: BG_BACKUP_STRINGS.nonce});
538
+
539
+ getFileDownloadProgress.callback = function(response){
540
+ if (typeof response.progress !== 'undefined') {
541
+ jQuery('#uploadSgbpFile').html('Importing ('+ Math.round(response.progress)+'%)');
542
+ SG_DOWNLOAD_PROGRESS = setTimeout(function () {
543
+ getFileDownloadProgress.run();
544
+ }, SG_AJAX_REQUEST_FREQUENCY);
545
+ }
546
+ };
547
+
548
+ getFileDownloadProgress.run();
549
+ };
550
+
551
+ sgBackup.fileUploadProgress = function(e){
552
+ if(e.lengthComputable){
553
+ jQuery('#uploadSgbpFile').html('Importing ('+ Math.round((e.loaded*100.0)/ e.total)+'%)');
554
+ }
555
+ };
556
+
557
+ sgBackup.checkBackupCreation = function(){
558
+ jQuery('#manualBackup .btn-success').attr('disabled', true);
559
+ var sgBackupCreationHandler = new sgRequestHandler('checkBackupCreation', {token: BG_BACKUP_STRINGS.nonce});
560
+ sgBackupCreationHandler.dataType = 'html';
561
+ sgBackupCreationHandler.callback = function(response) {
562
+ var hideAndReload = function () {
563
+ jQuery('#sg-modal').modal('hide');
564
+ location.reload();
565
+ };
566
+ if (response.length) {
567
+ var result = jQuery.parseJSON(response);
568
+ if (result && result.status == 'cleaned') {
569
+ sgBackup.manualBackup('cleaned');
570
+ }
571
+ else {
572
+ hideAndReload();
573
+ }
574
+ }
575
+ else {
576
+ hideAndReload();
577
+ }
578
+ };
579
+ sgBackupCreationHandler.run();
580
+ };
581
+
582
+ sgBackup.checkRestoreCreation = function(){
583
+ jQuery('#manualBackup .btn-success').attr('disabled', true);
584
+ var sgRestoreCreationHandler = new sgRequestHandler('checkRestoreCreation', {token: BG_BACKUP_STRINGS.nonce});
585
+ sgRestoreCreationHandler.callback = function(response){
586
+ if (response.status==0 && response.external_enabled==1) {
587
+ location.href = response.external_url;
588
+ }
589
+ else if (response.status == 'cleaned') {
590
+ jQuery('#manualBackup .btn-success').click();
591
+ }
592
+ else {
593
+ location.reload();
594
+ }
595
+ };
596
+ sgRestoreCreationHandler.run();
597
+ };
598
+
599
+ sgBackup.initManulBackupRadioInputs = function(){
600
+ jQuery('input[type=radio][name=backupType]').off('change').on('change', function(){
601
+ jQuery('.sg-custom-backup').fadeToggle();
602
+ });
603
+ jQuery('input[type=radio][name=restoreType]').off('change').on('change', function(){
604
+ if(jQuery('input[type=radio][name=restoreType]:checked').val() == "files"){
605
+ jQuery('.sg-restore-files-options').fadeIn();
606
+ }else{
607
+ jQuery('.sg-restore-files-options').fadeOut();
608
+ }
609
+ });
610
+
611
+ jQuery('input[type=radio][name=restoreFilesType]').off('change').on('change', function(){
612
+ jQuery('.sg-file-selective-restore').fadeToggle();
613
+ });
614
+
615
+ jQuery('input[type=checkbox][name=backupFiles], input[type=checkbox][name=backupDatabase], input[type=checkbox][name=backupCloud]').off('change').on('change', function(){
616
+ var sgCheckBoxWrapper = jQuery(this).closest('.checkbox').find('.sg-checkbox');
617
+ sgCheckBoxWrapper.fadeToggle();
618
+ if(jQuery(this).attr('name') == 'backupFiles') {
619
+ sgCheckBoxWrapper.find('input[type=checkbox]').attr('checked', 'checked');
620
+ }
621
+ });
622
+ jQuery('input[type=radio][name=backupDBType]').off('change').on('change',function(){
623
+ var sgCheckBoxWrapper = jQuery(this).closest('.checkbox').find('.sg-custom-backup-tables');
624
+ if(jQuery('input[type=radio][name=backupDBType]:checked').val() == '2'){
625
+ sgCheckBoxWrapper.find('input[type=checkbox]').not("[disabled]").prop('checked', true)
626
+ sgCheckBoxWrapper.fadeIn();
627
+ }else{
628
+ sgCheckBoxWrapper.fadeOut();
629
+ sgCheckBoxWrapper.find('input[type=checkbox][current="true"]').not("[disabled]").prop('checked', true)
630
+ sgCheckBoxWrapper.find('input[type=checkbox][current="false"]').prop('checked', false)
631
+ }
632
+ })
633
+ };
634
+
635
+ sgBackup.initImportTooltips = function () {
636
+ jQuery('a[data-toggle=tooltip]').tooltip();
637
+ };
638
+
639
+ sgBackup.initManualBackupTooltips = function(){
640
+ jQuery('[for=cloud-ftp]').tooltip();
641
+ jQuery('[for=cloud-dropbox]').tooltip();
642
+ jQuery('[for=cloud-gdrive]').tooltip();
643
+ jQuery('[for=cloud-one-drive]').tooltip();
644
+ jQuery('[for=cloud-amazon]').tooltip();
645
+ jQuery('[for=cloud-backup-guard]').tooltip();
646
+
647
+ jQuery('a[data-toggle=tooltip]').tooltip();
648
+ };
649
+
650
+ sgBackup.startRestore = function(bname)
651
+ {
652
+ var checkIsItMigration = new sgRequestHandler('checkFreeMigration',{bname: bname, token: BG_BACKUP_STRINGS.nonce});
653
+
654
+ checkIsItMigration.callback = function(response) {
655
+ if (response) {
656
+ jQuery('.modal-body.sg-modal-body').html(response);
657
+ return false;
658
+ }
659
+
660
+ sgBackup.startRestoreAction(bname);
661
+ };
662
+ checkIsItMigration.dataType = '';
663
+ checkIsItMigration.run();
664
+ };
665
+
666
+ sgBackup.startRestoreAction = function (bname)
667
+ {
668
+ jQuery('.alert').remove();
669
+ var type = jQuery('input[type=radio][name=restoreType]:checked').val();
670
+ var restoreFilesType = jQuery('input[type=radio][name=restoreFilesType]:checked').val() || "0";
671
+ var paths = restoreFilesType == "0"? "/" : jQuery("#fileSystemTreeContainer").jstree("get_selected");
672
+ var checkPHPVersionCompatibility = new sgRequestHandler('checkPHPVersionCompatibility',{bname: bname, token: BG_BACKUP_STRINGS.nonce});
673
+
674
+ checkPHPVersionCompatibility.callback = function(response) {
675
+ if (typeof response.error != 'undefined') {
676
+ alert(response.error);
677
+ return false;
678
+ }
679
+ else if (typeof response.warning != 'undefined') {
680
+ if (!confirm(response.warning)) {
681
+ return false;
682
+ }
683
+ }
684
+
685
+ sgBackup.showAjaxSpinner('#sg-content-wrapper');
686
+ var resetStatusHandler = new sgRequestHandler('resetStatus', {token: BG_BACKUP_STRINGS.nonce});
687
+ resetStatusHandler.callback = function(response) {
688
+ //If error
689
+ if(typeof response.success === 'undefined') {
690
+ alert(response);
691
+ location.reload();
692
+ return false;
693
+ }
694
+ var restoreHandler = new sgRequestHandler('restore',{bname: bname, type:type, paths:paths});
695
+ restoreHandler.run();
696
+ sgBackup.checkRestoreCreation();
697
+ };
698
+ resetStatusHandler.run();
699
+ };
700
+
701
+ if (type == "files" && restoreFilesType == 1) {
702
+ var isFeatureAvailable = new sgRequestHandler('isFeatureAvailable', {sgFeature: "SLECTIVE_RESTORE"});
703
+ isFeatureAvailable.callback = function (response) {
704
+ if (typeof response.success != 'undefined') {
705
+ checkPHPVersionCompatibility.run();
706
+ }
707
+ else {
708
+ var alert = sgBackup.alertGenerator(response.error, 'alert-warning');
709
+ jQuery('#sg-modal .modal-header').prepend(alert);
710
+ return false;
711
+ }
712
+ };
713
+
714
+ isFeatureAvailable.run();
715
+ }
716
+ else {
717
+ checkPHPVersionCompatibility.run();
718
+ }
719
+ };
720
+
721
+ sgBackup.initActiveAction = function(){
722
+ if(jQuery('.sg-active-action-id').length<=0){
723
+ return;
724
+ }
725
+
726
+ var activeActionsIds = [];
727
+ jQuery('.sg-active-action-id').each(function() {
728
+ activeActionsIds.push(jQuery(this).val());
729
+ });
730
+
731
+ //Cancel Button
732
+ jQuery('.sg-cancel-backup').click(function(){
733
+ if (confirm('Are you sure?')) {
734
+ var actionId = jQuery(this).attr('sg-data-backup-id');
735
+ var sgCancelHandler = new sgRequestHandler('cancelBackup', {actionId: actionId, token: BG_BACKUP_STRINGS.nonce});
736
+ sgCancelHandler.run();
737
+ }
738
+ });
739
+
740
+ for (var i = 0; i < activeActionsIds.length; i++) {
741
+ //GetProgress
742
+ sgBackup.getActionProgress(activeActionsIds[i]);
743
+ }
744
+ };
745
+
746
+ sgBackup.getActionProgress = function(actionId){
747
+ var progressBar = jQuery('.sg-progress .progress-bar', '#sg-status-tabe-data-'+actionId);
748
+
749
+ var sgActionHandler = new sgRequestHandler('getAction', {actionId: actionId, token: BG_BACKUP_STRINGS.nonce});
750
+ //Init tooltip
751
+ var statusTooltip = jQuery('#sg-status-tabe-data-'+actionId+'[data-toggle=tooltip]').tooltip();
752
+
753
+ sgActionHandler.callback = function(response){
754
+ if(response){
755
+ sgBackup.disableUi();
756
+ var progressInPercents = response.progress+'%';
757
+ progressBar.width(progressInPercents);
758
+ sgBackup.statusUpdate(statusTooltip, response, progressInPercents);
759
+ setTimeout(function () {
760
+ sgActionHandler.run();
761
+ }, SG_CHECK_ACTION_STATUS_REQUEST_FREQUENCY);
762
+ }
763
+ else{
764
+ jQuery('[class*=sg-status]').addClass('active');
765
+ jQuery('.sg-progress').remove();
766
+ jQuery('.sg-active-action-id').remove();
767
+ location.reload();
768
+ }
769
+ };
770
+ sgActionHandler.run();
771
+ };
772
+
773
+ sgBackup.statusUpdate = function(tooltip, response, progressInPercents){
774
+ var tooltipText = '';
775
+ if(response.type == '1'){
776
+ var currentAction = 'Backup';
777
+ if (response.status == '1') {
778
+ tooltipText = currentAction + ' database - '+progressInPercents;
779
+ }
780
+ else if (response.status == '2') {
781
+ tooltipText = currentAction + ' files - '+progressInPercents;
782
+ }
783
+ jQuery('.sg-status-'+response.status).prevAll('[class*=sg-status]').addClass('active');
784
+ }
785
+ else if(response.type == '2'){
786
+ var currentAction = 'Restore';
787
+ if (response.status == '1') {
788
+ tooltipText = currentAction + ' database - '+progressInPercents;
789
+ }
790
+ else if (response.status == '2') {
791
+ tooltipText = currentAction + ' files - '+progressInPercents;
792
+ }
793
+ jQuery('.sg-status-'+response.type+response.status).prevAll('[class*=sg-status]').addClass('active');
794
+ }
795
+ else if(response.type == '3'){
796
+ var cloudIcon = jQuery('.sg-status-'+response.type+response.subtype);
797
+ if(response.subtype == SG_STORAGE_FTP){
798
+ tooltipText = 'Uploading to FTP - '+progressInPercents;
799
+ }
800
+ else if(response.subtype == SG_STORAGE_DROPBOX){
801
+ tooltipText = 'Uploading to Dropbox - '+progressInPercents;
802
+ }
803
+ else if(response.subtype == SG_STORAGE_GOOGLE_DRIVE){
804
+ tooltipText = 'Uploading to Google Drive - '+progressInPercents;
805
+ }
806
+ else if(response.subtype == SG_STORAGE_AMAZON) {
807
+ tooltipText = 'Uploading to Amazon S3 - '+progressInPercents;
808
+ }
809
+ else if(response.subtype == SG_STORAGE_ONE_DRIVE) {
810
+ tooltipText = 'Uploading to OneDrive - '+progressInPercents;
811
+ }
812
+ else if(response.subtype == SG_STORAGE_BACKUP_GUARD) {
813
+ tooltipText = 'Uploading to BackupGuard - '+progressInPercents;
814
+ }
815
+ cloudIcon.prevAll('[class*=sg-status]').addClass('active');
816
+ }
817
+ tooltip.attr('data-original-title',tooltipText);
818
+ };
819
+
820
+ sgBackup.disableUi = function(){
821
+ jQuery('#sg-manual-backup').attr('disabled','disabled');
822
+ jQuery('#sg-backup-with-migration').attr('disabled','disabled');
823
+ jQuery('#sg-import').attr('disabled','disabled');
824
+ jQuery('.sg-restore').attr('disabled','disabled');
825
+ jQuery('.sg-restore-button').attr('disabled','disabled');
826
+ };
827
+
828
+ sgBackup.enableUi = function(){
829
+ jQuery('#sg-manual-backup').removeAttr('disabled');
830
+ jQuery('#sg-import').removeAttr('disabled');
831
+ jQuery('.sg-restore').removeAttr('disabled');
832
+ jQuery('.sg-restore-button').removeAttr('disabled');
833
+ };
834
+
835
+ sgBackup.initBackupDeletion = function(){
836
+ jQuery('.sg-remove-backup').click(function(){
837
+ var btn = jQuery(this),
838
+ url = btn.attr('data-remote'),
839
+ backupName = [btn.attr('data-sgbackup-name')];
840
+ if (confirm('Are you sure?')) {
841
+ var ajaxHandler = new sgRequestHandler(url, {backupName: backupName, token: BG_BACKUP_STRINGS.nonce});
842
+ ajaxHandler.callback = function (response) {
843
+ location.reload();
844
+ };
845
+ ajaxHandler.run();
846
+ }
847
+ });
848
+ };
public/systemInfo.php CHANGED
@@ -1,96 +1,98 @@
1
- <?php
2
- require_once(SG_SCHEDULE_PATH.'SGSchedule.php');
3
- $contentClassName = getBackupPageContentClassName('system_info');
4
- ?>
5
- <div id="sg-backup-page-content-system_info" class="sg-backup-page-content <?php echo $contentClassName; ?>">
6
- <div class="row">
7
- <div class="col-md-12">
8
- <form class="form-horizontal" method="post" data-sgform="ajax" data-type="sgsettings">
9
- <fieldset>
10
- <div><h1 class="sg-backup-page-title"><?php _backupGuardT('System information')?></h1></div>
11
- <div class="form-group">
12
- <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('Disk free space'); ?></label>
13
- <div class="col-md-3 text-left">
14
- <label class="sg-control-label">
15
- <?php echo convertToReadableSize(@disk_free_space(SG_APP_ROOT_DIRECTORY)); ?>
16
- </label>
17
- </div>
18
- </div>
19
- <div class="form-group sg-info-wrapper">
20
- <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('Memory limit'); ?></label>
21
- <div class="col-md-3 text-left">
22
- <label class="sg-control-label"><?php echo SGBoot::$memoryLimit; ?></label>
23
- </div>
24
- </div>
25
- <div class="form-group sg-info-wrapper">
26
- <label class="col-md-3 sg-control-label sg-user-info">
27
- <?php _backupGuardT('Max execution time'); ?>
28
- </label>
29
- <div class="col-md-3 text-left">
30
- <label class="sg-control-label"><?php echo SGBoot::$executionTimeLimit; ?></label>
31
- </div>
32
- </div>
33
- <div class="form-group sg-info-wrapper">
34
- <label class="col-md-3 sg-control-label sg-user-info">
35
- <?php _backupGuardT('PHP version'); ?>
36
- </label>
37
- <div class="col-md-3 text-left">
38
- <label class="sg-control-label"><?php echo PHP_VERSION; ?></label>
39
- </div>
40
- </div>
41
- <div class="form-group sg-info-wrapper">
42
- <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('MySQL version'); ?></label>
43
- <div class="col-md-3 text-left">
44
- <label class="sg-control-label"><?php echo SG_MYSQL_VERSION; ?></label>
45
- </div>
46
- </div>
47
- <div class="form-group sg-info-wrapper">
48
- <label class="col-md-3 sg-control-label sg-user-info">
49
- <?php _backupGuardT('Int size'); ?>
50
- </label>
51
- <div class="col-md-3 text-left">
52
- <?php echo '<label class="sg-control-label">'.PHP_INT_SIZE.'</label>'; ?>
53
- <?php
54
- if (PHP_INT_SIZE < 8) {
55
- echo '<label class="sg-control-label backup-guard-label-warning">Notice that archive size cannot be bigger than 2GB. This limitaion is comming from system.</label>';
56
- }
57
- ?>
58
- </div>
59
- </div>
60
- <div class="form-group sg-info-wrapper">
61
- <div class="col-md-3 ">
62
- <label class="sg-control-label sg-user-info"><?php _backupGuardT('Curl version'); ?></label>
63
- </div>
64
- <div class="col-md-8 text-left">
65
- <?php
66
- if (function_exists('curl_version') && function_exists('curl_exec')) {
67
- $cv = curl_version();
68
- echo '<label class="sg-control-label sg-blue-label">'.$cv['version'].' / SSL: '.$cv['ssl_version'].' / libz: '.$cv['libz_version'].'</label>';
69
- }
70
- else {
71
- echo '<label class="sg-control-label backup-guard-label-warning">Curl required for BackupGuard for better functioning.</label>';
72
- }
73
- ?>
74
- </div>
75
- </div>
76
- <div class="form-group sg-info-wrapper">
77
- <div class="col-md-3 ">
78
- <label class="sg-control-label sg-user-info"><?php _backupGuardT('Is cron available'); ?></label>
79
- </div>
80
- <div class="col-md-3 text-left">
81
- <?php
82
- $isCronAvailable = SGSchedule::isCronAvailable();
83
- if ($isCronAvailable) {
84
- echo '<label class="sg-control-label">Yes</label>';
85
- }
86
- else {
87
- echo '<label class="sg-control-label backup-guard-label-warning">Please consider enabling WP Cron in order to be able to setup schedules.</label>';
88
- }
89
- ?>
90
- </div>
91
- </div>
92
- </fieldset>
93
- </form>
94
- </div>
95
- </div>
96
- </div>
 
 
1
+ <?php
2
+ require_once(SG_SCHEDULE_PATH.'SGSchedule.php');
3
+ $contentClassName = getBackupPageContentClassName('system_info');
4
+ ?>
5
+ <div id="sg-backup-page-content-system_info" class="sg-backup-page-content <?php echo $contentClassName; ?>">
6
+ <div class="row">
7
+ <div class="col-md-12">
8
+ <form class="form-horizontal" method="post" data-sgform="ajax" data-type="sgsettings">
9
+ <fieldset>
10
+ <div><h1 class="sg-backup-page-title"><?php _backupGuardT('System information')?></h1></div>
11
+ <div class="form-group">
12
+ <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('Disk free space'); ?></label>
13
+ <div class="col-md-3 text-left">
14
+ <label class="sg-control-label">
15
+ <?php echo convertToReadableSize(@disk_free_space(SG_APP_ROOT_DIRECTORY)); ?>
16
+ </label>
17
+ </div>
18
+ </div>
19
+ <div class="form-group sg-info-wrapper">
20
+ <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('Memory limit'); ?></label>
21
+ <div class="col-md-3 text-left">
22
+ <label class="sg-control-label"><?php echo SGBoot::$memoryLimit; ?></label>
23
+ </div>
24
+ </div>
25
+ <div class="form-group sg-info-wrapper">
26
+ <label class="col-md-3 sg-control-label sg-user-info">
27
+ <?php _backupGuardT('Max execution time'); ?>
28
+ </label>
29
+ <div class="col-md-3 text-left">
30
+ <label class="sg-control-label"><?php echo SGBoot::$executionTimeLimit; ?></label>
31
+ </div>
32
+ </div>
33
+ <div class="form-group sg-info-wrapper">
34
+ <label class="col-md-3 sg-control-label sg-user-info">
35
+ <?php _backupGuardT('PHP version'); ?>
36
+ </label>
37
+ <div class="col-md-3 text-left">
38
+ <label class="sg-control-label"><?php echo PHP_VERSION; ?></label>
39
+ </div>
40
+ </div>
41
+ <div class="form-group sg-info-wrapper">
42
+ <label class="col-md-3 sg-control-label sg-user-info"><?php _backupGuardT('MySQL version'); ?></label>
43
+ <div class="col-md-3 text-left">
44
+ <label class="sg-control-label"><?php echo SG_MYSQL_VERSION; ?></label>
45
+ </div>
46
+ </div>
47
+ <div class="form-group sg-info-wrapper">
48
+ <label class="col-md-3 sg-control-label sg-user-info">
49
+ <?php _backupGuardT('Int size'); ?>
50
+ </label>
51
+ <div class="col-md-3 text-left">
52
+ <?php echo '<label class="sg-control-label">'.PHP_INT_SIZE.'</label>'; ?>
53
+ <?php
54
+ if (PHP_INT_SIZE < 8) {
55
+ echo '<label class="sg-control-label backup-guard-label-warning">Notice that archive size cannot be bigger than 2GB. This limitaion is comming from system.</label>';
56
+ }
57
+ ?>
58
+ </div>
59
+ </div>
60
+ <div class="form-group sg-info-wrapper">
61
+ <div class="col-md-3 ">
62
+ <label class="sg-control-label sg-user-info"><?php _backupGuardT('Curl version'); ?></label>
63
+ </div>
64
+ <div class="col-md-8 text-left">
65
+ <?php
66
+ if (function_exists('curl_version') && function_exists('curl_exec')) {
67
+ $cv = curl_version();
68
+ echo '<label class="sg-control-label sg-blue-label">'.$cv['version'].' / SSL: '.$cv['ssl_version'].' / libz: '.$cv['libz_version'].'</label>';
69
+ }
70
+ else {
71
+ echo '<label class="sg-control-label backup-guard-label-warning">Curl required for BackupGuard for better functioning.</label>';
72
+ }
73
+ ?>
74
+ </div>
75
+ </div>
76
+ <div class="form-group sg-info-wrapper">
77
+ <div class="col-md-3 ">
78
+ <label class="sg-control-label sg-user-info"><?php _backupGuardT('Is cron available'); ?></label>
79
+ </div>
80
+ <div class="col-md-3 text-left">
81
+ <?php
82
+ $isCronAvailable = SGSchedule::isCronAvailable(true);
83
+ if ($isCronAvailable) {
84
+ echo '<label class="sg-control-label">Yes</label>';
85
+ }
86
+ else {
87
+ //echo '<label class="sg-control-label backup-guard-label-warning">Please consider enabling WP Cron in order to be able to setup schedules.</label>';
88
+ echo '<label class="sg-control-label backup-guard-label-warning">WP cron is disabled on your end. If you don\'t use a custom cron, please, enable the WP cron or else the scheduled (backup) won\'t be successfully implemented.</label>';
89
+
90
+ }
91
+ ?>
92
+ </div>
93
+ </div>
94
+ </fieldset>
95
+ </form>
96
+ </div>
97
+ </div>
98
+ </div>