<?php

/**
 * @package eggblog
 * @author eggblog.net, tenfourzero@users.sourceforge.net
 * @version $Id: global.php,v 4.0.0RC1 2007/12/03 10:26:12 tenfourzero Exp $
 * @copyright Copyright (c) 2005, http://www.eggblog.net
 * @license http://www.gnu.org/licenses/gpl.html GNU Lesser General Public License
 */


/**
 * set version no.
 */
$config['version']="4.0.1";


/**
 * include the config and language files
 */
require_once 'config.php';
require_once 'langs/'.$config['lang'].'.php';


/**
 * include other library files
 */
require_once '_lib/admin.php';
require_once '_lib/forum.php';
require_once '_lib/news.php';
require_once '_lib/user.php';
require_once '_lib/xml.php';
require_once '_lib/photos.php';


/**
 * primary checks and processes
 */
function eb_pre() {
	global $config;
	// start session if not session_id not present
	if(session_id()=='') session_start();
	// check for a complete config file
	if(!strpos($_SERVER['REQUEST_URI'],'admin.php') && !strpos($_SERVER['REQUEST_URI'],'error.php') && !eb_checkconfig()) header('Location: error.php?id=config');
	// connect to mysql database; redirect on fail
	$mysql=mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
	if(!mysql_select_db($config['mysql_table'],$mysql) && !strpos($_SERVER['REQUEST_URI'],'error.php')) header('Location: error.php?id=mysql');
	if(!strpos($_SERVER['REQUEST_URI'],'admin.php') &&  !strpos($_SERVER['REQUEST_URI'], 'error.php') && !$mysql) header('Location: error.php?id=mysql');

	// check if install.php exists
	if(file_exists('install.php') && !strpos($_SERVER['REQUEST_URI'],'install.php') && !strpos($_SERVER['REQUEST_URI'],'upgrade_3to4.php') && !strpos($_SERVER['REQUEST_URI'],'error.php') && !strpos($_SERVER['REQUEST_URI'],'admin.php')) header('Location: error.php?id=install');
	// check if upgrade_3to4.php exists
	if(file_exists('upgrade_3to4.php') && !strpos($_SERVER['REQUEST_URI'],'install.php') && !strpos($_SERVER['REQUEST_URI'],'upgrade_3to4.php') && !strpos($_SERVER['REQUEST_URI'],'error.php') && !strpos($_SERVER['REQUEST_URI'],'admin.php')) header('Location: error.php?id=upgrade');
	// process hidden login if not logged in and email and password cookie exist
	if(isset($_COOKIE['email']) && isset($_COOKIE['password']) && !isset($_SESSION['user_id'])) eb_login($_COOKIE['email'],$_COOKIE['password'],1);
}


/**
 * print page header
 * @param string $title page title
 */
function eb_head($title) {
	global $config,$lang;
	if(strlen($title)==0) $title=htmlentities($config['title'],ENT_QUOTES)." - ".htmlentities($config['subtitle'],ENT_QUOTES);
	if(file_exists("themes/".$config['theme']."/inc_head.php")) {
		require_once "themes/".$config['theme']."/inc_head.php";
	}
	else {
		echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n";
		echo "<html>\r\n";
		echo "<head>\t\n";
		echo "\t<title>".$title."</title>\r\n";
		echo "\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$lang['charset']."\" />\r\n";
		echo "\t<meta http-equiv=\"content-style-type\" content=\"text/css\" />\r\n";
		echo "\t<meta name=\"description\" content=\"".$config['meta_desc']."\" />\r\n";
		echo "\t<meta name=\"keywords\" content=\"".$config['meta_keys']."\" />\r\n";
		if(file_exists('themes/'.$config['theme'].'/favicon.ico')) echo "\t<link rel=\"icon\" href=\"themes/".$config['theme']."/favicon.ico\" type=\"image/x-icon\" />\r\n\t<link rel=\"shortcut icon\" href=\"themes/".$config['theme']."/favicon.ico\" type=\"image/x-icon\" />\r\n";
		echo "\t<link rel=\"alternate\" href=\"rss.php?id=0\" type=\"application/rss+xml\" title=\"".htmlentities($config['title'],ENT_QUOTES)."\" />\r\n";
		echo "\t<link rel=\"stylesheet\" href=\"themes/".$config['theme']."/print.css\" type=\"text/css\" media=\"print\" />\r\n";
		echo "\t<style type=\"text/css\" media=\"screen\">@import \"themes/".$config['theme']."/style.css\";";
		echo "</style>\r\n";
		echo "</head>\r\n";
		echo "<body>\r\n";
		echo "<div id=\"container\">\r\n";
		echo "\t<div id=\"head\">\r\n";
		echo "\t\t<h1><a href=\"index.php\">".htmlentities($config['title'],ENT_QUOTES)."</a></h1>\r\n";
		echo "\t\t<h2>".htmlentities($config['subtitle'],ENT_QUOTES)."</h2>\r\n";
		echo "\t</div>\r\n";
		echo "\t<div id=\"main\">\r\n";
		echo eb_stickys();
	}
}


