<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/

//===========================================
//LOAD TIME i
//===========================================
$mtime = microtime();
$mtime = explode(" ",$mtime);
$starttime = $mtime[1] + $mtime[0];

//===========================================
//COMPRESSION
//===========================================
if (extension_loaded('zlib')) {
	@ini_set('zlib.output_compression_level',6);
	ob_start('ob_gzhandler');
}

//===========================================
//CHECK IF MEMHT IS INSTALLED
//===========================================
if (!file_exists("inc/inc_config.php")) {
	if (file_exists("install/index.php")) {
		header("Location: install/index.php");
	} else {
		die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Attention:</b> The configuration file is missing and a new installation cannot be started because the install file cannot be located</td></tr></table>");
	}
} else if (file_exists("install/index.php")) {
	die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Attention:</b> Delete the installation folder and files!</td></tr></table>");
}

//===========================================
//DATABASE: CONNECT
//===========================================
require_once("inc/inc_config.php");
require_once("inc/inc_database.php");

$dblink = new database();
$dblink->connect();

//===========================================
//TIMEZONE SETTING + DATABASE CHECK
//===========================================
$timezonerow = $dblink->get_row("SELECT timezone FROM memht_config") or die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Attention:</b> Cannot find database tables!</td></tr></table>");
$siteConfig['timezone'] = intval($timezonerow['timezone']);
$tzNOW = "DATE_ADD(NOW(),INTERVAL ".$siteConfig['timezone']." HOUR)";

//===========================================
//INCLUDES
//===========================================
require_once("inc/inc_login.php");
require_once("inc/inc_functions.php");
require_once("inc/inc_bbcode.php");
require_once("inc/inc_readConfig.php");
require_once("inc/inc_getinfo.php");
require_once("inc/inc_statistics.php");
require_once("inc/inc_ban.php");

include_once("inc/inc_banners.php");
include_once("inc/inc_online.php");
include_once("inc/inc_htmlclean.php");

//===========================================
//MODREWRITE + HTML Cleaner
//===========================================
if ($siteConfig['modrewrite']==1) {
	include_once("inc/inc_modrewrite.php");
	ob_start(replace_for_mod_rewrite);
} else {
	ob_start(replace_htmlclean);
}

//===========================================
//INITIALIZE TEMPLATE ENGINE
//===========================================
include_once("inc/tpl/RainTPL.class.php");
$tpl = new RainTPL($template_directory="templates/".$siteConfig['template']);
$tpl->assign("tpl_template",$siteConfig['template']);
if (file_exists("templates/".$siteConfig['template']."/table.php")) {
	include_once("templates/".$siteConfig['template']."/table.php");
} else {
	function openTable($title="") {
		echo "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='tpl_opentable'><tr><td>\n";
		if ($title!="") { echo "<div class='tpl_opentable_title'>$title</div>\n"; }
	}
	function closeTable() {
		echo "</td></table>\n";
	}
}
function page_title() {} //DEPRECATED
function page_title_blank() {} //DEPRECATED

//===========================================
//SELECT LANGUAGE
//===========================================
include_once (file_exists("lang/".$siteConfig['language'].".php")) ? "lang/".$siteConfig['language'].".php" : "lang/".$siteConfig['default_language'].".php" ;

global $pagetitle,$virtualpagerequest,$rankPage,$enabledPage,$userid,$userInfo;

//===========================================
//ERROR REPORTING
//===========================================
if (isAuth($userid,3)) { error_reporting(E_ALL); } else { error_reporting(0); }
$error_handler = set_error_handler("memhtErrorHandler");

