<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
//
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
//
// 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, or (at your option) 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 program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

if (isset($_REQUEST['logoff'])) {
	include "components/core/config/aroundme_core.config.php";
	session_name($core_config['node']['php_session_name']);
	session_start();
	session_unset();
	session_destroy();
	
	header("Location: index.php");
}


// -------------------------------------------------------------------------
// HEADER ------------------------------------------------------------------
include "components/core/config/aroundme_core.config.php";
include "components/core/inc/aroundme_core.functions.php";


// if we register from the same browser as where a session is already running we need to kill the session
if (isset($_REQUEST['email']) && isset($_REQUEST['amn']) && $_REQUEST['amn'] == "core_register") {
	session_name($core_config['node']['php_session_name']);
	session_start();
	session_unset();
	session_destroy();
}


// SETUP GLOBALS --------------------------------------------------
// ERROR HANDLING
// this is accessed and updated with all errors thoughtout this build
// processing regularly checks if empty before continuing
$GLOBALS['am_error_log'] = array();


// STOP SOME OBVIOUS HACKS ----------------------------------------
unset ($language_path, $language_path_core, $template_path,$template_core, $template_file);


// SETUP DEBUG MODE ----------------------------------------
if ($core_config['node']['debug_mode'] == 1 || $core_config['node']['debug_mode'] == 2) {
	$GLOBALS['am_debug_output'] = array();
	$GLOBALS['am_debug_output']['mode'] = $core_config['node']['debug_mode'];
	$GLOBALS['am_debug_output']['start_time'] = strtok(microtime(), ' ') + strtok('');
}

// SETUP DATABASE --------------------------------------------------------
require_once('components/core/class/Adodb/adodb.inc.php');
$ADODB_CACHE_DIR = 'cache/Adodb';
$ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
$ADODB_COUNTRECS = false;
$db = NewADOConnection($core_config['db']['driver']);
if (!$db->Connect($core_config['db']['host'], $core_config['db']['user'] , $core_config['db']['pass'] , $core_config['db']['db'])) {
	header("Location: components/core/error.php?error=1");
	exit;
}
$db->prefix = $core_config['db']['prefix'];



// START SESSION --------------------------------------------------------------
session_name($core_config['node']['php_session_name']);
session_start();
header("Cache-control: private"); // fix for IE with not refreshing form data after back button is used - TC


//SETUP DATE -----------------------------------------------------------------------
require_once('components/core/class/Date.class.php');
$date = new Date();


// ASERTAIN COMPONENT AND PATH ------------------------------------------------------
if (isset($_REQUEST['amn'])) {
	$amn = $_REQUEST['amn'];
	$amn_arr = explode("_", $amn, 2);
	$component_id = $amn_arr[0];
	$script_full_name = $amn;
	
	if (isset($amn_arr[1])) {
		$script_name = $amn_arr[1];
	}
	else {
		$script_name = "core_error";
	}
}
else {
	$component_id = "core";
	$script_name = "login";
	$script_full_name = "core_login";

}

if ($component_id == "core" && $script_name != "profile") {
	// there is no full screen mode view in the core
	unset ($_SESSION['fullscreen']);
}

$component_path = "components/" . $component_id . "/";


