<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2018 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}


define("ERROR_EMAIL"	, "");		// put an email address to receive a notification with the error every time the site generates one.
define("ERROR_DETAILS"	, 1);		//put 0 to disable showing the error in browser


//compatibility with old version 
if (!defined("E_DEPRECATED")) {
	define("E_USER_DEPRECATED" , 8192 );
}

if (!defined("E_USER_DEPRECATED")) {
	define("E_USER_DEPRECATED" , 16384 );
}

error_reporting(0);

$supported_errors = array(
	10101	=> array(
		"title"		=> "Database Connection",
		"message"	=> "Invalid database selected !",
		"fix"		=> "<li>Please make sure you put the correct database name. Check upload/conf/database.php `\$_CONF[default]`. </li>
						<li>Make sure you gave to mysql user to access this database.</li>"
	),

	//parse error
	4	=> array(
		"title"		=> "Parse Error",
		"message"	=> "",
		"fix"		=> "<li>Please compare the file that gives error with the one from original package. Most likely there was a timeout during upload and only a part of the file was saved on the server.</li>
						<li>If you changed the file yourself then you have an error in code . </li>"
	),
);


function StembaseShutDown_template($error) {
	global $supported_errors;


	if (isset($_SERVER["HTTPS"]) && (strtoupper($_SERVER["HTTPS"]) == "ON")) {
		$_TSM["PRIV.BASE.HREF"] = 	"https://" . dirname( $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] ) . "/";
	} else {
		$_TSM["PRIV.BASE.HREF"] = 	"http://" . dirname( $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] ) . "/";
	}


	$type = array(
		1		=>  "Fatal Error",
		2		=>  "Warning",
		4		=>	"Parse",
		8		=>	"Notice",
		8192	=>	"Deprecated",
		-1		=>	"System Error",
	);

	if (!$type[$error["type"]]) {
		$error["type"] = -1;
	}

	switch ($error["type"]) {
		case 4:
			$error_msg = array(
					"title"		=> $supported_errors[$error["type"]]["title"],
					"message"	=> $error["message"],
					"fix"		=> $supported_errors[$error["type"]]["fix"],
					"code"		=> $key,
					
					"file"		=> $error["file"],
					"line"		=> $error["line"],
			);		
		break;

		default:
			if ($supported_errors[$error["message"]]) {

				$error_msg = array(
						"title"		=> $supported_errors[$error["message"]]["title"],
						"message"	=> $supported_errors[$error["message"]]["message"],
						"fix"		=> $supported_errors[$error["message"]]["fix"],
						"code"		=> $key,
						
						"file"		=> $error["file"],
						"line"		=> $error["line"],
				);
			} else {

				$error_msg = array(
						"title"		=> $type[$error["type"]],
						"message"	=> $error["message"],
					
						"file"		=> $error["file"],
						"line"		=> $error["line"],
				);

			}
		break;
	}

	if (constant("ERROR_EMAIL") !="") {

		@mail(
			ERROR_EMAIL,
			"System Error: " . $_SERVER["HTTP_HOST"],
			"
				<table border='0' cellspacing='1'>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Type:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>" . $type[$error["type"]] . "</td>
					</tr>
					<tr>
						<td  style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Message:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$error['message']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>File:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$error['file']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Line:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$error['line']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Server:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$_SERVER['HTTP_HOST']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Link:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Referer:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$_SERVER['HTTP_REFERER']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Client IP:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>{$_SERVER['REMOTE_ADDR']}</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>Date:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'>" . date("+r") . "</td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>\$_GET:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'><pre>" . print_r($_GET,true) . "</pre></td>
					</tr>
					<tr>
						<td style='background: #00aeef;padding:4px 10px;font-size: 12px;color: #fff; text-align: right; font-weight: bold; '>\$_SESSION:</td>
						<td style='background: #efefef;padding:4px;font-size: 12px;'><pre>" . print_r($_SESSION,true) . "</pre></td>
					</tr>
					<tr>
						<td colspan='2' style='text-align: right;background: #efefef;padding:4px;font-size: 12px;'>powered by <a href='http://devsaver.com'>DevSaver Framework</a></td>
				</table>
			",
			"Content-type: text/html\r\n" . 
			"From: notice@devsaver.com\r\n".
			"X-Mailer: PHP/" . phpversion()
		);
		
	}

		
	$return = '<!DOCTYPE html>
	<html>
		<head>

			<title>Error</title>
			<base href="' . $_TSM['PRIV.BASE.HREF'] . '" />
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			<meta name="viewport" content="width=device-width, initial-scale=1.0">

			<link href="' . _LIBPATH . 'error/assets/css/layout.bootstrap.css" rel="stylesheet" media="screen">
			<link href="' . _LIBPATH . 'error/assets/css/layout.error.css" rel="stylesheet" media="screen">
			<script src="' . _LIBPATH . 'error/assets/js/jquery.min.js"></script>
			<script src="' . _LIBPATH . 'error/assets/js/custom.js"></script>
			<link rel="icon" type="image/png" href="' . _LIBPATH . '../assets/favicon.png" />

		</head>

		<body>

			<main>
				<div class="error-container">
					<div class="top"><</div>
					<p class="subtitle">Sorry, this just happened!</p>
					<div class="error-element">
						<p class="description">It\'s a system error that rarely happens but we should be able to fix this soon. Click the “Go Back” button to return to the previous page and try again later.</p>';

		if (ERROR_DETAILS == 1) {
			$return .= '<div class="table">
							<table>
								<tbody>
									<tr>
										<td><p><strong>' . $error_msg["title"] . ':</strong></p></td>
										<td><p>' . strip_tags($error_msg["message"]) . '</p></td>
									</tr>
									<tr>
										<td><p><strong>File:</strong></p></td>
										<td><p>' . $error_msg["file"] . '</p></td>
									</tr>
									<tr>
										<td><p><strong>Line:</strong></p></td>
										<td><p>' . $error_msg["line"] . '</p></td>
									</tr>
									<tr>
										<td><p><strong>Page URL:</strong></p></td>
										<td><p>' . $_SERVER["REQUEST_URI"] . '</p></td>
									</tr>
								</tbody>
							</table>
						</div>';
		}
		


		$return .= '	
					</div>
					<p class="go-back"><a href="javascript:window.history.back();">Go Back</a></p>
				</div>
			</main>

		</body>
	</html>';


	return $return;
}