if ($siteConfig['site_open']==1 OR isAuth($userid,3)) {
	//HEADER
	include_once("inc/inc_header.php");

	//MAIN
	if (isset($_GET['page'])) {
		$page = inCode($_GET['page']);
		ob_start();
			if (validate($page)) {
				//OPEN THE SELECTED PAGE
				if (file_exists("pages/$page/index.php") AND ($enabledPage==1 OR isAuth($userid,3))) {
					if (myRank()>=$rankPage) {
						$open = true;
						if ($result = $dblink->get_list("SELECT groupid FROM memht_groups_pages WHERE page='$page'")) {
							$grouparr = array();
							foreach ($result as $row) {
								$groupid = intval($row['groupid']);
								if ($dblink->get_num("SELECT id FROM memht_groups_members WHERE groupid=$groupid AND user=$userid AND standby=0 AND (permanent=1 OR expire > $tzNOW)")==0) { $open = false; $grouparr[] = $groupid; }
							}								
						} else { $open = true; }
						
						if ($open) {
							if (file_exists("pages/$page/lang/".$siteConfig['language'].".php")) {
								include_once("pages/$page/lang/".$siteConfig['language'].".php");
							} else if (file_exists("pages/$page/lang/".$siteConfig['default_language'].".php")) {
								include_once("pages/$page/lang/".$siteConfig['default_language'].".php");
							}
							//--
							define("_LOAD_PAGE_",1);
							if ($page=="mypage" AND $checkid>0 AND $checktitle!="") {
								$pagecontent['title'] = $checktitle;
								$pagecontent['url'] = "index.php?page=mypage&op=openPage&id=$checkid&title=".mem_urlencode($checktitle);
							} else {
								$pagecontent['title'] = $pagetitle;
								$pagecontent['url'] = "index.php?page=$page";
							}
							$pagecontent['name'] = $page;
							include("pages/$page/index.php");
							//--
						} else {
							$pagecontent['title'] = _ACCESSDENIED_;
							$pagecontent['url'] = "";
							$pagecontent['name'] = "";
							openTable();
								//ACCESS DENIED (group required)
								echo "<div align='center' id='errorText'><b>"._ACCESSDENIED_."</b></div>";
								echo "<div align='center' class='box'><b>"._YOUHAVENOPERM_." "._TOACCESSTHISPAGE_."!</b></div>";
								if (sizeof($grouparr)>0) {
									echo "<div class='box'><i>"._REQUIRED_.":</i><br>";
									foreach ($grouparr as $groupid) {
										$row = $dblink->get_row("SELECT type,amount,name FROM memht_groups WHERE id=$groupid");
										echo "<div>&nbsp;&nbsp;- "._GROUP_.": <b>".$row['name']."</b>";
										switch (intval($row['type'])) {
											case 1: echo ": <b>".$row['amount']."</b> "._FORUM_POSTS_; break;
											case 2: echo ": <b>".$row['amount']."</b> "._CONTRIBUTES_." ("._NEWS_.","._FILES_.")"; break;
										}
										echo "</div>";
									}
									echo "</div>";
								}
							closeTable();
						}
					} else {
						openTable();
							//ACCESS DENIED (Login required)
							echo "<div align='center' id='errorText'><b>"._ACCESSDENIED_."</b></div>";
							if ($rankPage==1) {
								echo "<div align='center' class='box'>"._YOUHAVENOPERM_." "._TOACCESSTHISPAGE_."!<br>"._DOTHE_." <a href='index.php?page=users' title='"._LOGIN_."'><b>"._LOGIN_."</b></a> "._OR_." <a href='index.php?page=users&op=register' title='"._REGISTER_."'><b>"._REGISTER_."</b></a> "._FORFREE_."</div>";
								@session_start();
								$_SESSION['redirect_url'] = "index.php?page=$page";
								$_SESSION['redirect_age'] = time();
							}
						closeTable();
					}
				} else if ($virtualpagerequest AND ($enabledPage==1 OR isAuth($userid,3)) AND $siteConfig['virtualpages']==1) {
					//VIRTUAL PAGES (Added in 3.8.0)
					if (myRank()>=$rankPage) {
						$open = true;
						if ($result = $dblink->get_list("SELECT groupid FROM memht_groups_pages WHERE page='$page'")) {
							$grouparr = array();
							foreach ($result as $row) {
								$groupid = intval($row['groupid']);
								if ($dblink->get_num("SELECT id FROM memht_groups_members WHERE groupid=$groupid AND user=$userid AND standby=0 AND (permanent=1 OR expire > $tzNOW)")==0) { $open = false; $grouparr[] = $groupid; }
							}								
						} else { $open = true; }
						if ($open) {
							define("_LOAD_PAGE_",1);
							require_once("inc/inc_header.php");
							$pagecontent['title'] = $pagetitle;
							$pagecontent['url'] = "index.php?page=$page";
							$pagecontent['name'] = $page;
							openTable();
								eval($pageContent);
							closeTable();
							require_once("inc/inc_footer.php");
						} else {
							$pagecontent['title'] = _ACCESSDENIED_;
							$pagecontent['url'] = "";
							$pagecontent['name'] = "";
							openTable();
								//ACCESS DENIED (group required)
								echo "<div align='center' id='errorText'><b>"._ACCESSDENIED_."</b></div>";
								echo "<div align='center' class='box'><b>"._YOUHAVENOPERM_." "._TOACCESSTHISPAGE_."!</b></div>";
								if (sizeof($grouparr)>0) {
									echo "<div class='box'><i>"._REQUIRED_.":</i><br>";
									foreach ($grouparr as $groupid) {
										$row = $dblink->get_row("SELECT type,amount,name FROM memht_groups WHERE id=$groupid");
										echo "<div>&nbsp;&nbsp;- "._GROUP_.": <b>".$row['name']."</b>";
										switch (intval($row['type'])) {
											case 1: echo ": <b>".$row['amount']."</b> "._FORUM_POSTS_; break;
											case 2: echo ": <b>".$row['amount']."</b> "._CONTRIBUTES_." ("._NEWS_.","._FILES_.")"; break;
										}
										echo "</div>";
									}
									echo "</div>";
								}
							closeTable();
						}
					} else {
						openTable();
							//ACCESS DENIED (Login required)
							echo "<div align='center' id='errorText'><b>"._ACCESSDENIED_."</b></div>";
							if ($rankPage==1) {
								echo "<div align='center' class='box'>"._YOUHAVENOPERM_." "._TOACCESSTHISPAGE_."!<br>"._DOTHE_." <a href='index.php?page=users' title='"._LOGIN_."'><b>"._LOGIN_."</b></a> "._OR_." <a href='index.php?page=users&op=register' title='"._REGISTER_."'><b>"._REGISTER_."</b></a> "._FORFREE_."</div>";
								@session_start();
								$_SESSION['redirect_url'] = "index.php?page=$page";
								$_SESSION['redirect_age'] = time();
							}
						closeTable();
					}
				} else {
					require_once("inc/inc_header.php");
					$pagecontent['title'] = _PAGE_NOEXIST_ORINACTIVE_;
					$pagecontent['url'] = "";
					$pagecontent['name'] = "";
					openTable();
						echo "<div align='center' id='errorText'><b>"._PAGE_NOEXIST_ORINACTIVE_."</b></div>";
					closeTable();
					require_once("inc/inc_footer.php");
				}
			} else {
				//SUSPICIOUS PAGE NAME
				$pagecontent['title'] = _SYNTAX_ERROR_;
				$pagecontent['url'] = "";
				$pagecontent['name'] = "";
				openTable();
					echo "<div align='center' id='errorText'><b>"._SYNTAX_ERROR_."</b></div>";
				closeTable();
			}
		$pagecontent['content'] = ob_get_contents();
		ob_end_clean();
	} else {
		//DEFAULT HOME
		ob_start();
			define("_LOAD_PAGE_",1);
			if (memRunHooks('DefaultHome')) {
				include_once("pages/messages/index.php");
				include_once("inc/inc_blocks_central.php");
				if (file_exists("pages/".$siteConfig['defpage']."/index.php")) {
					include("pages/".$siteConfig['defpage']."/index.php");
				} else if ($row = $dblink->get_row("SELECT content FROM memht_virtualpages WHERE name='".$siteConfig['defpage']."'")) {
					//VIRTUAL PAGES (Added in 3.8.0)
					eval(outCodeVP($row['content']));
				}
				
				memRunHooks('DefaultHomeEnd');
			}
		$pagecontent['title'] = "";
		$pagecontent['url'] = "index.php?page=".$siteConfig['defpage'];
		$pagecontent['name'] = $siteConfig['defpage'];
		$pagecontent['content'] = ob_get_contents();
		ob_end_clean();
	}
	
	//FOOTER
	include_once("inc/inc_footer.php");
	//BLOCKS
	include_once("inc/inc_blocks_nav.php");
	include_once("inc/inc_blocks_extra.php");
	
	$tpl->assign('tpl_page',$pagecontent);
} else {
	//Site closed
	$siteinactive = ($siteConfig['offlinemsg']!="") ? $siteConfig['offlinemsg'] : _SITE_TEMP_INACTIVE_ ;
	die("<div align='center'><table style='margin: 2px; padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;'><tr><td>$siteinactive</td></tr></table></div>");
}

