<?php
session_start();

$debug_all =  (isset($_GET['all']) && $_GET['all'] == 1) ? true : false;

require_once('config/config.inc.php');

# Get system parameters from SESSION if defined. Else they are defined when building the cache further down.
# This loop is set early to enable all system constants if we need to do a full compile later.

# This setting ($caching) MUST be set to 1 default or the cache will not function
# Enable session set cache
# Disable cache if development flag is set in config
 $_GET['caching'] = 0;
$countryid = 1;
$_GET['caching'] = 0;

if ((( isset($_GET['caching']) && $_GET['caching'] == 0 ) || 
   (  !isset($_GET['caching']) && $_SESSION['disable_cache'] == 1) ) ||
	   $_SESSION['login'] > 0) {

	$caching = 0;
	$_SESSION['disable_cache'] = 1;
	$memcache = regMemCacheServer();
	//flushMemCacheData($memcache, 0);
} else {
	$caching = 1;
	$_SESSION['disable_cache'] = 0;
}

if ($caching == 0) {
	if ($_GET['all']==1) echo __LINE__.'Yai, unset session<br />'.CACHE_IN_MEMORY_ENABLE;
	unset($_SESSION['page_systemparameter']);
}

if (isset($_SESSION['page_systemparameter']) ) {
	foreach ($_SESSION['page_systemparameter'] as $param_ix => $param_val) {
		define($param_ix, $param_val);
	}
}

	if ($_GET['all']==1) {
		print (defined(CACHE_IN_MEMORY_ENABLE)) ? CACHE_IN_MEMORY_ENABLE : 'No';
		$f = get_defined_constants(true);
		print '<pre>';
		print_r($f['user']);
		print '</pre>';
	}

# Se systemdokumentation avseende headers som skickas.
# If cache is 0, expire headers immediately
$expires = ( $caching==1 ) ? 60*60*240 : 0;

//send_page_headers($expires);

#Ok, we start here to see where our LEVEL 1 CACHE CAN PROVIDE DATA
$page = ($_GET['page'] > '' &&  $_GET['page'] != 'index.php') ? $_GET['page'] : 'blog';

if ( CACHE_IN_MEMORY_ENABLE == 1 && $caching == 1) {
	$mem_key = $_SERVER['HTTP_HOST'].$page;
	$memcache = regMemCacheServer();
#	delMemCacheData($memcache, $mem_key);	
	$get_result = $memcache->get($mem_key);
	
	# We find a cached result, show and exit, else, continue...
	if ( $get_result == true && ! $_SESSION['login'] > 0) {
		if ($_GET['all']==1) echo __LINE__.'Yai, in memory!<br />';
		print $get_result;
		exit;
	}
}
#Check for quicklogin through a special URL generated from admin.
if ($_GET['aurl'] > '')
{
	$login_url = $_GET['aurl'];
	#Check login in admin table
	$sql =   "SELECT * FROM ". $__systable['sys_admin']
			." WHERE admin_url = '".$login_url."'";
	$admin_row = $db->GetRow($sql);
	
	if ($admin_row['adminid']>0)
		$_SESSION['p_login'] = 1;
}

if ($_POST)
{
	foreach ($_POST as $var=>$value)
	{
		$_POST[$var] = stripslashes($value);
	}
}

#Take care of editable content and save to db if updated by admin
if ($_POST['contentid'] > 0 && $_SESSION['p_login'] == 1) 
	admin_update_page ($db);


#  Enter short version to enable quick output from site db-cache
# ----------------------------------------------------------- >>>
# Get page parameters and settings
# First we check page_language for a page name

	$sql =   ' SELECT * FROM page_language as pl, page_parameter as pp '
			." WHERE pl.page_name = '$page' "
			.' AND languageid = '.$countryid 
			.' AND pp.pageid=pl.pageid';

	$page_params = $db->getrow($sql);
	$cache_interval=$page_params['cache_interval'];
	$cachekey = preg_replace('/caching=[0-1]|all=1/', '', $page.$_SERVER['QUERY_STRING']);
	$cachekey = preg_replace('/[^A-Za-z0-9_]/', '', $cachekey);

	$sql =   ' SELECT * FROM page_cache as pc '
			." WHERE pc.cachekey = '$cachekey' "
			." AND pc.languageid = $countryid ";

	$cache_params = $db->getrow($sql);