/**
 * print page footer
 */
function eb_foot() {
	global $config,$lang;
	echo "\t</div>\r\n";
	echo "\t<div id=\"side\">\r\n";
	echo "\t\t<div class=\"box\">\r\n";
	// if logged in, print account options
	if(!empty($_SESSION['user_id'])) {
		echo "\t\t\t<strong><a href=\"mydetails.php\">".ucwords($lang['your_account'])."</a></strong>\r\n";
		echo "\t\t\t<ul>\r\n";
		if(eb_checkadmin($_SESSION['user_id'])) echo "\t\t\t\t<li><a href=\"admin.php\">".ucwords($lang['admin'])."</a></li>\r\n";
		echo "\t\t\t\t<li><a href=\"mydetails.php\">".ucwords($lang['my_details'])."</a></li>\r\n";
		echo "\t\t\t\t<li><a href=\"logout.php\">".ucwords($lang['log_out'])."</a></li>\r\n";
		echo "\t\t\t</ul>\r\n";
	}
	// if not logged in, print log in form
	else {
		echo "\t\t\t<strong>".ucwords($lang['login'])."</strong>\r\n";
		echo "\t\t\t<form action=\"login.php\" method=\"post\">\r\n";
		if(isset($_GET['login'])) echo "\t\t\t\t\t<p class=\"alert\">".$lang['login_fail']."</p>\r\n";
		echo "\t\t\t\t<p><label for=\"login_em\">".ucwords($lang['email'])."</label><br /><input type=\"text\" name=\"email\" id=\"login_em\" /></p>\r\n";
		echo "\t\t\t\t<p><label for=\"login_pw\">".ucwords($lang['password'])."</label><br /><input type=\"password\" name=\"password\" id=\"login_pw\" /></p>\r\n";
		echo "\t\t\t\t<p><input type=\"submit\" id=\"login_sm\" name=\"submit\" value=\"".ucwords($lang['login'])."\" /></p>\r\n";
		echo "\t\t\t</form>\r\n";
		echo "\t\t\t<ul>\r\n";
		echo "\t\t\t\t<li><a href=\"register.php\">".$lang['register']."</a></li>\r\n";
		echo "\t\t\t\t<li><a href=\"forgot.php\">".$lang['forgot_password']."</a></li>\r\n";
		echo "\t\t\t</ul>\r\n";
	}
	echo "\t\t</div>\r\n";
	// print list of recent articles
	echo eb_articlelist(10);

	echo "\t\t<div class=\"box\">\r\n";
	echo "\t\t\t<strong><a href=\"tags.php\">".ucwords($lang['tags'])."</a></strong>\r\n";
	eb_tags(10);
	echo "\t\t</div>\r\n";

	// print list of recent topics if forum is enabled
	if($config['forums']=="1") {
		echo "\t\t<div class=\"box\">\r\n";
		echo "\t\t\t<strong><a href=\"forum.php\">".ucwords($lang['forums'])."</a></strong>\r\n";
		$posts=eb_recentforum(5,0);
		if(count($posts)>0) {
			foreach($posts as $post) {
				echo "\t\t\t<p><a href=\"forum.php?topic=".$post['topic_id']."\"><b>".eb_linkable(eb_textpreview($post['topic_title'],25))."</b></a><br />".eb_textpreview(strip_tags($post['post_body']),50)."<br /><b>".$post['user_name']."</b> @ <b>";
				echo date("g:ia",$post['post_date']).", ".date("jS",$post['post_date'])." ".ucwords($lang['month'.date("n",$post['post_date'])])." ".date("Y",$post['post_date']);
				echo "</b></p>\r\n";
			}
		}
		echo "\t\t</div>\r\n";
	}
	if($config['photos']=="1") {
		echo "\t\t<div class=\"box\">\r\n";
		echo "\t\t\t<strong><a href=\"photos.php\">".ucwords($lang['photos'])."</a></strong>\r\n";
		echo eb_albums();
		echo "\t\t</div>\r\n";
	}
	if(file_exists('_lib/inc_side.php')) require_once '_lib/inc_side.php';
	echo "\t</div>\r\n";
	if(file_exists('themes/'.$config['theme'].'/inc_foot.php')) {
		require_once 'themes/'.$config['theme'].'/inc_foot.php';
	}
	else {
		echo "\t<div id=\"foot\">\r\n";
		echo "\t\t<ul>\r\n";
		echo "\t\t\t<li class=\"first\">&copy; ".date("Y")."</li>\r\n";
		echo "\t\t\t<li><a href=\"http://creativecommons.org/licenses/by-nc-sa/3.0/\">".htmlentities($lang['copyright'],ENT_QUOTES)."</a></li>\r\n";
		echo "\t\t\t<li><a href=\"rss.php?id=0\">".$lang["rss_news"]."</a></li>\r\n";
		// print link to forum rss if forums enabled
		if($config['forums']=="1") echo "\t\t\t<li><a href=\"rss.php?id=1\">".$lang['rss_forum']."</a></li>\r\n";
		echo "\t\t\t<li><a href=\"http://eggblog.net\">".htmlentities($lang['powered_by'],ENT_QUOTES)." eggBlog.net</a></li>\r\n";
		echo "\t\t</ul>\r\n";
		echo "\t</div>\r\n";
	}
	echo "</div>\r\n";
	if(file_exists('_lib/inc_foot.php')) require_once '_lib/inc_foot.php';
	echo "</body>\r\n";
	echo "</html>\r\n";
	mysql_close();
	exit();
}


