<?php

$file = base64_decode($_GET['file']);

$url = $file;

$auth = false;

if(isset($_GET['debug'])) {
	echo "####### IMG URL #######\n";
	echo $file."\n";
}
if (in_array("@", str_split($file))) {
	$auth = TRUE;
	if(isset($_GET['debug'])) {
		echo "AUTH DETECTED!\n";
		echo "CREDS: ".str_replace(array("http://", "https://"), "", explode("@", $url)[0])."\n";
		echo "URL: ".explode(":", $url)[0]."://".explode("@", $url)[1]."\n";
	}
}


$cache_file = './data/'.str_replace("=", "", base64_encode($file));

if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 2 ))) {
   	$file = file_get_contents($cache_file);
} else {
	if($auth) {
		$authpass = base64_encode(str_replace(array("http://", "https://"), "", explode("@", $url)[0]));
		$context = stream_context_create([
			"http" => [
			        "header" => "Authorization: Basic $authpass"
			]
		]);
		$file = file_get_contents(explode(":", $url)[0]."://".explode("@", $url)[1], false, $context );
	} else {
   		$file = file_get_contents($url);
	}
        if(strlen($file) < 300) {
        	if (file_exists($cache_file)) {
                        $file = file_get_contents($cache_file);
                } else {
                        die("Please try again later");
                }
        } else {
   		file_put_contents($cache_file, $file, LOCK_EX);
	}
}
if(!isset($_GET['debug'])) { header('Content-Type: image/png'); } else { echo "####### IMG DATA #######\n"; }

echo $file;