-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenginescript-site-exporter.php
More file actions
1863 lines (1606 loc) · 65.1 KB
/
enginescript-site-exporter.php
File metadata and controls
1863 lines (1606 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: EngineScript Site Exporter
* Description: Exports the site files and database as a zip archive.
* Version: 2.0.0
* Author: EngineScript
* Requires at least: 6.5
* Tested up to: 6.9
* Requires PHP: 7.4
* License: GPL-3.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
* Text Domain: enginescript-site-exporter
* Domain Path: /languages
*
* @package EngineScript_Site_Exporter
*/
// Prevent direct access. Note: Using return here instead of exit.
if ( ! defined( 'ABSPATH' ) ) {
return; // Prevent direct access.
}
// Define plugin version.
if ( ! defined( 'ES_SITE_EXPORTER_VERSION' ) ) {
define( 'ES_SITE_EXPORTER_VERSION', '2.0.0' );
}
// Define allowed file extensions for export operations.
if ( ! defined( 'SSE_ALLOWED_EXTENSIONS' ) ) {
define( 'SSE_ALLOWED_EXTENSIONS', array( 'zip', 'sql' ) );
}
// Define export directory name used across the plugin.
if ( ! defined( 'SSE_EXPORT_DIR_NAME' ) ) {
define( 'SSE_EXPORT_DIR_NAME', 'enginescript-site-exporter-exports' );
}
/**
* WordPress Core Classes Documentation
*
* This plugin uses WordPress core classes which are automatically available
* in the WordPress environment. These classes don't require explicit imports
* or use statements as they are part of WordPress core.
*
* Core classes used:
*
* @see WP_Error - WordPress error handling class
* @see ZipArchive - PHP ZipArchive class
* @see RecursiveIteratorIterator - PHP SPL iterator
* @see RecursiveDirectoryIterator - PHP SPL directory iterator
* @see SplFileInfo - PHP SPL file information class
* @see Exception - PHP base exception class
*
* @SuppressWarnings(PHPMD.MissingImport)
* @SuppressWarnings(PHPMD.ExcessiveClassLength) - Single file WordPress plugin architecture
*/
/**
* Safely get client IP address.
*
* @return string Client IP address or 'unknown' if not available.
*/
function sse_get_client_ip() {
// WordPress-style IP detection with validation.
$client_ip = 'unknown';
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- $_SERVER['REMOTE_ADDR'] is safe for IP logging when properly sanitized
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
$client_ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
}
// Basic IP validation.
if ( filter_var( $client_ip, FILTER_VALIDATE_IP ) !== false ) {
return $client_ip;
}
return 'unknown';
} // end sse_get_client_ip()
/**
* Stores important log messages in database for review.
*
* @param string $message The log message.
* @param string $level The log level.
* @return void
*/
function sse_store_log_in_database( $message, $level ) {
// Store last 20 important messages in an option.
$logs = get_option( 'sse_error_logs', [] );
$logs[] = [
'time' => time(),
'level' => $level,
'message' => $message,
'user_id' => get_current_user_id(),
'ip' => sse_get_client_ip(),
];
// Keep only the most recent 20 logs.
if ( count( $logs ) > 20 ) {
$logs = array_slice( $logs, -20 );
}
update_option( 'sse_error_logs', $logs, false );
} // end sse_store_log_in_database()
/**
* Outputs log message to WordPress debug log or error_log.
*
* @param string $formatted_message The formatted log message.
* @return void
*/
function sse_output_log_message( $formatted_message ) {
// Use WordPress logging (wp_debug_log is available in WP 5.1+).
if ( function_exists( 'wp_debug_log' ) ) {
wp_debug_log( $formatted_message );
}
} // end sse_output_log_message()
/**
* Safely log plugin messages
*
* @param string $message The message to log.
* @param string $level The log level (error, warning, info).
* @return void
*/
function sse_log( $message, $level = 'info' ) {
// Check if WP_DEBUG is enabled.
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
return;
}
// Format the message with a timestamp (using GMT to avoid timezone issues).
$formatted_message = sprintf(
'[%s] [%s] %s: %s',
gmdate( 'Y-m-d H:i:s' ),
'EngineScript Site Exporter',
strtoupper( $level ),
$message
);
// Only log if debug logging is enabled.
if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG ) {
return;
}
sse_output_log_message( $formatted_message );
// Store logs in the database (errors and security events to prevent issues).
if ( 'error' === $level || 'security' === $level ) {
sse_store_log_in_database( $message, $level );
}
} // end sse_log()
/**
* Safely get the PHP execution time limit.
*
* @return int Current PHP execution time limit in seconds.
*/
function sse_get_execution_time_limit() {
// Get the current execution time limit.
$max_exec_time = ini_get( 'max_execution_time' );
// Handle all possible return types from ini_get().
if ( false === $max_exec_time ) {
// Ini_get failed.
return 30;
}
if ( '' === $max_exec_time ) {
// Empty string returned.
return 30;
}
if ( ! is_numeric( $max_exec_time ) ) {
// Non-numeric value returned.
return 30;
}
return (int) $max_exec_time;
} // end sse_get_execution_time_limit()
// --- Admin Menu ---
/**
* Adds the Site Exporter page to the WordPress admin menu.
*
* @return void
*/
function sse_admin_menu() {
add_management_page(
__( 'EngineScript Site Exporter', 'enginescript-site-exporter' ), // Page title (escaped by WordPress core).
__( 'Site Exporter', 'enginescript-site-exporter' ), // Menu title (escaped by WordPress core).
'manage_options', // Capability required.
'enginescript-site-exporter',
'sse_exporter_page_html'
);
}
/**
* Initialize the EngineScript Site Exporter plugin.
*
* This function is hooked to 'plugins_loaded' to ensure that all other plugins
* and WordPress core functions are available before initializing this plugin.
* This prevents load order issues and conflicts with other plugins.
*
* @since 1.8.5
* @return void
*/
function sse_init_plugin() {
// Hook admin menu creation.
add_action( 'admin_menu', 'sse_admin_menu' );
// Hook export handler.
add_action( 'admin_init', 'sse_handle_export' );
// Hook scheduled deletion handler.
add_action( 'sse_delete_export_file', 'sse_delete_export_file_handler' );
// Hook bulk cleanup handler.
add_action( 'sse_bulk_cleanup_exports', 'sse_bulk_cleanup_exports_handler' );
// Hook secure download handler.
add_action( 'admin_init', 'sse_handle_secure_download' );
// Hook export deletion handler.
add_action( 'admin_init', 'sse_handle_export_deletion' );
}
// Initialize the plugin when all plugins are loaded.
add_action( 'plugins_loaded', 'sse_init_plugin' );
// --- Exporter Page HTML ---
/**
* Renders the exporter page HTML interface.
*
* @return void
*/
function sse_exporter_page_html() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to view this page.', 'enginescript-site-exporter' ), 403 );
}
$upload_dir = wp_upload_dir();
if ( empty( $upload_dir['basedir'] ) ) {
wp_die( esc_html__( 'Could not determine the WordPress upload directory.', 'enginescript-site-exporter' ) );
}
$export_dir_name = SSE_EXPORT_DIR_NAME;
$export_dir_path = trailingslashit( $upload_dir['basedir'] ) . SSE_EXPORT_DIR_NAME;
$display_path = str_replace( ABSPATH, '', $export_dir_path );
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_html() used for proper escaping ?></h1>
<?php
// Display deletion feedback notices from redirect. phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only parameter, no state change.
if ( isset( $_GET['sse_notice'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$sse_notice_type = sanitize_key( $_GET['sse_notice'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( 'deleted' === $sse_notice_type ) {
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Export file successfully deleted.', 'enginescript-site-exporter' ) . '</p></div>';
} elseif ( 'delete_failed' === $sse_notice_type ) {
echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Failed to delete export file.', 'enginescript-site-exporter' ) . '</p></div>';
}
}
?>
<p><?php esc_html_e( 'Click the button below to generate a zip archive containing your WordPress files and a database dump (.sql file).', 'enginescript-site-exporter' ); ?></p>
<p><strong><?php esc_html_e( 'Warning:', 'enginescript-site-exporter' ); ?></strong> <?php esc_html_e( 'This can take a long time and consume significant server resources, especially on large sites. Ensure your server has sufficient disk space and execution time.', 'enginescript-site-exporter' ); ?></p>
<p style="margin-top: 15px;">
<?php
// printf is standard in WordPress for translatable strings with placeholders. All variables are escaped.
printf(
// translators: %s: directory path.
esc_html__( 'Exported .zip files will be saved in the following directory on the server: %s', 'enginescript-site-exporter' ),
'<code>' . esc_html( $display_path ) . '</code>'
);
?>
</p>
<form method="post" action="" style="margin-top: 15px;">
<?php wp_nonce_field( 'sse_export_action', 'sse_export_nonce' ); ?>
<input type="hidden" name="action" value="sse_export_site">
<table class="form-table" style="margin-bottom: 20px;">
<tbody>
<tr>
<th scope="row">
<label for="sse_max_file_size"><?php esc_html_e( 'Maximum File Size', 'enginescript-site-exporter' ); ?></label>
</th>
<td>
<select name="sse_max_file_size" id="sse_max_file_size">
<option value="0"><?php esc_html_e( 'No limit (include all files)', 'enginescript-site-exporter' ); ?></option>
<option value="104857600"><?php esc_html_e( '100 MB', 'enginescript-site-exporter' ); ?></option>
<option value="524288000"><?php esc_html_e( '500 MB', 'enginescript-site-exporter' ); ?></option>
<option value="1073741824"><?php esc_html_e( '1 GB', 'enginescript-site-exporter' ); ?></option>
</select>
<p class="description">
<?php esc_html_e( 'Files larger than this size will be excluded from the export. Choose "No limit" to include all files regardless of size.', 'enginescript-site-exporter' ); ?>
</p>
</td>
</tr>
</tbody>
</table>
<?php submit_button( __( 'Export Site', 'enginescript-site-exporter' ) ); ?>
</form>
<hr>
<p>
<?php esc_html_e( 'This plugin is part of the EngineScript project.', 'enginescript-site-exporter' ); ?>
<a href="https://github.com/EngineScript/EngineScript" target="_blank" rel="noopener noreferrer">
<?php esc_html_e( 'Visit the EngineScript GitHub page', 'enginescript-site-exporter' ); ?>
</a>
</p>
<p style="color: #b94a48; font-weight: bold;">
<?php esc_html_e( 'Important:', 'enginescript-site-exporter' ); ?>
<?php esc_html_e( 'The exported zip file is publicly accessible while it remains in the above directory. For security, you should remove the exported file from the server once you are finished downloading it.', 'enginescript-site-exporter' ); ?>
</p>
<p style="color: #b94a48; font-weight: bold;">
<?php esc_html_e( 'Security Notice:', 'enginescript-site-exporter' ); ?>
<?php esc_html_e( 'For your protection, the exported zip file will be automatically deleted from the server 5 minutes after it is created.', 'enginescript-site-exporter' ); ?>
</p>
</div>
<?php
}
// --- Handle Export Action ---
/**
* Handles the site export process when the form is submitted.
*
* @return void
*/
function sse_handle_export() {
if ( ! sse_validate_export_request() ) {
return;
}
// Check for and set an export lock.
if ( get_transient( 'sse_export_lock' ) ) {
sse_show_error_notice( __( 'An export process is already running. Please wait for it to complete before starting a new one.', 'enginescript-site-exporter' ) );
return;
}
// Set lock with a 1-hour expiration to prevent permanent locks on failure.
set_transient( 'sse_export_lock', time(), HOUR_IN_SECONDS );
try {
sse_prepare_execution_environment();
$export_paths = sse_setup_export_directories();
if ( is_wp_error( $export_paths ) ) {
sse_show_error_notice( $export_paths->get_error_message() );
return;
}
$database_file = sse_export_database( $export_paths['export_dir'] );
if ( is_wp_error( $database_file ) ) {
sse_show_error_notice( $database_file->get_error_message() );
return;
}
$zip_result = sse_create_site_archive( $export_paths, $database_file );
if ( is_wp_error( $zip_result ) ) {
sse_cleanup_files( array( $database_file['filepath'] ) );
sse_show_error_notice( $zip_result->get_error_message() );
return;
}
sse_cleanup_files( array( $database_file['filepath'] ) );
// Test cron scheduling capability before attempting real scheduling.
sse_test_cron_scheduling();
sse_schedule_export_cleanup( $zip_result['filepath'] );
// Schedule a bulk cleanup sweep in case individual files were missed.
sse_schedule_bulk_cleanup();
sse_show_success_notice( $zip_result );
} finally {
// Always release the lock and clean up user preferences.
delete_transient( 'sse_export_lock' );
delete_transient( 'sse_export_max_file_size_' . get_current_user_id() );
}
}
/**
* Validates the export request for security and permissions.
*
* @return bool True if request is valid, false otherwise.
*/
function sse_validate_export_request() { // phpcs:ignore WordPress.Security.NonceVerification.Missing
$post_action = isset( $_POST['action'] ) ? sanitize_key( $_POST['action'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification happens below
if ( 'sse_export_site' !== $post_action ) {
return false;
}
$post_nonce = isset( $_POST['sse_export_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['sse_export_nonce'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- This line retrieves nonce for verification
if ( ! $post_nonce || ! wp_verify_nonce( $post_nonce, 'sse_export_action' ) ) {
wp_die( esc_html__( 'Nonce verification failed! Please try again.', 'enginescript-site-exporter' ), 403 );
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'enginescript-site-exporter' ), 403 );
}
// Store the user's max file size selection for use during export.
$max_file_size = isset( $_POST['sse_max_file_size'] ) ? absint( $_POST['sse_max_file_size'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above
set_transient( 'sse_export_max_file_size_' . get_current_user_id(), $max_file_size, HOUR_IN_SECONDS );
return true;
} // end sse_validate_export_request()
/**
* Prepares the execution environment for export operations.
*
* @return void
*/
function sse_prepare_execution_environment() {
$max_exec_time = sse_get_execution_time_limit();
$target_exec_time = 1800; // 30 minutes in seconds.
if ( $max_exec_time > 0 && $max_exec_time < $target_exec_time ) {
// Note: set_time_limit() is discouraged in WordPress plugins.
// Users should configure execution time limits at the server level.
sse_log( "Current execution time limit ({$max_exec_time}s) may be insufficient for large exports. Consider increasing server limits.", 'warning' );
return;
}
sse_log( 'Execution time limit appears adequate for export operations', 'info' );
} // end sse_prepare_execution_environment()
/**
* Sets up export directories and returns path information.
*
* @return array|WP_Error Array of paths on success, WP_Error on failure.
*/
function sse_setup_export_directories() {
$upload_dir = wp_upload_dir();
if ( empty( $upload_dir['basedir'] ) || empty( $upload_dir['baseurl'] ) ) {
return new WP_Error( 'upload_dir_error', __( 'Could not determine the WordPress upload directory or URL.', 'enginescript-site-exporter' ) );
}
$export_dir_name = SSE_EXPORT_DIR_NAME;
$export_dir = trailingslashit( $upload_dir['basedir'] ) . SSE_EXPORT_DIR_NAME;
$export_url = trailingslashit( $upload_dir['baseurl'] ) . $export_dir_name;
if ( ! wp_mkdir_p( $export_dir ) && ! is_dir( $export_dir ) ) {
sse_log( 'Failed to create export directory at path: ' . $export_dir, 'error' );
return new WP_Error( 'export_dir_creation_failed', __( 'Could not create the export directory. Please verify filesystem permissions.', 'enginescript-site-exporter' ) );
}
global $wp_filesystem;
if ( ! $wp_filesystem ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
if ( ! WP_Filesystem() ) {
sse_log( 'Failed to initialize WordPress filesystem API', 'error' );
return new WP_Error( 'filesystem_init_failed', __( 'Failed to initialize WordPress filesystem API.', 'enginescript-site-exporter' ) );
}
}
if ( ! $wp_filesystem->is_writable( $export_dir ) ) {
sse_log( 'Export directory is not writable: ' . $export_dir, 'error' );
return new WP_Error( 'export_dir_not_writable', __( 'The export directory is not writable. Please adjust filesystem permissions.', 'enginescript-site-exporter' ) );
}
sse_create_index_file( $export_dir );
return array(
'export_dir' => $export_dir,
'export_url' => $export_url,
'export_dir_name' => $export_dir_name,
);
}
/**
* Creates an index.php file in the export directory to prevent directory listing.
*
* @param string $export_dir The export directory path.
*/
function sse_create_index_file( $export_dir ) {
$index_file_path = trailingslashit( $export_dir ) . 'index.php';
if ( file_exists( $index_file_path ) ) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_exists_file_exists -- Checking controlled export directory
return;
}
global $wp_filesystem;
if ( ! $wp_filesystem ) {
require_once ABSPATH . 'wp-admin/includes/file.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- WordPress core filesystem API
if ( ! WP_Filesystem() ) {
sse_log( 'Failed to initialize WordPress filesystem API', 'error' );
return;
}
}
if ( $wp_filesystem && $wp_filesystem->is_writable( $export_dir ) ) {
$wp_filesystem->put_contents(
$index_file_path,
'<?php // Silence is golden.',
FS_CHMOD_FILE
);
return;
}
sse_log( 'Failed to write index.php file or directory not writable: ' . $export_dir, 'error' );
}
/**
* Finds a safe path to the WP-CLI executable.
*
* @return string|WP_Error The path to WP-CLI on success, or a WP_Error on failure.
*/
function sse_get_safe_wp_cli_path() {
// Check for WP-CLI in common paths.
$common_paths = array(
ABSPATH . 'wp-cli.phar',
dirname( ABSPATH ) . '/wp-cli.phar',
'/usr/local/bin/wp',
'/usr/bin/wp',
);
foreach ( $common_paths as $path ) {
if ( is_executable( $path ) ) {
return $path;
}
}
// Check if 'wp' is in the system's PATH.
// Use 'where' for Windows and 'command -v' for Unix-like systems.
if ( function_exists( 'shell_exec' ) ) {
$command = ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' ) ? 'where wp' : 'command -v wp';
$path = shell_exec( $command ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_shell_exec -- Safe command to find executable.
if ( ! empty( $path ) ) {
$trimmed = trim( $path );
// Additional verification: ensure resolved path exists and is executable (defense-in-depth).
if ( file_exists( $trimmed ) && is_executable( $trimmed ) ) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_exists_file_exists -- Controlled path verification
return $trimmed;
}
}
}
return new WP_Error( 'wp_cli_not_found', __( 'WP-CLI executable not found. Please ensure it is installed and in your server\'s PATH.', 'enginescript-site-exporter' ) );
}
/**
* Exports the database and returns file information.
*
* @param string $export_dir The directory to save the database dump.
* @return array|WP_Error Array with file info on success, WP_Error on failure.
*/
function sse_export_database( $export_dir ) {
$site_name = sanitize_file_name( get_bloginfo( 'name' ) );
$timestamp = gmdate( 'Y-m-d_H-i-s' );
$db_filename = "db_dump_{$site_name}_{$timestamp}.sql";
$db_filepath = trailingslashit( $export_dir ) . $db_filename;
if ( ! function_exists( 'shell_exec' ) ) {
return new WP_Error( 'shell_exec_disabled', __( 'shell_exec function is disabled on this server.', 'enginescript-site-exporter' ) );
}
// Enhanced WP-CLI path validation.
$wp_cli_path = sse_get_safe_wp_cli_path();
if ( is_wp_error( $wp_cli_path ) ) {
return $wp_cli_path;
}
// Only append --allow-root if we are actually running as root (hardening).
$allow_root_flag = '';
if ( function_exists( 'posix_geteuid' ) ) {
$uid = posix_geteuid();
if ( false !== $uid && 0 === $uid ) {
$allow_root_flag = ' --allow-root';
}
}
$command = sprintf(
'%s db export %s --path=%s%s',
escapeshellarg( $wp_cli_path ), // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.escapeshellarg_escapeshellarg -- Required for shell command security
escapeshellarg( $db_filepath ), // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.escapeshellarg_escapeshellarg -- Required for shell command security
escapeshellarg( ABSPATH ), // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.escapeshellarg_escapeshellarg -- Required for shell command security
$allow_root_flag
);
$output = shell_exec( $command . ' 2>&1' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_shell_exec -- Required for WP-CLI database export: all parameters are validated and escaped with escapeshellarg()
if ( ! file_exists( $db_filepath ) || filesize( $db_filepath ) <= 0 ) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_exists_file_exists -- Validating WP-CLI export success
// Sanitize WP-CLI output to avoid leaking absolute paths or sensitive data.
$safe_output = '';
if ( ! empty( $output ) ) {
$lines = array_slice( preg_split( '/\r?\n/', $output ), 0, 5 ); // Limit to first 5 lines.
$lines = array_map(
static function ( $line ) {
// Remove absolute paths (rudimentary) and collapse whitespace.
$line = preg_replace( '#(/|[A-Za-z]:\\\\)[^\s]+#', '[path]', $line );
$line = preg_replace( '/\s+/', ' ', $line );
return trim( $line );
},
$lines
);
$safe_output = implode( ' | ', $lines );
}
$error_message = $safe_output ? $safe_output : 'WP-CLI command failed silently.';
return new WP_Error( 'db_export_failed', $error_message );
}
sse_log( 'Database export successful', 'info' );
return array(
'filename' => $db_filename,
'filepath' => $db_filepath,
);
}
/**
* Creates a site archive with database and files.
*
* @param array $export_paths Export directory paths.
* @param array $database_file Database file information.
* @return array|WP_Error Archive info on success, WP_Error on failure.
*/
function sse_create_site_archive( $export_paths, $database_file ) {
if ( ! class_exists( 'ZipArchive' ) ) {
return new WP_Error( 'zip_not_available', __( 'ZipArchive class is not available on your server. Cannot create zip file.', 'enginescript-site-exporter' ) );
}
$site_name = sanitize_file_name( get_bloginfo( 'name' ) );
$timestamp = gmdate( 'Y-m-d_H-i-s' );
$random_str = substr( bin2hex( random_bytes( 4 ) ), 0, 7 );
$zip_filename = "site_export_sse_{$random_str}_{$site_name}_{$timestamp}.zip";
$zip_filepath = trailingslashit( $export_paths['export_dir'] ) . $zip_filename;
$zip = new ZipArchive();
if ( $zip->open( $zip_filepath, ZipArchive::CREATE | ZipArchive::OVERWRITE ) !== true ) {
return new WP_Error(
'zip_create_failed',
sprintf(
/* translators: %s: filename */
__( 'Could not create zip file at %s', 'enginescript-site-exporter' ),
basename( $zip_filepath ) // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_basename -- Safe usage: $zip_filepath is constructed from controlled inputs (WordPress upload dir + sanitized filename), not user input.
)
);
}
// Add database dump to zip.
if ( ! $zip->addFile( $database_file['filepath'], $database_file['filename'] ) ) {
$zip->close();
return new WP_Error( 'zip_db_add_failed', __( 'Failed to add database file to zip archive.', 'enginescript-site-exporter' ) );
}
$file_result = sse_add_wordpress_files_to_zip( $zip, $export_paths['export_dir'] );
if ( is_wp_error( $file_result ) ) {
$zip->close();
return $file_result;
}
$zip_close_status = $zip->close();
if ( ! $zip_close_status || ! file_exists( $zip_filepath ) ) {
return new WP_Error( 'zip_finalize_failed', __( 'Failed to finalize or save the zip archive after processing files.', 'enginescript-site-exporter' ) );
}
sse_log( 'Site archive created successfully: ' . $zip_filepath, 'info' );
return array(
'filename' => $zip_filename,
'filepath' => $zip_filepath,
);
}
/**
* Adds WordPress files to the zip archive.
*
* @param ZipArchive $zip The zip archive object.
* @param string $export_dir The export directory to exclude.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function sse_add_wordpress_files_to_zip( $zip, $export_dir ) {
$source_path = realpath( ABSPATH );
if ( ! $source_path ) {
sse_log( 'Could not resolve real path for ABSPATH. Using ABSPATH directly.', 'warning' );
$source_path = ABSPATH;
}
try {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( $source_path, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ( $files as $file_info ) {
sse_process_file_for_zip( $zip, $file_info, $source_path, $export_dir );
}
} catch ( Exception $e ) {
return new WP_Error(
'file_iteration_failed',
sprintf(
/* translators: %s: error message */
__( 'Error during file processing: %s', 'enginescript-site-exporter' ),
$e->getMessage()
)
);
}
return true;
}
/**
* Process a single file for addition to ZIP archive.
*
* @param ZipArchive $zip ZIP archive object.
* @param SplFileInfo $file_info File information object.
* @param string $source_path Source directory path.
* @param string $export_dir Export directory to exclude.
* @return true|null True on success, null if skipped.
*/
function sse_process_file_for_zip( $zip, $file_info, $source_path, $export_dir ) {
if ( ! $file_info->isReadable() ) {
sse_log( 'Skipping unreadable file/dir: ' . $file_info->getPathname(), 'warning' );
return null;
}
$file = $file_info->getRealPath();
$pathname = $file_info->getPathname();
$relative_path = ltrim( substr( $pathname, strlen( $source_path ) ), '/' );
if ( empty( $relative_path ) ) {
return null;
}
if ( sse_should_exclude_file( $pathname, $relative_path, $export_dir, $file_info ) ) {
return null;
}
return sse_add_file_to_zip( $zip, $file_info, $file, $pathname, $relative_path );
}
/**
* Adds a file or directory to the zip archive.
*
* @param ZipArchive $zip The zip archive object.
* @param SplFileInfo $file_info File information object.
* @param string|false $file Real file path or false if getRealPath() failed.
* @param string $pathname Original pathname.
* @param string $relative_path Relative path in archive.
* @return true
*/
function sse_add_file_to_zip( $zip, $file_info, $file, $pathname, $relative_path ) {
if ( $file_info->isDir() ) {
if ( ! $zip->addEmptyDir( $relative_path ) ) {
sse_log( 'Failed to add directory to zip: ' . $relative_path, 'error' );
}
return true;
}
if ( $file_info->isFile() ) {
// Use real path (getRealPath() must succeed for security).
if ( false === $file ) {
sse_log( 'Skipping file with unresolvable real path: ' . $pathname, 'warning' );
return true; // Skip this file but continue processing.
}
$file_to_add = $file;
if ( ! $zip->addFile( $file_to_add, $relative_path ) ) {
sse_log( 'Failed to add file to zip: ' . $relative_path . ' (Source: ' . $file_to_add . ')', 'error' );
}
}
return true;
}
/**
* Determines if a file should be excluded from the export.
*
* @param string $pathname The full pathname.
* @param string $relative_path The relative path.
* @param string $export_dir The export directory to exclude.
* @param SplFileInfo $file_info File information object.
* @return bool True if file should be excluded.
*/
function sse_should_exclude_file( $pathname, $relative_path, $export_dir, $file_info ) {
// Exclude export directory.
if ( strpos( $pathname, $export_dir ) === 0 ) {
return true;
}
// Exclude cache and temporary directories.
if ( preg_match( '#^wp-content/(cache|upgrade|temp)/#', $relative_path ) ) {
return true;
}
// Exclude version control and system files.
if ( preg_match( '#(^|/)\.(git|svn|hg|DS_Store|htaccess|user\.ini)$#i', $relative_path ) ) {
return true;
}
// Exclude files based on size.
if ( $file_info->isFile() ) {
// Cache the max file size to avoid repeated transient/filter lookups per file.
static $cached_max_file_size = null;
if ( null === $cached_max_file_size ) {
$user_max_file_size = get_transient( 'sse_export_max_file_size_' . get_current_user_id() );
/**
* Filters the maximum allowed file size for inclusion in the export.
*
* @since 1.8.5
*
* @param int $max_file_size Maximum file size in bytes. Default is user's selection or 0 (no limit).
*/
$cached_max_file_size = (int) apply_filters( 'sse_max_file_size_for_export', $user_max_file_size ? $user_max_file_size : 0 );
}
if ( $cached_max_file_size > 0 && $file_info->getSize() > $cached_max_file_size ) {
sse_log( 'Excluding large file: ' . $pathname . ' (Size: ' . size_format( $file_info->getSize() ) . ', Limit: ' . size_format( $cached_max_file_size ) . ')', 'info' );
return true;
}
}
return false;
}
/**
* Shows an error notice to the user.
*
* @param string $message The error message to display.
*/
function sse_show_error_notice( $message ) {
add_action(
'admin_notices',
function () use ( $message ) {
?>
<div class="notice notice-error is-dismissible">
<p><?php echo esc_html( $message ); ?></p>
</div>
<?php
}
);
sse_log( 'Export error: ' . $message, 'error' );
}
/**
* Shows a success notice to the user.
*
* @param array $zip_result The zip file information.
*/
function sse_show_success_notice( $zip_result ) {
add_action(
'admin_notices',
function () use ( $zip_result ) {
$download_url = add_query_arg(
array(
'sse_secure_download' => $zip_result['filename'],
'sse_download_nonce' => wp_create_nonce( 'sse_secure_download' ),
),
admin_url()
);
$delete_url = add_query_arg(
array(
'sse_delete_export' => $zip_result['filename'],
'sse_delete_nonce' => wp_create_nonce( 'sse_delete_export' ),
),
admin_url()
);
$display_zip_path = str_replace( ABSPATH, '[wp-root]/', $zip_result['filepath'] );
$display_zip_path = preg_replace( '|/+|', '/', $display_zip_path );
?>
<div class="notice notice-success is-dismissible">
<p>
<?php esc_html_e( 'Site export successfully created!', 'enginescript-site-exporter' ); ?>
<a href="<?php echo esc_url( $download_url ); ?>" class="button" style="margin-left: 10px;">
<?php esc_html_e( 'Download Export File', 'enginescript-site-exporter' ); ?>
</a>
<a href="<?php echo esc_url( $delete_url ); ?>" class="button button-secondary" style="margin-left: 10px;" onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this export file?', 'enginescript-site-exporter' ); ?>');">
<?php esc_html_e( 'Delete Export File', 'enginescript-site-exporter' ); ?>
</a>
</p>
<p><small>
<?php
printf(
/* translators: %s: file path */
esc_html__( 'File location: %s', 'enginescript-site-exporter' ),
'<code title="' . esc_attr__( 'Path is relative to WordPress root directory', 'enginescript-site-exporter' ) . '">' .
esc_html( $display_zip_path ) . '</code>'
);
?>
</small></p>
</div>
<?php
}
);
sse_log( 'Export successful. File saved to ' . $zip_result['filepath'], 'info' );
}
/**
* Cleans up temporary files.
*
* @param array $files Array of file paths to delete.
*/
function sse_cleanup_files( $files ) {
foreach ( $files as $file ) {
if ( file_exists( $file ) ) {
sse_safely_delete_file( $file );
sse_log( 'Cleaned up temporary file: ' . $file, 'info' );
}
}
}
/**
* Schedules cleanup of export files.
*
* @param string $zip_filepath The zip file path to schedule for deletion.
*/
function sse_schedule_export_cleanup( $zip_filepath ) {
sse_log( 'Attempting to schedule deletion for: ' . $zip_filepath, 'info' );
// Check if already scheduled.
$already_scheduled = wp_next_scheduled( 'sse_delete_export_file', array( $zip_filepath ) );
if ( $already_scheduled ) {
sse_log( 'Export file deletion already scheduled for ' . gmdate( 'Y-m-d H:i:s', $already_scheduled ) . ' GMT: ' . $zip_filepath, 'info' );
return;
}
// Schedule the deletion.
$scheduled_time = time() + ( 5 * 60 );
sse_log( 'Attempting to schedule for: ' . gmdate( 'Y-m-d H:i:s', $scheduled_time ) . ' GMT', 'info' );
$result = wp_schedule_single_event( $scheduled_time, 'sse_delete_export_file', array( $zip_filepath ) );
if ( false === $result ) {
sse_log( 'wp_schedule_single_event returned false - scheduling failed: ' . $zip_filepath, 'error' );
// Additional debugging.
$cron_disabled = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON;
sse_log( 'DISABLE_WP_CRON status: ' . ( $cron_disabled ? 'true' : 'false' ), 'info' );
// Check if we can get cron array.
$cron_array = _get_cron_array();
if ( empty( $cron_array ) ) {
sse_log( 'WordPress cron array is empty', 'warning' );
} else {
sse_log( 'WordPress cron array exists with ' . count( $cron_array ) . ' entries', 'info' );
}
} else {
sse_log( 'Export file deletion scheduled successfully for ' . gmdate( 'Y-m-d H:i:s', $scheduled_time ) . ' GMT: ' . $zip_filepath, 'info' );
// Verify it was actually scheduled.
$verify_scheduled = wp_next_scheduled( 'sse_delete_export_file', array( $zip_filepath ) );
if ( $verify_scheduled ) {
sse_log( 'Verification: Event confirmed scheduled for ' . gmdate( 'Y-m-d H:i:s', $verify_scheduled ) . ' GMT', 'info' );
} else {
sse_log( 'Verification: Event NOT found in cron schedule despite success return!', 'error' );
}
}
}
/**
* Test function to verify WordPress cron scheduling is working.
* Can be called manually to test the scheduling system.
*/
function sse_test_cron_scheduling() {
sse_log( 'Testing WordPress cron scheduling capability...', 'info' );
// Test with a simple event.
$test_time = time() + 60; // 1 minute from now.
$test_result = wp_schedule_single_event( $test_time, 'sse_test_cron_event' );
if ( false === $test_result ) {
sse_log( 'Test cron scheduling FAILED - wp_schedule_single_event returned false', 'error' );
return false;
}
// Verify it was scheduled.
$verify_test = wp_next_scheduled( 'sse_test_cron_event' );
if ( $verify_test ) {
sse_log( 'Test cron scheduling SUCCESS - event scheduled for ' . gmdate( 'Y-m-d H:i:s', $verify_test ) . ' GMT', 'info' );
// Clean up the test event.
wp_unschedule_event( $verify_test, 'sse_test_cron_event' );
sse_log( 'Test event cleaned up', 'info' );
return true;
} else {
sse_log( 'Test cron scheduling FAILED - event not found after scheduling', 'error' );
return false;
}
}
/**
* Schedules a bulk cleanup of all export files in the upload directory.
* This runs as a safety net to catch any files that individual cleanup missed.
*/
function sse_schedule_bulk_cleanup() {
// Only schedule if not already scheduled.
if ( ! wp_next_scheduled( 'sse_bulk_cleanup_exports' ) ) {
// Schedule bulk cleanup for 10 minutes from now (after individual files should be cleaned up).
$scheduled_time = time() + ( 10 * 60 );
$result = wp_schedule_single_event( $scheduled_time, 'sse_bulk_cleanup_exports' );
if ( $result ) {
sse_log( 'Bulk export cleanup scheduled for ' . gmdate( 'Y-m-d H:i:s', $scheduled_time ) . ' GMT', 'info' );
} else {
sse_log( 'Failed to schedule bulk export cleanup', 'error' );
}
} else {
sse_log( 'Bulk export cleanup already scheduled', 'info' );
}
}