function StembaseShutDown(){

	global $StembaseShutDown_template;
	
    $error=error_get_last();

    if($error==null) {
        
    } else {

		switch ($error["type"]) {

			case E_USER_WARNING:
			case E_CORE_WARNING:
			case E_COMPILE_WARNING:
//			case E_WARNING:

			case E_USER_ERROR:

			case E_COMPILE_ERROR:

			case E_CORE_ERROR:
			case E_ERROR:
			case E_PARSE:

				if (php_sapi_name() == "cli") {
				} else {			
					ob_clean();
					header('HTTP/1.1 503 Service Temporarily Unavailable' , true);
					header('Status: 503 Service Temporarily Unavailable');
					header('Retry-After: 3600');
				}

				echo StembaseShutDown_template(
					$error
				);

				die();
			break;
			
			//ignore this type of errors		
			case E_RECOVERABLE_ERROR:
			case E_NOTICE:
			case E_STRICT:
			case E_USER_NOTICE:
			case E_DEPRECATED:
			case E_USER_DEPRECATED:
			break;

		}


	}
   
}

function StembaseErrorsHandlerDisable() {
	set_error_handler('StembaseShutDownHandlerEmpty');
	set_exception_handler('StembaseExceptionHandlerEmpty');
}

function StembaseErrorsHandlerRestore() {
	restore_error_handler();
	restore_exception_handler();
}

function StembaseExceptionHandler($exception) {

	StembaseShutDownHandler(
		E_ERROR, 
		$exception->getMessage(), 
		$exception->getFile(), 
		$exception->getLine()
	);
}
function StembaseExceptionHandlerEmpty($exception) {}
function StembaseShutDownHandlerEmpty($errno, $errstr, $errfile, $errline){} 

