<?php
 /*
  * Script to handle default host traffic.
  * 1. IP or hostname (web00.telefuture.nl) show default page, or phpinfo() when called from office IP.
  * 2. domainname that is not a vhost will be looked up in the database and forwarded if found.
  */

$homeDomain = 'web00.telefuture.nl';
$homeIp     = gethostbyname($homeDomain);
$hostname   = str_replace('test.','',str_replace('www.','',$_SERVER['HTTP_HOST']));

if (true === in_array($_SERVER['HTTP_HOST'], [$homeDomain, $homeIp])) {
  if ($_SERVER['REMOTE_ADDR'] == '185.36.133.219') {
    phpinfo();
  } else {
    echo 'web00';
  }
} else {
  try {
    $connection = new PDO('mysql:host=localhost;dbname=flatbox_redirects;charset=utf8', 'flatbox_redirect', 'fbredi182');
  } catch(PDOException $e) {
    die('database error');
  }

  $stmt = $connection->prepare('SELECT * FROM domain_redirects WHERE domain_code = :hostname LIMIT 1');
  $stmt->execute([':hostname' => $hostname]);

  $rows = $stmt->fetchAll();
  if (count($rows) == 1) {
    $row = $rows[0];

    $stmt = $connection->prepare('INSERT INTO domain_redirect_stats VALUES(:domain_id, :date, 1) ON DUPLICATE KEY UPDATE counter=counter+1');
    $stmt->execute([':domain_id' => $row['id'], ':date' => date("Y-m-d")]);

    /* Copy GET params: */
    @$request_parts     = explode('?', $_SERVER["REQUEST_URI"]);
    @$redirect_parts    = explode('?', $row['redirect_url']);
    $row['redirect_url'] = @rtrim($redirect_parts[0],'/') . @$request_parts[0] . '?' . @$redirect_parts[1] . '&'. @$request_parts[1];

    if ($row['frame_title'] == '') {
      /* Forward / Redict */
      HEADER("Location: " . $row['redirect_url'] );
    } else {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
        <title><?=$row['frame_title']?></title>
</head>
<frameset rows="100%">
    <frame src="<?=$row['redirect_url']?>" frameborder="0" marginheight="0" marginwidth="0" />
    <noframes>
    <body>
    <?=$row['frame_body']?>
    </body>
    </noframes>
</frameset>
</html>
<?php
      exit;
    }
  } else {
    echo 'web00';
  }
}
