<?php
// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Verify nonce
if( ! empty( $_GET['action'] ) && ( 'downloadlog' == $_GET['action'] ) ) {
    if ( empty( $_REQUEST['_wpnonce'] )  ) { 
        return false;
    } 
} else {
    return false;
}
 
// Start the session
session_start();

// Get upload folder
$upload_dir 		= wp_upload_dir();
$upload_base_dir 	= $upload_dir['basedir'];
$dir_logs			= $upload_base_dir . '/youtube-automate/logs/';

// Check the file
$files  = @scandir( $dir_logs );
$result = '';

if ( ! empty( $files ) ) {
    foreach ( $files as $key => $value ) {
        if ( ! in_array( $value, array( '.', '..' ), true ) ) {
            if ( ! is_dir( $value ) && strstr( $value, '.log' ) ) {
                $result = $value;
                $filename = $dir_logs . $result;
            }
        }
    }
}

// Exit if no log file
if( empty( $result ) ) {
    return false;
}

if ( !is_file($filename) || !is_readable( $filename ) ) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
$size = filesize($filename);
 
// Close the session
session_write_close();
 
// Disable cache
header("Cache-Control: no-cache, must-revalidate");
header("Cache-Control: post-check=0,pre-check=0");
header("Cache-Control: max-age=0");
header("Pragma: no-cache");
header("Expires: 0");
 
// Force download with filename
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename="' . $result . '"');
 
// File size
header("Content-Length: " . $size);
 
// Send the file using WP_Filesystem
require_once(ABSPATH . 'wp-admin/includes/file.php');
$url = wp_nonce_url('options-general.php');
$creds = request_filesystem_credentials($url, '', false, false, null);
if (!WP_Filesystem($creds)) {
    header("HTTP/1.1 500 Internal Server Error");
    exit;
}
global $wp_filesystem;
$content = $wp_filesystem->get_contents($filename);
if ($content === false) {
    header("HTTP/1.1 404 Not Found");
    exit;
}
echo wp_kses_post( $content );
?>