/**
 * check for a completed config file
 * @return boolean
 */
function eb_checkconfig() {
	global $config;
	$array=array(
		"meta_keys",
		"meta_desc",
		"theme",
		"lang",
		"email",
		"title",
		"subtitle",
		"forums",
		"photos",
		"uri",
		"mysql_host",
		"mysql_user",
		"mysql_pass",
		"mysql_table"
	);
	foreach($array as $item) {
		if(!isset($config[$item])) $error=$item;
		elseif(strlen($config[$item])==0) $error=$item;
	}
	if(!strpos($_SERVER['REQUEST_URI'],'admin.php') && isset($error)) return false;
	else {
		if(file_exists('langs/'.$config['lang'].'.php')) return true;
		else return false;
	}
}


/**
 * returns html stripped n chars of a string
 * @param string $input original text
 * @param int $chars number of characters to show on preview
 * @return string
 */
function eb_textpreview($input,$chars) {
	settype($chars,"integer");
	$output=strip_tags($input);
	$output=str_replace("\r","",$output);
	$output=str_replace("\n"," ",$output);
	if(strlen(trim($output))>$chars) {
		$output=substr($output,0,$chars);
		// uncomment to not cut textpreview mid-words
		// $output=substr($output,0,strlen($output)-strpos(strrev($output)," "));

		// prevent cutting html entity
		if(strpos($output,";")) {
			$i=strrpos($output,";");
			$output=substr($output,0,$i);
			$output.=substr($input,$i,$chars-$i);
			$output.="...";
		}
		else $output.="...";
	}
	return $output;
}


/**
 * print error message
 * @param varchar $id error code
 */
