| 1 |
<?php |
| 2 |
|
| 3 |
namespace ISC\Admin; |
| 4 |
|
| 5 |
/** |
| 6 |
* Handle admin-related AJAX calls |
| 7 |
*/ |
| 8 |
class Admin_Ajax { |
| 9 |
|
| 10 |
/** |
| 11 |
* Constructor |
| 12 |
*/ |
| 13 |
public function __construct() { |
| 14 |
add_action( 'wp_ajax_isc_download_log', [ $this, 'download_log' ] ); |
| 15 |
} |
| 16 |
|
| 17 |
/** |
| 18 |
* Download log file via AJAX |
| 19 |
*/ |
| 20 |
public function download_log() { |
| 21 |
check_ajax_referer( 'isc-admin-ajax-nonce', 'nonce' ); |
| 22 |
|
| 23 |
if ( ! current_user_can( 'manage_options' ) ) { |
| 24 |
wp_die( 'You do not have permission to access this file.', 403 ); |
| 25 |
} |
| 26 |
|
| 27 |
$log_file_path = \ISC_Log::get_log_file_path(); |
| 28 |
|
| 29 |
if ( ! \ISC_Log::log_file_exists() ) { |
| 30 |
wp_die( 'Log file does not exist.', 404 ); |
| 31 |
} |
| 32 |
|
| 33 |
// Get file size for Content-Length header |
| 34 |
$file_size = filesize( $log_file_path ); |
| 35 |
|
| 36 |
// Clear any output buffers |
| 37 |
if ( ob_get_level() ) { |
| 38 |
ob_end_clean(); |
| 39 |
} |
| 40 |
|
| 41 |
// Set headers for file download |
| 42 |
header( 'Content-Type: text/plain; charset=utf-8' ); |
| 43 |
header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( basename( $log_file_path ) ) . '"' ); |
| 44 |
header( 'Content-Length: ' . $file_size ); |
| 45 |
header( 'Cache-Control: no-cache, must-revalidate' ); |
| 46 |
header( 'Pragma: no-cache' ); |
| 47 |
header( 'Expires: 0' ); |
| 48 |
|
| 49 |
// Output the file content. readfile is supposedly more efficient than WP_Filesystem for large files. |
| 50 |
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile |
| 51 |
readfile( $log_file_path ); |
| 52 |
|
| 53 |
die(); |
| 54 |
} |
| 55 |
} |