<?php

/**

	This script is used by forward hostingplans to redirect to the given URL
	If all else fails we show an iframe which shows the registration page

*/

	$oldErrorHandler = set_error_handler("myErrorHandler"); // set to the user defined error handler

	$domain = getDomainFromHTTPHost(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); // get domain

	try {
		$db = new PDO('mysql:dbname=server;host=localhost', "c2_fwd4", "xWB0nTwb4Py7");
	} catch (Exception $e) {
		$db = false;
	}

	if ( ! $db) { // no database connection!
		/*$html = array(
			'html' => '<html><body><h1>Service Unavailable</h1></body></html>',
			'headers' => array("HTTP/1.1 503 Service Unavailable"),
		);*/
		$html = getRegistrationPage($domain);
	}
	else {
		$html = processRequest($db, $domain);
	}

	foreach ($html['headers'] as $header) { // output headers
		header($header);
	}

	if ($html['html']!='') { // output html
		echo $html['html'];
	}

	exit();

/**

	-- DONE --

*/

/**
 * processRequest processes forward (as iframe or redirect) or registration request
 *
 * @param resource pdo db connection
 * @param string domain
 * @return array html[html, headers]
 */
function processRequest($db, $domain) {

	$sth = $db->prepare("SELECT * FROM `forwards` WHERE `domain` = ? LIMIT 1");
	$sth->execute(array($domain));
	$count = $sth->rowCount();

	if($count > 0) { // domain found
		$row = $sth->fetch(PDO::FETCH_ASSOC);

		switch ($row['fwd_frame']) {
			case '1': # frame
				$html = getFramesPage($row);
				break;
			case '0': # no frame
			case '': # no frame
			default:
				$html = getForwardPage($row);
				break;
		}
	}
	else { // no domain found: show registration page
		$html = getRegistrationPage($domain);
	}

	return $html;
}

/**
 * Custom error handler
 *
 * @param int errno
 * @param string errstr
 * @param string errfile
 * @param int errline
 */
function myErrorHandler($errno, $errstr, $errfile, $errline) {
	$replevel = error_reporting(); // if reporting level was decreased then do not fail
	if( ( $errno & $replevel ) != $errno ) { 
		return; // we shall remain quiet
	} 

	$errortype = array (
		1    =>  "Error",
		2    =>  "Warning",
		4    =>  "Parsing Error",
		8    =>  "Notice", // this notice is also for not-declared variables, so we do not use it
		16   =>  "Core Error",
		32   =>  "Core Warning",
		64   =>  "Compile Error",
		128  =>  "Compile Warning",
		256  =>  "User Error",
		512  =>  "User Warning",
		1024 =>  "User Notice",
		2048 =>  "E_STRICT",
		4096 =>  "E_RECOVERABLE_ERROR",
		8192 =>  "E_DEPRECATED",
		16384 => "E_USER_DEPRECATED",
		32767 =>  "E_ALL",
	);

	$halt = false;

	// Halt on everything *except* notices/strict/deprecated/e-all
	if(!in_array($errno,array(8,2048,4096,8192,16384,32767))) {
		$halt = true;
	}

$msg = "---------------------------------------
Message: $errstr
File: $errfile
Line: $errline
---------------------------------------
Date: ".date("r")."
Type: {$errortype[$errno]} ($errno)
PHP version: " . PHP_VERSION . "
OS: " . PHP_OS . "
---------------------------------------
POST VARS:".print_r($_POST,true)."
---------------------------------------
GET VARS:".print_r($_GET,true)."
---------------------------------------
SERVER VARS:".print_r($_SERVER,true)."
";

	if ($halt)
	{
		// Redirect to failure page
        echo '<h1>ERROR!</h1><META HTTP-EQUIV="Refresh" CONTENT="0;URL=https://www.managedomain.nl/failure.html">';
		ndie($msg); // send email to beheer
	}

	// Don't execute PHP internal error handler
	return true;
}

/**
 * getForwardPage
 *
 * @param array $row with forward information
 * @return array html[html, headers]
 */