#	If page hasn't expired and has a valid cache content, show it
	if (	$cache_params['cached_content'] > '' && 
			strtotime($cache_params['cache_expires']) > time() && 
			$caching == 1)
	{
		if ($_GET['all']==1) echo __LINE__.'Yai, in memory!<br />';
		echo $cache_params['cached_content'];
		exit;
	} else {
		$cache_is_expired = 1;
		send_page_headers(0);
	}
# <<< END SITE DB-CACHE, Cache has probably expired or is updated by admin
# Fetch public parameters to enable modules
$sql = 'SELECT * FROM page_systemparameter ';
$page_systemparams = $db->getArray($sql);

if ($_GET['all']==1) echo __LINE__.'Yai, define Constants<br />';

foreach ($page_systemparams as $param_ix =>$param_r) {
	if ($_GET['all']==1) {
		print	$param_r['param_name'] .'=>'. $param_r['param_value'].' :<br />';
	}

	$_SESSION['page_systemparameter'][$param_r['param_name']] = $param_r['param_value'];
	define($param_r['param_name'] , $param_r['param_value']);
}

# Get page content
$pageid = ($page_params['pageid'] > 0) ? $page_params['pageid'] : 1;

# Om vi har ett id som ej existerar, returnera 404
if (is_null($page_params['templateid'])) {
	header('404');
	print '<br />PAGE NOT FOUND: '.$page.', Exit on line:'. __LINE__;
	exit;
}

$sql = 'SELECT * FROM page_template WHERE templateid = '.$page_params['templateid'];
$template = $db->Getrow($sql);

# Check for an uploaded new template and load into db

if ( is_file(TEMPLATE_DIR.'/'.$template['template_name']) && 
	 date('Y-m-d H:i:s', filemtime(TEMPLATE_DIR.'/'.$template['template_name'])) > $template['lastupdate'] ||
	 date('Y-m-d H:i:s') > $template['template_expires'] )
{
	update_db_template($template['templateid'], $template['template_name'], $page_params['cache_interval'], $db);
}

#initialize a webpage instance
require_once($_SERVER['DOCUMENT_ROOT']."/__admin/modules/page.class.php");
$current_page = new webpage($db, $smarty, $pageid);
$current_page->updatepage($countryid);
//$template = $current_page->gettemplate();
# Select template

# Get content
$current_page->getcontents($countryid);

$meta_r = $current_page->getmeta($countryid);
$smarty->assign('meta_r', $meta_r);
#Added by Fredrik Andersson 20110818 Get php include file from database instead of just using the page variableto avoid loosing functionality when changing page name e.g. for different languages.
#:TODO: remove the old way of including files.
if ($page_params['script_path'] > '')
{
	if (is_file($_SERVER['DOCUMENT_ROOT']."/includes/{$page_params['script_path']}.php")) require_once($_SERVER['DOCUMENT_ROOT']."/includes/{$page_params['script_path']}.php");

}
if (is_file($page.".php")) require_once($page.".php");

require_once('common.php');
$page_title = $page_params['page_title'];

$div_id = ($_SESSION['login'] == 1) ? 'wrap_inner_special' : 'wrap_inner';

#Build links for foreign language flags.
$sql = "SELECT * FROM language";
$languages = $db->getarray($sql);
foreach ($languages as $i=>$row)
{
	$sql = 'SELECT * FROM page_language WHERE pageid = '.$pageid .' AND languageid = '.$row['id'];
	$page_in_lang = $db->getrow($sql);
	$lang_link[$row['language_code']] = $page_in_lang['page_name'];
	if ($countryid == $row['id']) $lang_code = $row['language_code'];
}

include_once($_SERVER['DOCUMENT_ROOT'].'/config/phrases_'.$lang_code.'.inc.php');

if ( NEWS_ENABLED == 1 || $caching == 0) {
	$sql = "SELECT * FROM news ORDER BY news_date DESC, newsid DESC LIMIT 2";
	$latest_news = $db->getarray($sql);
}

$css_content = file_get_contents($_SERVER['DOCUMENT_ROOT'].CSS_DIR.CSS_NAME);

#$css_content['ie'] = file_get_contents($_SERVER['DOCUMENT_ROOT'].CSS_IE_PATH);