function StembaseShutDownHandler($errno, $errstr, $errfile, $errline) {

	if ($errstr == "demo") {
		DemoMode();
	}

	
    switch ($errno) {
	    case E_USER_ERROR:
	    case E_USER_WARNING:

//		case E_DEPRECATED:
//		case E_USER_DEPRECATED:

		case E_ERROR:
//		case E_WARNING:
		case E_PARSE:

//		case E_CORE_WARNING:
		case E_CORE_ERROR:

		case E_COMPILE_ERROR:
		case E_COMPILE_WARNING:
		case E_RECOVERABLE_ERROR:

			if (php_sapi_name() == "cli") {
			} else {			

				//clearn headers if anythign sent already
				if (ob_get_contents()) {
					ob_clean();
				}
				
				header('HTTP/1.1 503 Service Temporarily Unavailable' , true);
				header('Status: 503 Service Temporarily Unavailable');
				header('Retry-After: 3600');
			}

			echo StembaseShutDown_Template(
				array(
					"type"		=>	$errno , 
					"message"	=>	$errstr , 
					"file"		=>	$errfile,
					"line"		=>	$errline
				)
			);

			die();
		break;
		
		case E_NOTICE:
	    case E_USER_NOTICE:

	    case E_STRICT:
		case E_DEPRECATED:
		case E_USER_DEPRECATED:
		break;

	}

}


/**
* description
*
* @param
*
* @return
*
* @access
*/
function DemoMode() {

	if (isset($_SERVER["HTTPS"]) && (strtoupper($_SERVER["HTTPS"]) == "ON")) {
		$_TSM["PRIV.BASE.HREF"] = 	"https://" . dirname( $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] ) . "/";
	} else {
		$_TSM["PRIV.BASE.HREF"] = 	"http://" . dirname( $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] ) . "/";
	}

	echo  '<!DOCTYPE html>
	<html>
		<head>

			<title>Not Allowed</title>
			<base href="' . $_TSM['PRIV.BASE.HREF'] . '" />
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			<meta name="viewport" content="width=device-width, initial-scale=1.0">

			<link href="' . _LIBPATH . 'error/assets/css/layout.bootstrap.css" rel="stylesheet" media="screen">
			<link href="' . _LIBPATH . 'error/assets/css/layout.error.css" rel="stylesheet" media="screen">
			<script src="' . _LIBPATH . 'error/assets/js/jquery.min.js"></script>
			<script src="' . _LIBPATH . 'error/assets/js/custom.js"></script>
			<link rel="icon" type="image/png" href="' . _LIBPATH . '../assets/favicon.png" />

		</head>

		<body>
			<main>
				<div class="error-container demo-mode">
					<div class="top sorry"></div>
					<p class="subtitle">Not allowed in demo mode!</p>
					<div class="error-element">
						<p class="description">
							This feature is disabled to preserve the front-end demo setup. 
							Download the website template to access all the CMS functions.
							Click the “Go Back” button to return to the previous page.
						</p>					
					</div>
					<p class="go-back"><a href="javascript:window.history.back();">Go Back</a></p>
				</div>
			</main>
		</body>
	</html>';

	die();

}



//catch all exceptions
set_exception_handler("StembaseExceptionHandler");

//catch catch all errors that are not fatal
set_error_handler("StembaseShutDownHandler" , E_ALL);


//Catch fatal errorrs
function StembaseFatalErrorHandler()
{
    $error = error_get_last();
    if ($error !== NULL && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {

		echo StembaseShutDown_Template(
			array(
				"type"		=>	$error["type"], 
				"message"	=>	$error["message"], 
				"file"		=>	$error["file"],
				"line"		=>	$error["line"]
			)
		);

		die();
    }
}
if (function_exists("register_shutdown_function")) {
	register_shutdown_function('StembaseFatalErrorHandler');
}

