<?php

function endswith($string, $test) {
    $strlen = strlen($string);
    $testlen = strlen($test);
    if ($testlen > $strlen) return false;
    return substr_compare($string, $test, -$testlen) === 0;
}



$file = getcwd() . '/papers/' . $_GET['file'];
$fileLink = '/akcheung/papers/' . $_GET['file'];

// write to log

$remoteIP = $_SERVER['REMOTE_ADDR'];
$remoteHost = gethostbyaddr($remoteIP);
//$remoteHost = $_SERVER['REMOTE_HOST'];
$time = date('Y/m/d-H:i:s');

if (strcmp($remoteIP, "200.82.186.130") != 0) {
  $log = fopen(getcwd() . '/logs/log.txt', 'a');
  fwrite($log, $time . "\t" . $remoteIP . "\t" . $remoteHost . "\t" . $_GET['file'] . "\n");
  fclose($log);
}

$filename = $_GET['file'];
$fileExists = file_exists($file);
$filenameValid = endswith($filename, 'pdf') and (preg_match('/^\w+\.txt$/', $filename) == 0);

if (! $filenameValid or ! $fileExists or strcmp($remoteIP, "200.82.186.130") == 0 )
{
  //$log = fopen(getcwd() . '/logs/log.txt', 'a');
  //fwrite($log, "request ignored\n");
  //fclose($log);

  echo "<html>";
  echo "<head><link rel=stylesheet href='/akcheung/style.css' type='test/css'></head>";
  echo "<title>Error!</title>";
  echo "<body>File does not exist.<hr><a href='/akcheung'>home</a></body>";
  echo "</html>";
}
else
{
  header("Cache-Control: no cache, must-revalidate");
  header("Pragma: no-cache");
  header("Content-type: application/pdf");
  header('Location: ' . $fileLink);
}

?>
