<?php
 ///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.05
// Randem Systems: https://randemsystems.support
// Transfer Files Server to Server
// Extract the zipped file to a destination
// Date: 08/01/2026
// Usage: BotBanishTransferFile.php
//
//	get_headers return array format
//
//		Array (
//			[0] => HTTP/1.1 200 OK
//			[Content-Type] => text/html; charset=UTF-8
//			[Connection] => close
//			[Date] => Sun, 19 May 2019 08:35:47 GMT
//			[Server] => Apache
//			[Strict-Transport-Security] => max-age=3600; includeSubDomains
//			[Cache-Control] => s-maxage=21600, max-age=3, must-revalidate
//			[Access-Control-Allow-Credentials] => true
//			[X-Frame-Options] => DENY
//			[X-Content-Type-Options] => nosniff
//			[Vary] => Accept-Encoding, Cookie
//			[X-Cache] => Miss from cloudfront
//			[Via] => 1.1 95d17b4d563934eb90636ad03f8f524e.cloudfront.net (CloudFront)
//			[X-Amz-Cf-Id] => se3QRyaWDeuHI3GrisMzAr4FJBamqMtbUNzhTPqAJhBoQZbWvy3UPw==
//		)
///////////////////////////////////////////////////////////////////////////////////////////////////////
		
function BotBanishDownloadFile($remote_file, $local_file, $extract_loc) {

	global $BotBanishSettings;

	@set_time_limit(600);
	
	$version = substr($BotBanishSettings['BOTBANISH_VERSION_CLIENT'], 0, 3);
	$flag = false;

	$url = 'https://randemsystems.cloud/data/botbanish/v' . $version . '/' . $remote_file;

	$file_headers = BotBanishGetHeaders($url, true);

	// Proceed only if the source file is found on remote server

	if (is_array($file_headers) && !empty($file_headers) && stripos($file_headers['Status'], '404') === false)	{

		$filesize = isset($file_headers['Content-Length']) ? $file_headers['Content-Length'] : 8192;

		// Find which download functions are available to use
		
		$on = ini_get("allow_url_fopen");

		if (!$flag && function_exists('file_get_contents') && (($on == 'on') || ($on == 1)))
			$flag = BotBanishDownloadViaDirect($url, $local_file);
		
		if (!$flag && defined('ABSPATH'))
			$flag = BotBanishDownloadViaWP($url, $local_file);

		if (!$flag && function_exists('curl_init') && function_exists('fopen'))
			$flag = BotBanishDownloadViaCURL($url, $local_file, $remote_file);
		
		if (!$flag && function_exists('ftp_connect'))
			$flag = BotBanishDownloadViaFTP($local_file, $remote_file);

		if (!$flag && function_exists('fopen'))
			$flag = BotBanishDownloadViaHTML($url, $local_file, $filesize);

		if (!$flag) {

			BotBanishLogError('Cannot download:', $local_file . ' - No Function available (cURL, fopen, ftp_connect)', 'Error');

		} else {

			clearstatcache();	// Needs this to get proper filesize after a recent write operation

			if (file_exists($local_file)) {

				if ((filesize($local_file) > 0) && ($flag == true))
					BotBanishExtract($local_file, $extract_loc);

				unlink($local_file);
			}
		}

	} else {

		$data = array('url' => $url, 'file_headers' => $file_headers, 'remote_file' => $remote_file);	
		BotBanishLogError('Cannot download:', $remote_file . ' - Connection error, No headers available' . PHP_EOL . PHP_EOL .
			'Data: ' . BotBanishFormatArray($data), 'Error');
	}

	return $flag;
}

function BotBanishDownloadViaFTP($local_file, $remote_file) {

	global $BotBanishSettings;

	BotBanishTransferTrace('BotBanishDownloadViaFTP', '', $local_file, $remote_file);

	$flag = false;

    /* Source File Name and Path */
    /* FTP Account */
    $ftp_host = 'ftp.randemsystems.cloud'; /* host */
    $ftp_user_name = 'support@randemsystems.cloud'; /* username */
    $ftp_user_pass = 'I81U812OKrj!'; /* password */

    /* Connect using basic FTP */
    $connect_it = @ftp_connect( $ftp_host );

	if (is_object($connect_it)) {
		
		/* Login to FTP */
		$flag = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

		if ($flag) {
			
			$version = substr($BotBanishSettings['BOTBANISH_VERSION_CLIENT'], 0, 3);
			$flag = ftp_chdir( $connect_it, 'public_html/data/botbanish/v' . $version . '/');
		}

		/* Download $remote_file and save to $local_file */
		if ($flag)
			$flag = ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY );

		/* Close the connection */
		if ($flag)
			$flag = ftp_close( $connect_it );
	}

	if (!$flag) {

		$error_string = 'Cannot access file: ' . $remote_file;
		BotBanishTransferTraceError('BotBanishDownloadViaFTP', $error_string);
	}

	return $flag;
}