if (is_file($component_path . $script_name .'.php')) {
	
	// SETUP TEMPLATE -------------------------------------------------------------------
	if (!isset($_SESSION['template_title'])) {
		$_SESSION['template_title'] = $core_config['template']['default_name'];
	}
	
	$template_path = $component_path . "template/" . $_SESSION['template_title'] . "/";
	$template_path_core = "components/core/template/" . $_SESSION['template_title'] . "/";
	
	require_once('components/core/class/Template.class.php');
	$tpl = & new Template($template_path_core); // outer template
	$body = & new Template($template_path); // inner template
	$body->date = $date;
	
	
	
	// SETUP LANGUAGE -----------------------------------------------------------
	if (!isset($_SESSION['language_id'])) {
		$_SESSION['language_id'] = $core_config['language']['default_id'];
	}
	elseif (isset($_REQUEST['language_id'])) {
		// we check the language pack is installed
		if (!empty($core_config['language']['pack'])) {
			foreach ($core_config['language']['pack'] as $key => $i):
				if ($key == $_REQUEST['language_id']) {
					$_SESSION['language_id'] = $_REQUEST['language_id'];
					break;
				}
			endforeach;
		}
	}
	
	// get language include files and create language array
	$lang = array();
	$language_path = $component_path . "language/" . $_SESSION['language_id'] . "/" . $_SESSION['template_title'] . "/";
	$language_path_core = "components/core/language/" . $_SESSION['language_id'] . "/" . $_SESSION['template_title'] . "/";
	require_once($language_path_core . 'common.lang.php');
	require_once($language_path . $script_name .'.lang.php');
	
	
	require_once('components/core/class/User.class.php');
	$user = new User($db, $core_config['user']);
	
	if (!empty($_REQUEST['http_referer'])) {
		$body->set('http_referer', $_REQUEST['http_referer']);
	}
	
	// SETUP AND VALIDATE USER ---------------------------------------------------------
	if (!empty($_SESSION['md5'])) {
		//authenticate user
		$user->authUser();
		// GET UNREAD MESSAGES COUNT
		//setup instant messaging
		$core_config['messaging']['file']['allocation'] = $core_config['file']['allocation'];
		
		require_once('components/core/class/Message.class.php');
		$im = new Message($_SESSION['user_id'], $db, $core_config['messaging']);
		$user_messages = $im->messageCount(null, 'to_identity_id', $core_config['messaging']['status']['unread']);
		$_SESSION['mail'] = $user_messages['total'];
		
		// GET CONTACT REPORTS
		if ($_SESSION['user_core_permission'] & $core_config['resource']['user']['mng_contacts']) {
			unset($_SESSION['outstanding_contact_reports']);
			
			$query = "
				SELECT count(contact_id) as total 
				FROM " . $db->prefix . "_contact 
				WHERE 
				assigned_user_id is null"
			;
			
			$result = $db->Execute($query);
		
			if (isset($result->fields)) {
				$_SESSION['outstanding_contact_reports'] = $result->fields['total'];
			}
		}
		
		// GET ANNOUNCMENTS SINCE LAST LOGIN
		unset($_SESSION['outstanding_announcements']);
			
		$query = "
			SELECT count(announce_id) as total 
			FROM " . $db->prefix . "_announce 
			WHERE 
			announce_create_datetime > " . $db->DBDate($_SESSION['last_login_datetime']) . " OR 
			announce_edit_datetime > " . $db->DBDate($_SESSION['last_login_datetime'])
		;
		
		$result = $db->Execute($query);
		
		if (isset($result->fields)) {
			$_SESSION['outstanding_announcements'] = $result->fields['total'];
		}
		
	}
	else { //treat as public (a visitor)
		$_SESSION['user_core_permission'] = $core_config['resource']['core']['user']['visitor'];
		$_SESSION['user_mod_permission'] = $core_config['resource']['core']['module']['visitor'];
		
		if (!isset($_SESSION['language_id'])) {	
			$_SESSION['language_id'] = $core_config['language']['default_id'];
		}
		$_SESSION['template_name'] = $core_config['template']['default_name'];
		$_SESSION['template_id'] = $core_config['template']['default_id'];
		
		if(empty($_SESSION['language_ids'])) {
			$_SESSION['language_ids'] = 		array();
			$_SESSION['user_homepage'] = 		$core_config['node']['page_default'];
			
			if (!empty($core_config['node']['language']['pack'])) {
				foreach($core_config['node']['language']['pack'] as $key => $i):
					$_SESSION['language_ids'][] = $key;
				endforeach;
			}
		}
	}
	
	
	// MODULE SETUP -----------------------------------------------------------
	if (isset($_REQUEST['module_id'])) {
		$module_id = $_REQUEST['module_id'];
		
		// check the module exists
		if (isset($core_config['module'][$module_id]['prefix'])) {

			
			$suffix = $core_config['module'][$module_id]['prefix'];
			
			$language_path = "components/" . $suffix . "/language/" . $_SESSION['language_id'] . "/" . $_SESSION['template_title'] . "/";
			
			// we include the config
			include_once ("components/" . $suffix . "/config/" . $suffix . ".config.php");
			
			// we include the initation script
			include_once ("components/" . $suffix . "/inc/" . $suffix . "_initiate.inc.php");
			
			// we include the common language file
			include_once ($language_path . "inc/" . $suffix . "_common.inc.php");
			
			// we alter the standard template path for the templates
			$template_path = "components/" . $suffix . "/template/" . $_SESSION['template_title'] . "/";
			
			$body->set('module_suffix', $suffix);
			$body->set('module_id', $module_id);
		}
	}

	// include any html drawing functions for templates
	include $template_path_core . "inc/html_functions.inc.php";

	
	// -------------------------------------------------------------------------
	// CONTENT ------------------------------------------------------------------
	require_once($component_path . $script_name .'.php');
	
	// -------------------------------------------------------------------------
	// FOOTER ------------------------------------------------------------------
	
	
	// DICTIONARY ---------------------------------------------------------------
	// Is the config set to allow spell checking?
	if (!empty($core_config['language']['aspell']['command'])) {
	    $body->set('allow_spellcheck', 1);
	}
	
	
	// APPLY VARS TO TEMPLATES -----------------------------------------------
	$tpl->set('lang', $lang); // language
	$body->set('lang', $lang); // language
	
	$tpl->set('template_path', $template_path);
	$body->set('template_path', $template_path);
	$tpl->set('template_path_core', $template_path_core);
	$body->set('template_path_core', $template_path_core);
	$body->set('page_name_short', $script_name);
	$tpl->set('page_name_short', $script_name);
	$body->set('core_config', $core_config);
	$tpl->set('core_config', $core_config);
	
	$tpl->set('resource', $core_config['resource']); // permissions system
	$body->set('resource', $core_config['resource']); // permissions system

	// template language
	$tpl->set('language_arr', $core_config['language']['pack'][$_SESSION['language_id']]);
	
	if (isset($menu_section)) {
	    $tpl->set('section', $menu_section);
	}
	
	
	// PROCESS TEMPLATE ------------------------------------------------------
	if (!isset($template_file)) {
		$template_file = $script_name . ".tpl.php";
	}
	
	$outer_template_file = "default.tpl.php";
	
	if (isset($_REQUEST['abuse_report']) && $script_name != "contact") { //if page is reported as abuse we redirect
		$_SESSION['report_abuse_body'] = $body->fetch($template_file);
		header("Location: index.php?amn=core_contact&contact_report_type=abuse_report&" . strip_tags(SID));
		exit;
	}
	else {
		if (!empty($_SESSION['fullscreen'])) { // module full screen mode is selected
			$tpl->path	= $template_path;
			$outer_template_file = "fullscreen.tpl.php";
		}
				
		if (isset($template_file)) {
			$tpl->set('content', $body->fetch($template_file));
		}
		
		$tpl->set('debug_mode', $core_config['node']['debug_mode']);
		
		
	
		$output_to_browser = $tpl->fetch($outer_template_file);
		
		if (isset($GLOBALS['am_debug_output'])) {
			$GLOBALS['am_debug_output']['end_time'] = strtok(microtime(), ' ') + strtok('');
			$GLOBALS['am_debug_output']['total_time'] = $GLOBALS['am_debug_output']['end_time'] - $GLOBALS['am_debug_output']['start_time'];
			
			$debug_txt = readTxtFile($language_path_core . "texts/debug.txt.php");
			
			$debug_txt = str_replace("SYS_DEBUG_STARTTIME", $GLOBALS['am_debug_output']['start_time'], $debug_txt);
			$debug_txt = str_replace("SYS_DEBUG_ENDTIME", $GLOBALS['am_debug_output']['end_time'], $debug_txt);
			$debug_txt = str_replace("SYS_DEBUG_TOTALTIME", round($GLOBALS['am_debug_output']['total_time'],3), $debug_txt);
			
			
			if (isset($GLOBALS['am_debug_output']['mode']) && $GLOBALS['am_debug_output']['mode'] == 2 && !empty($GLOBALS['am_debug_output']['queries'])) {
				$debug_sql = "";
				
				foreach ($GLOBALS['am_debug_output']['queries'] as $key => $i):
					$debug_sql .= "\n\n";
					$sql = str_replace(",", ", ", $i['query_sql']);
					$debug_sql .= round($i['query_time'],4) . " - " . $sql . "\n";
					
			
				endforeach;
				
				$debug_txt .= $debug_sql;
			}
			
			$debug_txt = nl2br($debug_txt);
			
			$output_to_browser = str_replace("SYS_DEBUG_MODE_OUTPUT", $debug_txt, $output_to_browser);
			
		}
		
		echo $output_to_browser;
	}
}
else { // file not found
	header("Location: index.php?amn=core_error");
	exit;
}

// TIDY UP ---------------------------------------------------------------
$db->Close();

?>