function eb_error($id) {
	global $lang;
	if($_GET['id']=="install") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p>".$lang['del_install']."</p>\r\n";
	elseif($_GET['id']=="mysql") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p><a href=\"admin.php?id=config\">".$lang['error_mysql']."</a>.</p>\r\n";
	elseif($_GET['id']=="mysql_table") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p><a href=\"admin.php?id=config\">".$lang['error_mysql_table']."</a>.</p>\r\n";
	elseif($_GET['id']=="config") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p>".$lang['error_config']."</p>\r\n";
	elseif($_GET['id']=="upgrade") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p>".$lang['del_upgrade']."</p>\r\n";
	elseif($_GET['id']=="config-rights") return "\t\t<h3>".ucwords($lang['error'])."</h3>\r\n\t\t<p>".$lang['error_config_rights']."</p>\r\n";
}


/*
 * return a string with links href'd
 * @return string
 */
function eb_linkable($text) {
	$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
	$ret = ' ' . $text;
	$ret = preg_replace("#(^|[\n ]|>)([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" rel=\"nofollow\">\\2</a>", $ret);
	$ret = preg_replace("#(^|[\n ]|>)((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" rel=\"nofollow\">\\2</a>", $ret);
	$ret = preg_replace("#(^|[\n ]|>)([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\" rel=\"nofollow\">\\2@\\3</a>", $ret);
	$ret = substr($ret, 1); 
	return $ret; 
}


/**
 * print list of page numbers
 * @param int $n number of items per page
 * @param int $i page to show
 * @param int $total total number of items
 * @param string $file filename to use in uri (filename.php?)
 * @return string
 */
function eb_pages($n,$i,$total,$file) {
	$pages=ceil($total/$n);
	if($i>$pages || $i<=0) $i=$pages;

	$output="\t\t\t<ul id=\"pages\">\r\n";
	for($count=1;$count<=$pages;$count++) {
		if($count>=$i-2 && $count<=$i+2) {
			$output.="\t\t\t\t<li";
			if($count==$i) $output.=" class=\"on\"";
			$output.="><a href=\"".$file."i=".$count."\">".$count."</a></li>\t\n";
		}
		elseif($count==$pages && $count==$i+3) {
			$output.="\t\t\t\t<li><a href=\"".$file."i=".$count."\">".$count."</a></li>\t\n";
		}
		elseif($count==$pages) {
			$output.="\t\t\t\t<li class=\"clear\">...</li>\t\n";
			$output.="\t\t\t\t<li><a href=\"".$file."i=".$count."\">".$count."</a></li>\t\n";
		}
		elseif($count==1 && $count==$i-3) {
			$output.="\t\t\t\t<li><a href=\"".$file."i=".$count."\">".$count."</a></li>\t\n";
		}
		elseif($count==1) {
			$output.="\t\t\t\t<li><a href=\"".$file."i=".$count."\">".$count."</a></li>\t\n";
			$output.="\t\t\t\t<li class=\"clear\">...</li>\t\n";
		}
	}
	$output.="\t\t\t</ul>\r\n";
	return $output;
}


/**
 * @param 
 */
function eb_captcha_image() {
	$possible_chars="23456789abcdefghjkmnpqrstuvwxyz";
	$captchacode="";
	for($i=1;$i<=6;$i++) {
		$char=substr($possible_chars,mt_rand(0,strlen($possible_chars)-1),1);
		if (!strstr($captchacode,$char)) $captchacode.=$char;
		else $i--;
	}
	if(!empty($_SESSION['captcha'])) unset($_SESSION['captcha']);
	$_SESSION['captcha']=$captchacode;
	$width="130";
	$height="45";
	$image=imagecreate($width,$height);
	$bg=imagecolorallocate($image,0,0,0);
	$text=imagecolorallocate($image,245,245,245);
	$line=imagecolorallocate($image,160,160,160);
	for($i=0;$i<($width*$height)/2;$i++) imagefilledellipse($image,mt_rand(0,$width),mt_rand(0,$height),1,1,$line);
	for($i=0;$i<($width*$height)/150;$i++) imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$line);
	$font='_lib/captcha.ttf';
	imagettftext($image,20,0,10,32,$text,$font,$captchacode);
	header('Content-type: image/png');
	imagepng($image);
	imagedestroy($image);
}

?>