function BotBanishDownloadViaHTML ($url, $local_file, $filesize) {

	BotBanishTransferTrace('BotBanishDownloadViaHTML', $url, $local_file, '');

	BotBanishCleanOutput();

	ob_start();
	$flag = false;

	header('Pragma: ');
	header('Content-Encoding: none');//	header('Content-type: text/html; charset=ISO-8859-1');
	header('Content-type: application/octet-stream; charset=ISO-8859-1');
	header("Content-Transfer-Encoding: Binary");
	header('Content-Length: '. $filesize);
	header('Cache-Control: no-cache');
	header("Location: " . $url);

	if ($fp = fopen($url, 'rb')) {

		ob_end_clean();

		//File to save the contents to
		$fp_out = fopen ($local_file, 'w+');

		while( !feof($fp) and (connection_status()==0) ) {

			fwrite($fp_out, fread($fp, 8192));
			flush();
		}

		@fclose($fp);
		@fclose($fp_out);

		$flag = true;

	} else {

		$error_string = 'Cannot access remote file: ' . $url;
		BotBanishTransferTraceError('BotBanishDownloadViaHTML', $error_string);
	}

	return $flag;
}

function BotBanishDownloadViaDirect($url, $local_file) {

	BotBanishTransferTrace('BotBanishDownloadViaDirect', $url, $local_file, '');

	$headers = @get_headers($url);
	
	if ($headers && str_contains($headers[0], "200 OK")) {
		
		if (isset($headers['Content-Length'])) {
			
			if ($headers['Content-Length'] > 1024 * 10)
				return false;
			
		} else {
			
			return false;
		}
	}
	
	$contents = file_get_contents($url);
	$flag = (!empty($contents)) ? file_put_contents($local_file, $contents) : false;
 
	return $flag;
}

function BotBanishDownloadViaCURL ($url, $local_file) {

	BotBanishTransferTrace('BotBanishDownloadViaCURL', $url, $local_file, '');

	set_time_limit(0);

	//File to save the contents to
	$fp = fopen ($local_file, 'w+');

	//Here is the file we are downloading, replace spaces with %20
	$ch = curl_init(str_replace(" ","%20",$url));

	curl_setopt($ch, CURLOPT_TIMEOUT, 60 * 2);
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

	$flag = curl_exec($ch);//get curl response
	curl_close($ch);

	if (!$flag) {

		$error_string = 'Cannot access file: ' . $url;
		BotBanishTransferTraceError('BotBanishDownloadViaCURL', $error_string);
	}

	return $flag;
}

function BotBanishDownloadViaWP ($url, $local_file) {

	BotBanishTransferTrace('BotBanishDownloadViaWP', $url, $local_file, '');

	$flag = false;

	if (!function_exists('download_url'))
		require_once ABSPATH . '/wp-admin/includes/file.php';

	$result = download_url($url);

/*
	// Use wp_remote_get to fetch the data
	$response = wp_remote_get($url);

	// Save the body part to a variable
	$body = $response['body'];

	$wp_filesystem = GetWPFileSystem();

	global $wp_filesystem;

	$wp_filesystem->put_contents($local_file, $body);
*/
	if (is_wp_error($result)) {

		$error_string = $result->get_error_message();
		BotBanishTransferTraceError('BotBanishDownloadViaWP', $error_string);

	} else {

		copy( $result, $local_file );
		@unlink( $result );
		$flag = true;
	}

	return $flag;
}

function GetWPFileSystem()
{
    global $wp_filesystem;

    if ( is_null( $wp_filesystem ) ) {

        require_once ABSPATH . '/wp-admin/includes/file.php';
        WP_Filesystem();
    }

    return $wp_filesystem;
}

function BotBanishExtract($filename, $destination) {

	$zip = new Zip;
	$flag = $zip->unzip_file($filename, $destination);
}

function BotBanishTransferTrace($rtn, $url, $local_file, $remote_file, $logit = false) {

	if ($logit) {
		
		$date = BotBanishGetCorrectTime();
		$filename = BotBanishSetLogFilename('Download');
		BotBanishWriteFile($filename, $date . ' - ' . $rtn . '()' . PHP_EOL . '     URL: ' . $url . PHP_EOL . '     Local: ' . $local_file . PHP_EOL . '     Remote: ' . $remote_file . PHP_EOL . PHP_EOL, true);
	}
}

function BotBanishTransferTraceError($rtn, $error) {

	$date = BotBanishGetCorrectTime();
	$filename = BotBanishSetLogFilename('Download');
	BotBanishWriteFile($filename, $date . ' - ' . $rtn . '() - Transfer Error: ' . $error . PHP_EOL, true);
}
?>