if ($siteConfig['usecronjobs']==0) {
	//MAINTENANCE
	$maintenance = new Maintenance();
	$maintenance->All();
	//NEWSLETTER
	sendNewsletter();
}

//===========================================
//DRAW TEMPLATE
//===========================================
$tpl->draw("home");

//===========================================
//CLEAN
//===========================================
ob_end_flush();

//===========================================
//LOAD TIME e
//===========================================
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = sprintf("%01.2f",($endtime - $starttime));
$totaltime = explode(".",$totaltime);

if ($totaltime[1]>=75) { $totaltime = ($totaltime[0]+1).".00";
} else if ($totaltime[1]>=50) { $totaltime = $totaltime[0].".75";
} else if ($totaltime[1]>=25) {	$totaltime = $totaltime[0].".50";
} else if ($totaltime[1]>0) { $totaltime = $totaltime[0].".25";
} else { $totaltime = $totaltime[0].".00"; }

if ($dblink->get_num("SELECT time FROM memht_statistics_loadtime WHERE time='$totaltime' LIMIT 1")>0) {
	$dblink->query("UPDATE memht_statistics_loadtime SET hits=hits+1 WHERE time='$totaltime'");
} else {
	$dblink->query("INSERT INTO memht_statistics_loadtime (time,hits,started) VALUES ('$totaltime',1,$tzNOW)");
}

//===========================================
//DATABASE: DISCONNECT
//===========================================
$dblink->disconnect();

?>

</body>
</html>