$smarty->assign('news', $latest_news);
$smarty->assign('lang_link', $lang_link);
$smarty->assign('languageid', $countryid);
$smarty->assign('div_id', $div_id);
$smarty->assign('page_title', $page_title);
$smarty->assign('phrase', $phrase);
$smarty->assign('from_page', $_GET['page']);
$smarty->assign('page_params', $page_params);
$smarty->assign('company_googleid', COMPANY_GOOGLEID);
$smarty->assign('page', $page);
$smarty->assign('css_sheet', $css_content);
$smarty->assign('site_charset', SITE_CHARSET);

# Start generate new cache and view content
$smarty->force_compile=true;

#Set cache expires to "now()" if admin needs a fresh update.
$cache_ttl = ( $_SESSION['login'] > 0 ) ? 0 : $page_params['cache_interval'];
if ($_SESSION['testtemplate'] == 1)
{
	$smarty->display($template['template_name']);
}
else
{
	$smarty->display($template['template_name']);
	$cached_content   = ($cache_is_expired ==1) ? $original_content : $cache_params['original_content'];
}
# Replace single line comments
$cached_content =  preg_replace('#^\s*//.+$#m', '', $cached_content);
# Replace HTML comments "<--"
$cached_content = preg_replace('/<!--[^\[].*?-->/s', '', $cached_content);
# Replace C-style comments " /* */"
$cached_content = preg_replace('/\/\*.*?\*\//s', '', $cached_content);

// using resource from php script

#Enable image caching in HTML-document
if ( CACHE_IMG_ENCODING == 1 && $caching == 0) {
	if(preg_match_all("/img src=[\"' ]?([^\"' >]+)[\"' ]?[^\"]/i", $cached_content, $m)) {
	  for($i = 0; $i < count($m[1]); $i++) {
		$fname = $_SERVER['DOCUMENT_ROOT'].'/'.preg_replace('/\.\.\//', '', $m[1][$i]);
		$img_r = getimagesize($fname);
		$data = file_get_contents($fname);
		$replace = 'data:'.$img_r['mime'].';base64,' . base64_encode($data);
		$cached_content = str_replace($m[1][$i],  $replace , $cached_content);
	  }
	}
}
$find_r = array('  ', "\n", "\r","\t");
$repl_r = array(' ');

# Repeat search and replace as long as there are occurrences left in the string ($count)
# $count is only a flag, not a real counter
$count = 1;
while($count)
	$cached_content = str_replace($find_r, $repl_r, $cached_content, $count);

$find_r = array('<html', '<head>', '<meta','<body', '<style');
$repl_r = array("\n\t<html","\n\t<head>", "\n\t<meta","\n\t<body", "\n\t<style");

$cached_content = str_replace($find_r, $repl_r, $cached_content, $cnt);

$repl = "<meta name='openit' content='Site is compressed and optimized for 100% maximum speed and performance by http://www.openit.se' />\n\t<meta";
$cached_content = preg_replace('/<meta/', $repl, $cached_content, 1 );

# output first the cached content, then update db.
if ($_GET['all']==1) echo __LINE__.'Yai, last output before cache!<br />';

if ($caching == 1)
	echo $cached_content;
else
	echo $original_content;

if ($_GET['all']==1) echo 'Caching='.$caching;

if (($cache_is_expired == 1 && $cache_ttl>0)|| ($caching == 0 && $_SESSION['p_login'] != 1)) {
	$sql =	 ' UPDATE page_cache'
			.' SET cache_expires=?, '
			.' original_content=?,'
			.' cached_content=?,'
			.' lastupdate=?,'
			.' pageid=?,'
			.' languageid=?'
			.' WHERE cachekey=?';

	//$prep_upd_sql = $db->prepare($sql);
	//$cache_rec = array((date('Y-m-d H:i:s',(time() + $cache_ttl))), $original_content, $cached_content, date('Y-m-d H:i:s'), $page_params['pageid'], $countryid, $cachekey);

	//$result = $db->execute($prep_upd_sql, $cache_rec);

	if ($db->affected_rows()==0) {
		$sql =	 ' INSERT INTO page_cache'
				.' (cache_expires, original_content, cached_content, lastupdate, pageid, languageid, cachekey)'
				.' VALUES (?,?,?,?,?,?,?)';
		//$prep_ins_sql = $db->prepare($sql);
		//$result = $db->Execute($prep_ins_sql, $cache_rec);

	}
	# Clean up page_cache from expires pages
	$sql = 'DELETE FROM page_cache WHERE cache_expires < CURRENT_TIMESTAMP';
	$db->Execute($sql);
	if ($_GET['all']==1) echo 'Deleted from page_cache (rows): '.$db->affected_rows();
	print $db->ErrorMsg();
}
if ( CACHE_IN_MEMORY_ENABLE == 1 && $caching == 0) {
	$mem_cache_ttl = round(($cache_interval / CACHE_IN_MEMORY_DIVISOR),0);
	//delMemCacheData($memcache, $mem_key);
	//setMemCacheData($memcache, $mem_key, $cached_content, $mem_cache_ttl);
}
# <----- END OF MAIN SCRIPT ---<<<<
# >>>--- START FUNCTIONS SECTION -->

