<?php
require '../session.php';
require '../log.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || !isset($_GET['url'])) {
	include '../deny.php';
}

require '../fileindex.php';

if (!is_array($index)) {
	require '/notfound.php';
}

$ignores = array('testSCORM.swf', 'favicon.ico');

$map = array(
	chr(196) => 'a',	// Ä
	chr(197) => 'a',	// Å
	chr(228) => 'a',	// ä
	chr(229) => 'a',	// å
	chr(214) => 'o',	// Ö
	chr(246) => 'o',	// ö
);

$urlCustom     = str_replace('url=', '', $_SERVER['QUERY_STRING']);
$urlCustomUtf8 = utf8_encode($urlCustom);
$url           = $_GET['url'];
$urlUtf8       = utf8_encode($_GET['url']);
$urlAscii      = strtr($url, $map);
if (!isset($index[$url])) {
	if (isset($index[$urlUtf8])) {
		$url = $urlUtf8;
	} else if (isset($index[$urlAscii])) {
		$url = $urlAscii;
	} else if (isset($index[$urlCustom])) {
		$url = $urlCustom;
	} else if (isset($index[$urlCustomUtf8])) {
		$url = $urlCustomUtf8;
	}
}

if (isset($index[$url]) && is_array($index[$url]) && isset($index[$url]['mime']) && isset($index[$url]['file'])) {
	$mime      = $index[$url]['mime'];
	$file      = $index[$url]['file'];
	$path      = dirname(__FILE__) . '/../resources';
	$extension = pathinfo($file, PATHINFO_EXTENSION);
	if ($extension === 'php') {
		include "$path/$file";
		die();
	}
	$bytes = file_get_contents("$path/$file");
	if ($extension === 'html' && isset($index[$url]['encoding'])) {
		$encoding  = $index[$url]['encoding'];
		header("Content-type: $mime; charset=$encoding");
		$bytes = str_replace('http://', '//', $bytes);
	} else {
		header("Content-type: $mime");
	}
	//$bytes = readfile("$path/$file");
        echo $bytes;
	if ($bytes === false) {
		logline("Could not read file $file");
	}
	die();
}

$filename = basename($url);
if (!in_array($filename, $ignores)) {
	$hex = bin2hex($url);
	logline("Invalid file: $url ($hex)");
}

require '../notfound.php';