function getForwardPage($row) {

	$headers = array(); // set headers based on http status code
	switch ($row['http_status_code']) {
		case '301':
			$headers[] = "HTTP/1.1 301 Moved Permanently";
			break;
		case '302':
			$headers[] = "HTTP/1.1 302 Found";
			break;
		case '303':
			$headers[] = "HTTP/1.1 303 See Other";
			break;
		case '307':
			$headers[] = "HTTP/1.1 307 Temporary Redirect";
			break;
		default: // no headers
			break;
	}
	$headers[] = "Location: ".trim($row['fwd_url']);
	$headers[] = "Content-type: text/html";

	$htmlCode = "<html><body>Please follow this <a href='".trim($row['fwd_url'])."'>link</a>.</body></html>";

	return array(
		'html' => $htmlCode,
		'headers' => $headers,
	);
}

/**
 * getFramesPage
 *
 * @param array $row with forward information
 * @return array html[html, headers]
 */
function getFramesPage($row) {

	if($row['noframes_content']=='') { // default content for no-frames
		$row['noframes_content'] = "<p>This page uses frames, but your browser does not support them.</p>
<p>Follow this <a href='".trim($row['fwd_url'])."'>link</a> to your destination.</p>";
	}

	$metas = array(
		array(
			'name' => $row['fwd_meta1_name'],
			'content' => $row['fwd_meta1_content'],
		),
		array(
			'name' => $row['fwd_meta2_name'],
			'content' => $row['fwd_meta2_content'],
		),
		array(
			'name' => $row['fwd_meta3_name'],
			'content' => $row['fwd_meta3_content'],
		),
	);

	$htmlCode = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
	"https://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
'.($row['fwd_title']!=""?"<title>".trim($row['fwd_title'])."</title>
":"").($row['fwd_description']!=""?"<meta name='description' content='".trim($row['fwd_description'])."'>
":"").($row['fwd_keywords']!=""?"<meta name='keywords' content='".trim($row['fwd_keywords'])."'>
":"");

	foreach ($metas as $meta) {
		if (trim($meta['name'])!='') {
			$htmlCode .= "<meta name='".trim($meta['name'])."' content='".trim($meta['content'])."'>\n";
		}
	}

	$htmlCode .= "</head>
<frameset>
	<frame scrolling='auto' src='".trim($row['fwd_url'])."'>
	<noframes>
		".trim($row['noframes_content'])."
	</noframes>
</frameset>
</html>
";

	return array(
		'html' => $htmlCode,
		'headers' => array(),
	);

}

/**
 * getRegistrationPage
 *
 * @param string $domain
 * @return array html[html, headers]
 */
function getRegistrationPage($domain) {

	$htmlCode = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "https://www.w3.org/TR/html4/frameset.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Domain registered - '.trim($domain).'</title>
</head>
<frameset>
	<frame scrolling="auto" src="https://www.managedomain.nl/script/placeholder/?servername='.trim($domain).'">
	<noframes>
		<p>This page uses frames, but your browser does not support them.</p>
	</noframes>
</frameset>
</html>
';

	return array(
		'html' => $htmlCode,
		'headers' => array(),
	);
}

/**
 * getDomainFromServerPath
 *
 * @return string $domain
 */
function getDomainFromServerPath() {
	$dirs = explode('/',$_SERVER['DOCUMENT_ROOT']);
	if ((sizeof($dirs)!=6)||($dirs[0]!='')||($dirs[1]!='home')||($dirs[5]!='')) {
		ndie("Warning, the forward script is in an invalid location!"); 
	}
	return $dirs[3];
}

function getDomainFromHTTPHost($host) {
	return preg_replace('/^www\./', '', $host);
}

/**
 * ndie - the advanced die function
 *
 * @param string $message
 */
function ndie($message = '') {
	mail('beheer@hensel.nl','[HH] ERROR in forward script on '.$_SERVER['SERVER_ADDR'],
		"This script is used to forward a client domain to a given URL\n".
		"Every Hensel Hosting Server has its own local script\n\n\n".
		"*ERROR*\n".
		"$message\n\n\n".
		"*DUMP*\n\n".
		"*SERVER*\n".print_r($_SERVER,true)."\n\n".
		"*POST*\n".print_r($_POST,true)."\n\n".
		"*GET*\n".print_r($_GET,true)."\n\n".
		"From:root@hensel.nl"
	);
	die("ERROR");
}