/*
	update_db_template: Exists for administrators purpose only.
	If an administrator has uploaded a new template via FTP, we compare
	the db-content with file content and updates db.

*/

function admin_update_page (&$db) 
{
	$_POST['content_text'] = str_replace(array('<ph_frm', '</ph_frm>'), array('<form', '</form>'), $_POST['content_text']);
	$sql = 'UPDATE page_content SET '
			.' content_title = ?, '
			.' content_text =?'
			.' WHERE contentid = ?';
	$prep_upd_sql = $db->prepare($sql);
	$result = $db->execute($prep_upd_sql, array($_POST['content_title'], $_POST['content_text'], $_POST['contentid']));

	$sql =	 ' SELECT pageid FROM page_content'
			.' WHERE contentid='. intval($_POST['contentid']);
	$pc_r = $db->getRow($sql);
	
	$sql =	 ' UPDATE page_cache'
			.' SET cache_expires=CURRENT_DATE-1 '
			.' WHERE pageid='.$pc_r['pageid'];
	$res = $db->Execute($sql);
}


# Define  caching functions

# Define element in memory cache
function setMemCacheData(&$memcache, $mem_key = '', $content='', $ttl=10) {
	if ($_GET['all']==1) echo __LINE__.'Yai, set Memcache:'.$mem_key.'<br />';
	$memcache->set($mem_key, $content, $ttl);
}

# Delete element from memory cache
function delMemCacheData(&$memcache, $mem_key = '') {
	if ($_GET['all']==1) echo __LINE__.'Yai, Delete Memcache:'.$mem_key.'<br />';
	$memcache->delete($mem_key);
}

# Invalidate all items in memory cache
function flushMemCacheData(&$memcache, $delay=0) {
	$memcache->flush($delay);
	if ($_GET['all']==1) echo __LINE__.'Yai, flushed memory!<br />';
}

# Define memcached server in memory 
function regMemCacheServer() {
 return false;
	
}

function update_db_template($templateid = 0, $template_name ='', $cache_interval=0, &$db) {

	$tpl_body = file_get_contents(TEMPLATE_DIR.'/'.$template_name);

	$sql =	 ' UPDATE page_template'
			.' SET template_content=?, '
			.' lastupdate=?, '
			.' template_expires=?'
			.' WHERE templateid=?';

	$prep_upd_sql = $db->prepare($sql);
	$result = $db->execute($prep_upd_sql, array($tpl_body, date('Y-m-d H:i:s'), date('Y-m-d H:i:s',(time() + 10* $cache_interval)), $templateid));
}

function send_page_headers($expires=0) {
	ob_end_clean();
	header('Pragma: public');
	header('Cache-Control: maxage='.$expires);
	header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
	header('Content-Type: text/html;charset='.SITE_CHARSET);
	#echo SITE_CHARSET;
}
function compress($buffer='')
{
 
	$search = array(
		'/\>[^\S ]+/s', 
		'/[^\S ]+\</s', 
		'/(\s)+/s', // shorten multiple whitespace sequences
		'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s' //leave CDATA alone
	);
	$replace = array(
		'>',
		'<',
		'\\1',
		"//&lt;![CDATA[\n".'\1'."\n//]]>"
	);

	$buffer = preg_replace($search, $replace, $buffer);
	return $buffer;
}
?>	