<?php
/*---------------------------------------------------+
| PHP-Fusion 6 Content Management System
+----------------------------------------------------+
| Copyright © 2002 - 2006 Nick Jones
| http://www.php-fusion.co.uk/
+----------------------------------------------------+
| Released under the terms & conditions of v2 of the
| GNU General Public License. For details refer to
| the included gpl.txt file or visit http://gnu.org
+----------------------------------------------------+
| Modified by PHP-Fusion SF Group
| Copyright © 2007 by SF
| http://www.rus-phpfusion.com/
+----------------------------------------------------*/
if (preg_match("/maincore.php/i", $_SERVER['PHP_SELF'])) die();

// If register_globals is turned off, extract super globals (php 4.2.0+)
if (ini_get('register_globals') != 1) {
	if ((isset($_POST) == true) && (is_array($_POST) == true)) extract($_POST, EXTR_OVERWRITE);
	if ((isset($_GET) == true) && (is_array($_GET) == true)) extract($_GET, EXTR_OVERWRITE);
}

// Prevent any possible XSS attacks via $_GET.
foreach ($_GET as $check_url) {
	if ((preg_match("/<[^>]*script*\"?[^>]*>/i", $check_url)) || (preg_match("/<[^>]*object*\"?[^>]*>/i", $check_url)) ||
		(preg_match("/<[^>]*iframe*\"?[^>]*>/i", $check_url)) || (preg_match("/<[^>]*applet*\"?[^>]*>/i", $check_url)) ||
		(preg_match("/<[^>]*meta*\"?[^>]*>/i", $check_url)) || (preg_match("/<[^>]*style*\"?[^>]*>/i", $check_url)) ||
		(preg_match("/<[^>]*form*\"?[^>]*>/i", $check_url)) || (preg_match("/\([^>]*\"?[^)]*\)/i", $check_url)) ||
		(preg_match("/\"/i", $check_url))) {
	die ();
	}
}
unset($check_url);

//Cache control
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 
header('Cache-Control: no-store, no-cache, must-revalidate'); 
header('Cache-Control: post-check=0, pre-check=0', FALSE); 
header('Pragma: no-cache');

// Start Output Buffering
ob_start();

//Error Reporting
//error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Locate config.php and set the basedir path
$folder_level = "";
while (!file_exists($folder_level."config.php")) { $folder_level .= "../"; }
require_once $folder_level."config.php";
define("BASEDIR", $folder_level);

// Establish mySQL database connection
$link = dbconnect($db_host, $db_user, $db_pass, $db_name);

// Fetch the Site Settings from the database and store them in the $settings variable
$settings = dbarray(dbquery("SELECT * FROM ".$db_prefix."settings"));
@$settings_forum = dbarray(dbquery("SELECT * FROM ".$db_prefix."forum_settings"));

// Sanitise $_SERVER globals
$_SERVER['PHP_SELF'] = cleanurl($_SERVER['PHP_SELF']);
$_SERVER['QUERY_STRING'] = isset($_SERVER['QUERY_STRING']) ? cleanurl($_SERVER['QUERY_STRING']) : "";
$_SERVER['REQUEST_URI'] = isset($_SERVER['REQUEST_URI']) ? cleanurl($_SERVER['REQUEST_URI']) : "";
$PHP_SELF = cleanurl($_SERVER['PHP_SELF']);
// Common definitions
define("IN_FUSION", TRUE);
define("FUSION_REQUEST", isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != "" ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME']);
define("FUSION_QUERY", isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : "");
define("FUSION_SELF", basename($_SERVER['PHP_SELF']));
define("FUSION_IP", $_SERVER['REMOTE_ADDR']);
define("USER_IP", $_SERVER['REMOTE_ADDR']);
define("QUOTES_GPC", (ini_get('magic_quotes_gpc') ? TRUE : FALSE));
// Path definitions
define("ADMIN", BASEDIR."administration/");
define("IMAGES", BASEDIR."images/");
define("IMAGES_A", IMAGES."articles/");
define("IMAGES_N", IMAGES."news/");
define("IMAGES_NC", IMAGES."news_cats/");
define("INCLUDES", BASEDIR."includes/");
define("LOCALE", BASEDIR."locale/");
define("LOCALESET", $settings['locale']."/");
define("FORUM", BASEDIR."forum/");
define("INFUSIONS", BASEDIR."infusions/");
define("PHOTOS", IMAGES."photoalbum/");
define("THEMES", BASEDIR."themes/");

// MySQL database functions
function dbquery($query) {
	$result = @mysql_query($query);
	if (!$result) {
		echo mysql_error();
		return false;
	} else {
		return $result;
	}
}

function dbcount($field,$table,$conditions="") {
	$cond = ($conditions ? " WHERE ".$conditions : "");
	$result = @mysql_query("SELECT Count".$field." FROM ".DB_PREFIX.$table.$cond);
	if (!$result) {
		echo mysql_error();
		return false;
	} else {
		$rows = mysql_result($result, 0);
		return $rows;
	}
}

function dbresult($query, $row) {
	$result = @mysql_result($query, $row);
	if (!$result) {
		echo mysql_error();
		return false;
	} else {
		return $result;
	}
}

function dbrows($query) {
	$result = @mysql_num_rows($query);
	return $result;
}

function dbarray($query) {
	$result = @mysql_fetch_assoc($query);
	if (!$result) {
		echo mysql_error();
		return false;
	} else {
		return $result;
	}
}

function dbarraynum($query) {
	$result = @mysql_fetch_row($query);
	if (!$result) {
		echo mysql_error();
		return false;
	} else {
		return $result;
	}
}

function dbconnect($db_host, $db_user, $db_pass, $db_name) {
	$db_connect = @mysql_connect($db_host, $db_user, $db_pass);
	$db_select = @mysql_select_db($db_name);
	if (!$db_connect) {
		die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to establish connection to MySQL</b><br>".mysql_errno()." : ".mysql_error()."</div>");
	} elseif (!$db_select) {
		die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to select MySQL database</b><br>".mysql_errno()." : ".mysql_error()."</div>");
	}
}

// Initialise the $locale array
$locale = array();
// Load the Global language file
include LOCALE.LOCALESET."global.php";

// Check if users full or partial ip is blacklisted
$sub_ip1 = substr(USER_IP,0,strlen(USER_IP)-strlen(strrchr(USER_IP,".")));
$sub_ip2 = substr($sub_ip1,0,strlen($sub_ip1)-strlen(strrchr($sub_ip1,".")));
if (dbcount("(*)", "blacklist", "blacklist_ip='".USER_IP."' OR blacklist_ip='$sub_ip1' OR blacklist_ip='$sub_ip2'")) {
	header("Location: http://www.google.com/"); exit;
}

// PHP-Fusion user cookie functions
if (!isset($_COOKIE['fusion_visited'])) {
	$result=dbquery("UPDATE ".$db_prefix."settings SET counter=counter+1");
	setcookie("fusion_visited", "yes", time() + 31536000, "/", "", "0");
}


$return_path = FUSION_SELF.(FUSION_QUERY != "" ? "?".FUSION_QUERY : "");
setcookie("return_path", $return_path, time() + 3600 * 3, "/", "", "0");

// PHP-Fusion user cookie functions

if (isset($_POST['login'])) {
	$user_pass = md5($_POST['user_pass']);
	$user_name = preg_replace(array("/\=/","/\#/","/\sOR\s/"), "", stripinput($_POST['user_name']));
	$result = dbquery("SELECT * FROM ".$db_prefix."users WHERE user_name='$user_name' AND (user_password='".md5($user_pass)."' OR user_password='$user_pass')");
	if (dbrows($result) != 0) {
		$data = dbarray($result);
		if ($data['user_password'] == $user_pass) {
			$result = dbquery("UPDATE ".$db_prefix."users SET user_password='".md5($user_pass)."' WHERE user_id='".$data['user_id']."'");
			}
		$cookie_value = $data['user_id'].".".$user_pass;
		if ($data['user_status'] == 0) {	
			$cookie_exp = isset($_POST['remember_me']) ? time() + 3600*24*30 : time() + 3600*3;
			header("P3P: CP='NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM'");
			setcookie("fusion_user", $cookie_value, $cookie_exp, "/", "", "0");
			redirect(BASEDIR."setuser.php?user=".$data['user_name'], "script");
		} elseif ($data['user_status'] == 1) {
			redirect(BASEDIR."setuser.php?error=1", "script");
		} elseif ($data['user_status'] == 2) {
			redirect(BASEDIR."setuser.php?error=2", "script");
		}
	} else {
		redirect(BASEDIR."setuser.php?error=3");
	}
}

if (isset($_POST['login_forum'])) {
	$user_pass = md5($_POST['user_pass']);
	$user_name = preg_replace(array("/\=/","/\#/","/\sOR\s/"), "", stripinput($_POST['user_name']));
	$result = dbquery("SELECT * FROM ".$db_prefix."users WHERE user_name='$user_name' AND (user_password='".md5($user_pass)."' OR user_password='$user_pass')");
	if (dbrows($result) != 0) {
		$data = dbarray($result);
		if ($data['user_password'] == $user_pass) {
			$result = dbquery("UPDATE ".$db_prefix."users SET user_password='".md5($user_pass)."' WHERE user_id='".$data['user_id']."'");
		}
		$cookie_value = $data['user_id'].".".$user_pass;
		if ($data['user_status'] == 0) {	
			$cookie_exp = isset($_POST['remember_me']) ? time() + 3600*24*30 : time() + 3600*3;
			header("P3P: CP='NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM'");
			setcookie("fusion_user", $cookie_value, $cookie_exp, "/", "", "0");
			redirect(BASEDIR."setuser_forum.php?user=".$data['user_name'], "script");
		} elseif ($data['user_status'] == 1) {
			redirect(BASEDIR."setuser_forum.php?error=1", "script");
		} elseif ($data['user_status'] == 2) {
			redirect(BASEDIR."setuser_forum.php?error=2", "script");
		}
	} else {
		redirect(BASEDIR."setuser_forum.php?error=3");
	}
}

if (isset($_COOKIE['fusion_user'])) {
	$cookie_vars = explode(".", $_COOKIE['fusion_user']);
	$cookie_1 = isNum($cookie_vars['0']) ? $cookie_vars['0'] : "0";
	$cookie_2 = (preg_match("/^[0-9a-z]{32}$/", $cookie_vars['1']) ? $cookie_vars['1'] : "");
	$result = dbquery("SELECT * FROM ".$db_prefix."users WHERE user_id='$cookie_1' AND user_password='".md5($cookie_2)."'");
	unset($cookie_vars,$cookie_1,$cookie_2);
	if (dbrows($result) != 0) {
		$userdata = dbarray($result);
		if ($userdata['user_status'] == 0) {
			if ($userdata['user_theme'] != "Default" && file_exists(THEMES.$userdata['user_theme']."/theme.php")) {
				define("THEME", THEMES.$userdata['user_theme']."/");
			} else {
				define("THEME", THEMES.$settings['theme']."/");
			}
			if ($userdata['user_offset'] <> 0) {
				$settings['timeoffset'] = $settings['timeoffset'] + $userdata['user_offset'];
			}
			if (empty($_COOKIE['fusion_lastvisit'])) {
				setcookie("fusion_lastvisit", $userdata['user_lastvisit'], time() + 3600, "/", "", "0");
				$lastvisited = $userdata['user_lastvisit'];
			} else {
				$lastvisited = $_COOKIE['fusion_lastvisit'];
			}
		} else {
			header("P3P: CP='NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM'");
			setcookie("fusion_user", "", time() - 7200, "/", "", "0");
			setcookie("fusion_lastvisit", "", time() - 7200, "/", "", "0");
			redirect(BASEDIR."index.php", "script");
		}
	} else {
		header("P3P: CP='NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM'");
		setcookie("fusion_user", "", time() - 7200, "/", "", "0");
		setcookie("fusion_lastvisit", "", time() - 7200, "/", "", "0");
		redirect(BASEDIR."index.php", "script");
	}
} else {
	define("THEME", THEMES.$settings['theme']."/");
	$userdata = "";	$userdata['user_level'] = 0; $userdata['user_rights'] = ""; $userdata['user_groups'] = "";
}

// Redirect browser using the header function
function redirect($location, $type="header") {
	if ($type == "header") {
		header("Location: ".$location);
	} else {
		echo "<script type='text/javascript'>document.location.href='".$location."'</script>\n";
	}
}

// Fallback to safe area in event of unauthorised access
function fallback($location) {
	header("Location: ".$location);
	exit;
}

// Clean URL Function, prevents entities in server globals
function cleanurl($url) {
	$bad_entities = array("&", "\"", "'", '\"', "\'", "<", ">", "(", ")", "*");
	$safe_entities = array("&amp;", "", "", "", "", "", "", "", "", "");
	$url = str_replace($bad_entities, $safe_entities, $url);
	return $url;
}

// Strip Input Function, prevents HTML in unwanted places
function stripinput($text) {
	if (QUOTES_GPC) $text = stripslashes($text);
	$search = array("\"", "'", "\\", '\"', "\'", "<", ">", "&nbsp;");
	$replace = array("&quot;", "&#39;", "&#92;", "&quot;", "&#39;", "&lt;", "&gt;", " ");
	$text = str_replace($search, $replace, $text);
	return $text;
}

// stripslash function, only stripslashes if magic_quotes_gpc is on
function stripslash($text) {
	if (QUOTES_GPC) $text = stripslashes($text);
	return $text;
}

// stripslash function, add correct number of slashes depending on quotes_gpc
function addslash($text) {
	if (!QUOTES_GPC) {
		$text = addslashes(addslashes($text));
	} else {
		$text = addslashes($text);
	}
	return $text;
}

// htmlentities is too agressive so we use this function
function phpentities($text) {
	$search = array("&", "\"", "'", "\\", "<", ">");
	$replace = array("&amp;", "&quot;", "&#39;", "&#92;", "&lt;", "&gt;");
	$text = str_replace($search, $replace, $text);
	return $text;
}

// Trim a line of text to a preferred length
function trimlink($text, $length) {
	$dec = array("\"", "'", "\\", '\"', "\'", "<", ">");
	$enc = array("&quot;", "&#39;", "&#92;", "&quot;", "&#39;", "&lt;", "&gt;");
	$text = str_replace($enc, $dec, $text);
	if (strlen($text) > $length) $text = substr($text, 0, ($length-3))."...";
	$text = str_replace($dec, $enc, $text);
	return $text;
}

// Validate numeric input
function isNum($value) {
	return (preg_match("/^[0-9]+$/", $value));
}

// Parse smiley bbcode into HTML images
function parsesmileys($message) {
	$smiley = array(
		"#\:\)#si" => "<img src='".IMAGES."smiley/smile.gif' alt='smiley'>",
		"#\;\)#si" => "<img src='".IMAGES."smiley/wink.gif' alt='smiley'>",
		"#\:\(#si" => "<img src='".IMAGES."smiley/sad.gif' alt='smiley'>",
		"#\:\|#si" => "<img src='".IMAGES."smiley/frown.gif' alt='smiley'>",
		"#\:o#si" => "<img src='".IMAGES."smiley/shock.gif' alt='smiley'>",
		"#\:p#si" => "<img src='".IMAGES."smiley/pfft.gif' alt='smiley'>",
		"#b\)#si" => "<img src='".IMAGES."smiley/cool.gif' alt='smiley'>",
		"#\:d#si" => "<img src='".IMAGES."smiley/grin.gif' alt='smiley'>",
		"#\:@#si" => "<img src='".IMAGES."smiley/angry.gif' alt='smiley'>",
		"#f_emo_01#si" => "<img src='".IMAGES."smiley/emo/f_emo_01.gif' alt='smiley'>",
		"#f_emo_02#si" => "<img src='".IMAGES."smiley/emo/f_emo_02.gif' alt='smiley'>",
		"#f_emo_03#si" => "<img src='".IMAGES."smiley/emo/f_emo_03.gif' alt='smiley'>",
		"#f_emo_04#si" => "<img src='".IMAGES."smiley/emo/f_emo_04.gif' alt='smiley'>",
		"#f_emo_05#si" => "<img src='".IMAGES."smiley/emo/f_emo_05.gif' alt='smiley'>",
		"#f_emo_06#si" => "<img src='".IMAGES."smiley/emo/f_emo_06.gif' alt='smiley'>",
		"#f_emo_07#si" => "<img src='".IMAGES."smiley/emo/f_emo_07.gif' alt='smiley'>",
		"#f_emo_08#si" => "<img src='".IMAGES."smiley/emo/f_emo_08.gif' alt='smiley'>",
		"#f_emo_09#si" => "<img src='".IMAGES."smiley/emo/f_emo_09.gif' alt='smiley'>",
		"#f_emo_10#si" => "<img src='".IMAGES."smiley/emo/f_emo_10.gif' alt='smiley'>",
		"#f_emo_11#si" => "<img src='".IMAGES."smiley/emo/f_emo_11.gif' alt='smiley'>",
		"#f_emo_12#si" => "<img src='".IMAGES."smiley/emo/f_emo_12.gif' alt='smiley'>",
		"#f_emo_13#si" => "<img src='".IMAGES."smiley/emo/f_emo_13.gif' alt='smiley'>",
		"#f_emo_14#si" => "<img src='".IMAGES."smiley/emo/f_emo_14.gif' alt='smiley'>",
		"#f_emo_15#si" => "<img src='".IMAGES."smiley/emo/f_emo_15.gif' alt='smiley'>",
		"#f_emo_16#si" => "<img src='".IMAGES."smiley/emo/f_emo_16.gif' alt='smiley'>",
		"#f_emo_17#si" => "<img src='".IMAGES."smiley/emo/f_emo_17.gif' alt='smiley'>",
		"#f_emo_18#si" => "<img src='".IMAGES."smiley/emo/f_emo_18.gif' alt='smiley'>",
		"#f_emo_19#si" => "<img src='".IMAGES."smiley/emo/f_emo_19.gif' alt='smiley'>",
		"#f_emo_20#si" => "<img src='".IMAGES."smiley/emo/f_emo_20.gif' alt='smiley'>",
		"#f_emo_21#si" => "<img src='".IMAGES."smiley/emo/f_emo_21.gif' alt='smiley'>",
		"#f_emo_22#si" => "<img src='".IMAGES."smiley/emo/f_emo_22.gif' alt='smiley'>",
		"#f_emo_23#si" => "<img src='".IMAGES."smiley/emo/f_emo_23.gif' alt='smiley'>",
		"#f_emo_24#si" => "<img src='".IMAGES."smiley/emo/f_emo_24.gif' alt='smiley'>",
		"#f_emo_25#si" => "<img src='".IMAGES."smiley/emo/f_emo_25.gif' alt='smiley'>",
		"#f_emo_26#si" => "<img src='".IMAGES."smiley/emo/f_emo_26.gif' alt='smiley'>",
		"#f_emo_27#si" => "<img src='".IMAGES."smiley/emo/f_emo_27.gif' alt='smiley'>",
		"#f_emo_28#si" => "<img src='".IMAGES."smiley/emo/f_emo_28.gif' alt='smiley'>",
		"#f_emo_29#si" => "<img src='".IMAGES."smiley/emo/f_emo_29.gif' alt='smiley'>",
		"#f_emo_30#si" => "<img src='".IMAGES."smiley/emo/f_emo_30.gif' alt='smiley'>",
		"#f_emo_31#si" => "<img src='".IMAGES."smiley/emo/f_emo_31.gif' alt='smiley'>",
		"#f_emo_32#si" => "<img src='".IMAGES."smiley/emo/f_emo_32.gif' alt='smiley'>",
		"#f_emo_33#si" => "<img src='".IMAGES."smiley/emo/f_emo_33.gif' alt='smiley'>",
		"#f_emo_34#si" => "<img src='".IMAGES."smiley/emo/f_emo_34.gif' alt='smiley'>",
		"#f_emo_35#si" => "<img src='".IMAGES."smiley/emo/f_emo_35.gif' alt='smiley'>",
		"#f_emo_36#si" => "<img src='".IMAGES."smiley/emo/f_emo_36.gif' alt='smiley'>",
		"#f_emo_37#si" => "<img src='".IMAGES."smiley/emo/f_emo_37.gif' alt='smiley'>",
		"#f_emo_38#si" => "<img src='".IMAGES."smiley/emo/f_emo_38.gif' alt='smiley'>",
		"#f_emo_39#si" => "<img src='".IMAGES."smiley/emo/f_emo_39.gif' alt='smiley'>",
		"#f_emo_40#si" => "<img src='".IMAGES."smiley/emo/f_emo_40.gif' alt='smiley'>",
		"#f_emo_41#si" => "<img src='".IMAGES."smiley/emo/f_emo_41.gif' alt='smiley'>",
		"#f_emo_42#si" => "<img src='".IMAGES."smiley/emo/f_emo_42.gif' alt='smiley'>",
		"#f_emo_43#si" => "<img src='".IMAGES."smiley/emo/f_emo_43.gif' alt='smiley'>",
		"#f_emo_44#si" => "<img src='".IMAGES."smiley/emo/f_emo_44.gif' alt='smiley'>",
		"#f_emo_45#si" => "<img src='".IMAGES."smiley/emo/f_emo_45.gif' alt='smiley'>",
		"#f_emo_46#si" => "<img src='".IMAGES."smiley/emo/f_emo_46.gif' alt='smiley'>",
		"#f_emo_47#si" => "<img src='".IMAGES."smiley/emo/f_emo_47.gif' alt='smiley'>",
		"#f_emo_48#si" => "<img src='".IMAGES."smiley/emo/f_emo_48.gif' alt='smiley'>",
		"#f_emo_49#si" => "<img src='".IMAGES."smiley/emo/f_emo_49.gif' alt='smiley'>",
		"#f_emo_50#si" => "<img src='".IMAGES."smiley/emo/f_emo_50.gif' alt='smiley'>",
		"#f_emo_51#si" => "<img src='".IMAGES."smiley/emo/f_emo_51.gif' alt='smiley'>",
		"#f_emo_52#si" => "<img src='".IMAGES."smiley/emo/f_emo_52.gif' alt='smiley'>",
		"#f_emo_53#si" => "<img src='".IMAGES."smiley/emo/f_emo_53.gif' alt='smiley'>",
		"#f_emo_54#si" => "<img src='".IMAGES."smiley/emo/f_emo_54.gif' alt='smiley'>",
		"#f_emo_55#si" => "<img src='".IMAGES."smiley/emo/f_emo_55.gif' alt='smiley'>",
		"#f_emo_56#si" => "<img src='".IMAGES."smiley/emo/f_emo_56.gif' alt='smiley'>",
		"#f_emo_57#si" => "<img src='".IMAGES."smiley/emo/f_emo_57.gif' alt='smiley'>",
		"#f_emo_58#si" => "<img src='".IMAGES."smiley/emo/f_emo_58.gif' alt='smiley'>",
		"#f_emo_59#si" => "<img src='".IMAGES."smiley/emo/f_emo_59.gif' alt='smiley'>",
		"#f_emo_60#si" => "<img src='".IMAGES."smiley/emo/f_emo_60.gif' alt='smiley'>",
		"#f_emo_61#si" => "<img src='".IMAGES."smiley/emo/f_emo_61.gif' alt='smiley'>",
		"#f_emo_62#si" => "<img src='".IMAGES."smiley/emo/f_emo_62.gif' alt='smiley'>",
		"#f_emo_63#si" => "<img src='".IMAGES."smiley/emo/f_emo_63.gif' alt='smiley'>",
		"#f_emo_64#si" => "<img src='".IMAGES."smiley/emo/f_emo_64.gif' alt='smiley'>",
		"#f_emo_65#si" => "<img src='".IMAGES."smiley/emo/f_emo_65.gif' alt='smiley'>",
		"#f_emo_66#si" => "<img src='".IMAGES."smiley/emo/f_emo_66.gif' alt='smiley'>",
		"#f_emo_67#si" => "<img src='".IMAGES."smiley/emo/f_emo_67.gif' alt='smiley'>",
		"#f_emo_68#si" => "<img src='".IMAGES."smiley/emo/f_emo_68.gif' alt='smiley'>",
		"#f_emo_69#si" => "<img src='".IMAGES."smiley/emo/f_emo_69.gif' alt='smiley'>",
		"#f_emo_70#si" => "<img src='".IMAGES."smiley/emo/f_emo_70.gif' alt='smiley'>",
		"#f_emo_71#si" => "<img src='".IMAGES."smiley/emo/f_emo_71.gif' alt='smiley'>",
		"#f_emo_72#si" => "<img src='".IMAGES."smiley/emo/f_emo_72.gif' alt='smiley'>",
		"#f_emo_73#si" => "<img src='".IMAGES."smiley/emo/f_emo_73.gif' alt='smiley'>",
		"#f_emo_74#si" => "<img src='".IMAGES."smiley/emo/f_emo_74.gif' alt='smiley'>",
		"#f_emo_75#si" => "<img src='".IMAGES."smiley/emo/f_emo_75.gif' alt='smiley'>",
		"#f_emo_76#si" => "<img src='".IMAGES."smiley/emo/f_emo_76.gif' alt='smiley'>",
		"#f_emo_77#si" => "<img src='".IMAGES."smiley/emo/f_emo_77.gif' alt='smiley'>",
		"#f_emo_78#si" => "<img src='".IMAGES."smiley/emo/f_emo_78.gif' alt='smiley'>",
		"#f_emo_79#si" => "<img src='".IMAGES."smiley/emo/f_emo_79.gif' alt='smiley'>",
		"#f_emo_80#si" => "<img src='".IMAGES."smiley/emo/f_emo_80.gif' alt='smiley'>",
		"#f_emo_81#si" => "<img src='".IMAGES."smiley/emo/f_emo_81.gif' alt='smiley'>",
		"#f_emo_82#si" => "<img src='".IMAGES."smiley/emo/f_emo_82.gif' alt='smiley'>",
		"#f_emo_83#si" => "<img src='".IMAGES."smiley/emo/f_emo_83.gif' alt='smiley'>",
		"#f_emo_84#si" => "<img src='".IMAGES."smiley/emo/f_emo_84.gif' alt='smiley'>",
		"#f_emo_85#si" => "<img src='".IMAGES."smiley/emo/f_emo_85.gif' alt='smiley'>",
	);
	foreach($smiley as $key=>$smiley_img) $message = preg_replace($key, $smiley_img, $message);
	return $message;
}

// Show smiley icons in comments, forum and other post pages
function displaysmileys($textarea) {
	$smiles = "";
	$smileys = array (
		":)" => "smile.gif",
		";)" => "wink.gif",
		":|" => "frown.gif",
		":(" => "sad.gif",
		":o" => "shock.gif",
		":p" => "pfft.gif",
		"B)" => "cool.gif",
		":D" => "grin.gif",
		":@" => "angry.gif"
	);
	foreach($smileys as $key=>$smiley) $smiles .= "<img src='".IMAGES."smiley/$smiley' alt='smiley' onClick=\"insertText('$textarea', '$key');\">\n";
	return $smiles;
}

// Show smiley icons in comments, forum and other post pages 2
function displayemo($textarea) {
	$smiles = "";
	$smileys = array (
		"f_emo_01" => "f_emo_01.gif",
		"f_emo_02" => "f_emo_02.gif",
		"f_emo_03" => "f_emo_03.gif",
		"f_emo_04" => "f_emo_04.gif",
		"f_emo_05" => "f_emo_05.gif",
		"f_emo_06" => "f_emo_06.gif",
		"f_emo_07" => "f_emo_07.gif",
		"f_emo_08" => "f_emo_08.gif",
		"f_emo_09" => "f_emo_09.gif",
		"f_emo_10" => "f_emo_10.gif",
		"f_emo_11" => "f_emo_11.gif",
		"f_emo_12" => "f_emo_12.gif",
		"f_emo_13" => "f_emo_13.gif",
		"f_emo_14" => "f_emo_14.gif",
		"f_emo_15" => "f_emo_15.gif",
		"f_emo_16" => "f_emo_16.gif",
		"f_emo_17" => "f_emo_17.gif",
		"f_emo_18" => "f_emo_18.gif",
		"f_emo_19" => "f_emo_19.gif",
		"f_emo_20" => "f_emo_20.gif",
		"f_emo_21" => "f_emo_21.gif",
		"f_emo_22" => "f_emo_22.gif",
		"f_emo_23" => "f_emo_23.gif",
		"f_emo_24" => "f_emo_24.gif",
		"f_emo_25" => "f_emo_25.gif",
		"f_emo_26" => "f_emo_26.gif",
		"f_emo_27" => "f_emo_27.gif",
		"f_emo_28" => "f_emo_28.gif",
		"f_emo_29" => "f_emo_29.gif",
		"f_emo_30" => "f_emo_30.gif",
		"f_emo_31" => "f_emo_31.gif",
		"f_emo_32" => "f_emo_32.gif",
		"f_emo_33" => "f_emo_33.gif",
		"f_emo_34" => "f_emo_34.gif",
		"f_emo_35" => "f_emo_35.gif",
		"f_emo_36" => "f_emo_36.gif",
		"f_emo_37" => "f_emo_37.gif",
		"f_emo_38" => "f_emo_38.gif",
		"f_emo_39" => "f_emo_39.gif",
		"f_emo_40" => "f_emo_40.gif",
		"f_emo_41" => "f_emo_41.gif",
		"f_emo_42" => "f_emo_42.gif",
		"f_emo_43" => "f_emo_43.gif",
		"f_emo_44" => "f_emo_44.gif",
		"f_emo_45" => "f_emo_45.gif",
		"f_emo_46" => "f_emo_46.gif",
		"f_emo_47" => "f_emo_47.gif",
		"f_emo_48" => "f_emo_48.gif",
		"f_emo_49" => "f_emo_49.gif",
		"f_emo_50" => "f_emo_50.gif",
		"f_emo_51" => "f_emo_51.gif",
		"f_emo_52" => "f_emo_52.gif",
		"f_emo_53" => "f_emo_53.gif",
		"f_emo_54" => "f_emo_54.gif",
		"f_emo_55" => "f_emo_55.gif",
		"f_emo_56" => "f_emo_56.gif",
		"f_emo_57" => "f_emo_57.gif",
		"f_emo_58" => "f_emo_58.gif",
		"f_emo_59" => "f_emo_59.gif",
		"f_emo_60" => "f_emo_60.gif",
		"f_emo_61" => "f_emo_61.gif",
		"f_emo_62" => "f_emo_62.gif",
		"f_emo_63" => "f_emo_63.gif",
		"f_emo_64" => "f_emo_64.gif",
		"f_emo_65" => "f_emo_65.gif",
		"f_emo_66" => "f_emo_66.gif",
		"f_emo_67" => "f_emo_67.gif",
		"f_emo_68" => "f_emo_68.gif",
		"f_emo_69" => "f_emo_69.gif",
		"f_emo_70" => "f_emo_70.gif",
		"f_emo_71" => "f_emo_71.gif",
		"f_emo_72" => "f_emo_72.gif",
		"f_emo_73" => "f_emo_73.gif",
		"f_emo_74" => "f_emo_74.gif",
		"f_emo_75" => "f_emo_75.gif",
		"f_emo_76" => "f_emo_76.gif",
		"f_emo_77" => "f_emo_77.gif",
		"f_emo_78" => "f_emo_78.gif",
		"f_emo_79" => "f_emo_79.gif",
		"f_emo_80" => "f_emo_80.gif",
		"f_emo_81" => "f_emo_81.gif",
		"f_emo_82" => "f_emo_82.gif",
		"f_emo_83" => "f_emo_83.gif",
		"f_emo_84" => "f_emo_84.gif",
		"f_emo_85" => "f_emo_85.gif"
		
		
	);	
	foreach($smileys as $key=>$smiley) $smiles .= "<img src='".IMAGES."smiley/emo/$smiley' alt='smiley' onClick=\"insertText('$textarea', '$key');\">\n";
	return $smiles;
}

// Parse bbcode into HTML code
function parseubb($text) {
	$text = preg_replace('#\[b\](.*?)\[/b\]#si', '<b>\1</b>', $text);
	
	$text = preg_replace('#\[i\](.*?)\[/i\]#si', '<i>\1</i>', $text);
	$text = preg_replace('#\[u\](.*?)\[/u\]#si', '<u>\1</u>', $text);
	$text = preg_replace('#\[center\](.*?)\[/center\]#si', '<center>\1</center>', $text);
	
	$text = preg_replace('#\[url\]([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";\+]*?)([\r\n]*)\[/url\]#si', '<a href=\'\2\3\' target=\'_blank\'>\2\3</a>', $text);
	$text = preg_replace('#\[url\]([\r\n]*)([^\s\'\";\+]*?)([\r\n]*)\[/url\]#si', '<a href=\'http://\2\' target=\'_blank\'>\2</a>', $text);
	$text = preg_replace('#\[url=([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";\+]*?)\](.*?)([\r\n]*)\[/url\]#si', '<a href=\'\2\3\' target=\'_blank\'>\4</a>', $text);
	$text = preg_replace('#\[url=([\r\n]*)([^\s\'\";\+]*?)\](.*?)([\r\n]*)\[/url\]#si', '<a href=\'http://\2\' target=\'_blank\'>\3</a>', $text);
	
	$text = preg_replace('#\[mail\]([\r\n]*)([^\s\'\";:\+]*?)([\r\n]*)\[/mail\]#si', '<a href=\'mailto:\2\'>\2</a>', $text);
	$text = preg_replace('#\[mail=([\r\n]*)([^\s\'\";:\+]*?)\](.*?)([\r\n]*)\[/mail\]#si', '<a href=\'mailto:\2\'>\3</a>', $text);
	
	$text = preg_replace('#\[small\](.*?)\[/small\]#si', '<span class=\'small\'>\1</span>', $text);
	$text = preg_replace('#\[color=(black|blue|brown|cyan|gray|green|lime|maroon|navy|olive|orange|purple|red|skyblue|royalblue|darkblue|gold|coral|orangered|crimson|firebrick|darkred|limegreen|seagreen|deeppink|indigo|burlywood|sandybrown|sienna|choclate|teal|silver|tomato|violet|white|yellow)\](.*?)\[/color\]#si', '<span style=\'color:\1\'>\2</span>', $text);
	
	$text = preg_replace('#\[flash width=([0-9]*?) height=([0-9]*?)\]([^\s\'\";:\+]*?)(\.swf)\[/flash\]#si', '<object classid=\'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\' codebase=\'http://active.macromedia.com/flash6/cabs/swflash.cab#version=6,0,0,0\' id=\'\3\4\' width=\'\1\' height=\'\2\'><param name=movie value=\'\3\4\'><param name=\'quality\' value=\'high\'><param name=\'bgcolor\' value=\'#ffffff\'><embed src=\'\3\4\' quality=\'high\' bgcolor=\'#ffffff\' width=\'\1\' height=\'\2\' type=\'application/x-shockwave-flash\' pluginspage=\'http://www.macromedia.com/go/getflashplayer\'></embed></object>', $text);
	$text = preg_replace("#\[img\]((http|ftp|https|ftps)://)(.*?)(\.(jpg|jpeg|gif|png|JPG|JPEG|GIF|PNG))\[/img\]#sie","'<img src=\'\\1'.str_replace(array('.php','?','&','='),'','\\3').'\\4\' style=\'border:0px\'>'",$text);
//New bbcode
	$text = preg_replace('#\[s\](.*?)\[/s\]#si', '<s>\1</s>', $text);
	$text = preg_replace('#\[left\](.*?)\[/left\]#si', '<div align=left>\1</div>', $text);
	$text = preg_replace('#\[right\](.*?)\[/right\]#si', '<div align=right>\1</div>', $text);
	$text = preg_replace('#\[surl\]([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";\+]*?)([\r\n]*)\[/surl\]#si', '<a href=\'\2\3\' target=\'_self\'>\2\3</a>', $text);
	$text = preg_replace('#\[surl\]([\r\n]*)([^\s\'\";\+]*?)([\r\n]*)\[/surl\]#si', '<a href=\'http://\2\' target=\'_self\'>\2</a>', $text);
	$text = preg_replace('#\[surl=([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";\+]*?)\](.*?)([\r\n]*)\[/surl\]#si', '<a href=\'\2\3\' target=\'_self\'>\4</a>', $text);
	$text = preg_replace('#\[surl=([\r\n]*)([^\s\'\";\+]*?)\](.*?)([\r\n]*)\[/surl\]#si', '<a href=\'http://\2\' target=\'_self\'>\3</a>', $text);

	$text = preg_replace('#\[magnet\]([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";]*?)([\r\n]*)\[/magnet\]#si', '<a href=\'\2\3\' target=\'_blank\'>\2\3</a>', $text);
	$text = preg_replace('#\[magnet\]([\r\n]*)([^\s\'\";]*?)([\r\n]*)\[/magnet\]#si', '<a href=\'\2\' target=\'_blank\'>\2</a>', $text);
	$text = preg_replace('#\[magnet=([\r\n]*)(http://|ftp://|https://|ftps://)([^\s\'\";]*?)\](.*?)([\r\n]*)\[/magnet\]#si', '<a href=\'\2\3\' target=\'_blank\'>\4</a>', $text);
	$text = preg_replace('#\[magnet=([\r\n]*)([^\s\'\";]*?)\](.*?)([\r\n]*)\[/magnet\]#si', '<a href=\'\2\' target=\'_blank\'>\3</a>', $text);
	$text = preg_replace('#\[color=([\#a-f0-9]*?)\](.*?)\[/color\]#si', '<span style=\'color:\1\'>\2</span>', $text);
	$text = preg_replace('#\[marquee\](.*?)\[/marquee\]#si', '<marquee behavior=\'alternate\'>\1</marquee>', $text);
	$text = preg_replace('#\[offtopic\](.*?)\[/offtopic\]#si', '<span style=\'font-size:10px;color: #006699\'><u>Offtopic</u>: <i>\1</i></span>', $text);
	// begin hidden block
$hide = substr_count($text, "[hide]");
	if(iMEMBER){
		for ($i=0;$i < $hide;$i++) $text = preg_replace('#\[hide\](.*?)\[/hide\]#si', '<div class=\'quote\'>Скрытый текст:<br>\1</div>', $text);
	} else {
		for ($i=0;$i < $hide;$i++) $text = preg_replace('#\[hide\](.*?)\[/hide\]#si', '<div class=\'quote\'><center>Для просмотра скрытого текста - <a href=\''.BASEDIR.'register.php\'><b>зарегистрируйтесь</b></a></center></div>', $text); 	}
	// end hidden block
	$text = preg_replace('#\[size=(4|6|8|10|12|14|16|18|20|22|24|26|28|30|32|34|36|38|40|42|44|46|48|50|52)\](.*?)\[/size\]#si', '<span style=\'font-size:\1\'>\2</span>', $text);	
	$text = preg_replace('#\[border\](.*?)\[/border\]#si', '<span style=\'border: 1px solid #006699; padding:2px\'>\1</span>', $text);
	$text = preg_replace('#\[ul\](.*?)\[/ul\]#si', '<ul>\1</ul>', $text);
$text = preg_replace('#\[ol\](.*?)\[/ol\]#si', '<ol>\1</ol>', $text);
$text = preg_replace('#\[li\](.*?)\[/li\]#si', '<li>\1</li>', $text);
$text = preg_replace('#\[list\](.*?)\[/list\]#si', '<list>\1</list>', $text);
$text = preg_replace('#\[list=a\](.*?)\[/list\]#si', '<ol type=a>\1</ol>', $text);
$text = preg_replace('#\[list=A\](.*?)\[/list\]#si', '<ol type=A>\1</ol>', $text);
$text = preg_replace('#\[list=I\](.*?)\[/list\]#si', '<ol type=I>\1</ol>', $text);
$text = preg_replace('#\[list=1\](.*?)\[/list\]#si', '<ol type=1>\1</ol>', $text);
$text = preg_replace('#\[list=*\](.*?)\[/list\]#si', '<ol type=*=\1</ol>', $text);
$text = preg_replace('#\[\*\]#si', '<li>', $text);

$text = preg_replace('#\[table\](.*?)\[/table\]#si', '<table cellpadding=\'0\' cellspacing=\'0\' width=\'100%\' class=\'border\'>\1</table>', $text);
$text = preg_replace('#\[tr\](.*?)\[/tr\]#si', '<tr>\1</tr>', $text);
$text = preg_replace('#\[th\](.*?)\[/th\]#si', '<td class=\'tbl2\'>\1</td>', $text);
$text = preg_replace('#\[td\](.*?)\[/td\]#si', '<td>\1</td>', $text);

$text = preg_replace('#\[scroll\](.*?)\[/scroll\]#si', '<span><marquee>\1</marquee></span>', $text);

$text = preg_replace('#\[blink\](.*?)\[/blink\]#si', '<blink>\1</blink>', $text);
//end new bbcode	
	$qcount = substr_count($text, "[quote]"); $ccount = substr_count($text, "[code]");
	for ($i=0;$i < $qcount;$i++) $text = preg_replace('#\[quote\](.*?)\[/quote\]#si', '<div class=\'quote\'>\1</div>', $text);
	for ($i=0;$i < $ccount;$i++) $text = preg_replace('#\[code\](.*?)\[/code\]#si', '<div class=\'quote\' style=\'width:400px;white-space:nowrap;overflow:auto\'><code style=\'white-space:nowrap\'>\1<br><br><br></code></div>', $text);

	$text = descript($text,false);

	return $text;
}

// This function sanitises news & article submissions
function descript($text,$striptags=true) {
	// Convert problematic ascii characters to their true values
	$search = array("40","41","58","65","66","67","68","69","70",
		"71","72","73","74","75","76","77","78","79","80","81",
		"82","83","84","85","86","87","88","89","90","97","98",
		"99","100","101","102","103","104","105","106","107",
		"108","109","110","111","112","113","114","115","116",
		"117","118","119","120","121","122"
		);
	$replace = array("(",")",":","a","b","c","d","e","f","g","h",
		"i","j","k","l","m","n","o","p","q","r","s","t","u",
		"v","w","x","y","z","a","b","c","d","e","f","g","h",
		"i","j","k","l","m","n","o","p","q","r","s","t","u",
		"v","w","x","y","z"
		);
	$entities = count($search);
	for ($i=0;$i < $entities;$i++) $text = preg_replace("#(&\#)(0*".$search[$i]."+);*#si", $replace[$i], $text);
	// the following is based on code from bitflux (http://blog.bitflux.ch/wiki/)
	// Kill hexadecimal characters completely
	$text = preg_replace('#(&\#x)([0-9A-F]+);*#si', "", $text);
	// remove any attribute starting with "on" or xmlns
	$text = preg_replace('#(<[^>]+[\\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onload|xmlns)[^>]*>#iU', ">", $text);
	// remove javascript: and vbscript: protocol
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text);
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text);
	$text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text);
        //<span style="width: expression(alert('Ping!'));"></span> (only affects ie...)
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU', "$1>", $text);
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU', "$1>", $text);
	if ($striptags) {
		do {
	        	$thistext = $text;
			$text = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $text);
		} while ($thistext != $text);
	}
	return $text;
}

// Scan image files for malicious code
function verify_image($file) {
	$txt = html_entity_decode(file_get_contents($file), ENT_QUOTES);
	$image_safe = true;
	if (preg_match("#&\#x([0-9a-f]+);*#i", $txt)) $image_safe = false;
	if (preg_match('#&\#([0-9]+);*#i', $txt)) $image_safe = false;
	if (preg_match("#([a-z]*)=([\`\'\"]*)script:#iU", $txt)) $image_safe = false;
	if (preg_match("#([a-z]*)=([\`\'\"]*)javascript:#iU", $txt)) $image_safe = false;
	if (preg_match("#([a-z]*)=([\'\"]*)vbscript:#iU", $txt)) $image_safe = false;
	if (preg_match("#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU", $txt)) $image_safe = false;
	if (preg_match("#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU", $txt)) $image_safe = false;
	if (preg_match("#</*(applet|link|style|script|iframe|frame|frameset)[^>]*>#i", $txt)) $image_safe = false;
	return $image_safe;
}

// captcha routines
function make_captcha() {
	global $settings;
	srand((double)microtime()*1000000);
	$temp_num = md5(rand(0,9999));
	$captcha_string = substr($temp_num, 17, 5);
	$captcha_encode = md5($temp_num);
	$result = mysql_query("INSERT INTO ".DB_PREFIX."captcha (captcha_datestamp, captcha_ip, captcha_encode, captcha_string) VALUES('".time()."', '".USER_IP."', '$captcha_encode', '$captcha_string')");
	if ($settings['validation_method'] == "image") {
		return "<input type='hidden' name='captcha_encode' value='".$captcha_encode."'><img src='".INCLUDES."captcha_include.php?captcha_code=".$captcha_encode."' alt='' />\n";
	} else {
		return "<input type='hidden' name='captcha_encode' value='".$captcha_encode."'><strong>".$captcha_string."</strong>\n";
	}
}

function check_captcha($captchs_encode, $captcha_string) {
	if (preg_match("/^[0-9a-z]+$/", $captchs_encode) && preg_match("/^[0-9a-z]+$/", $captcha_string)) {
		$result = dbquery("SELECT * FROM ".DB_PREFIX."captcha WHERE captcha_ip='".USER_IP."' AND captcha_encode='".$captchs_encode."' AND captcha_string='".$captcha_string."'");
		if (dbrows($result)) {
			$result = dbquery("DELETE FROM ".DB_PREFIX."captcha WHERE captcha_ip='".USER_IP."' AND captcha_encode='".$captchs_encode."' AND captcha_string='".$captcha_string."'");
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

// Replace offensive words with the defined replacement word
function censorwords($text) {
	global $settings;
	if ($settings['bad_words_enabled'] == "1" && $settings['bad_words'] != "" ) {
		$word_list = explode("\r\n", $settings['bad_words']);
		for ($i=0;$i < count($word_list);$i++) {
			if ($word_list[$i] != "") $text = preg_replace("/".$word_list[$i]."/si", $settings['bad_word_replace'], $text);
		}
	}
	return $text;
}

// Display the user's level
function getuserlevel($userlevel) {
	global $locale;
	if ($userlevel==101) { return $locale['user1']; }
	elseif ($userlevel==102) { return $locale['user2']; }
	elseif ($userlevel==103) { return $locale['user3']; }
}

// Check if Administrator has correct rights assigned
function checkrights($right) {
	if (iADMIN && in_array($right, explode(".", iUSER_RIGHTS))) {
		return true;
	} else {
		return false;
	}
}

// Check if user is assigned to the specified user group
function checkgroup($group) {
	if (iSUPERADMIN) { return true; }
	elseif (iADMIN && ($group == "0" || $group == "101" || $group == "102")) { return true; }
	elseif (iMEMBER && ($group == "0" || $group == "101")) { return true; }
	elseif (iGUEST && $group == "0") { return true; }
	elseif (iMEMBER && in_array($group, explode(".", iUSER_GROUPS))) {
		return true;
	} else {
		return false;
	}
}

// Compile access levels & user group array
function getusergroups() {
	global $locale;
	$groups_array = array(
		array("0", $locale['user0']),
		array("101", $locale['user1']),
		array("102", $locale['user2']),
		array("103", $locale['user3'])
	);
	$gsql = dbquery("SELECT group_id,group_name FROM ".DB_PREFIX."user_groups");
	while ($gdata = dbarray($gsql)) {
		array_push($groups_array, array($gdata['group_id'], $gdata['group_name']));
	}
	return $groups_array;
}

// Get the name of the access level or user group
function getgroupname($group) {
	global $locale;
	if ($group == "0") { return $locale['user0']; }
	elseif ($group == "101") { return $locale['user1']; }
	elseif ($group == "102") { return $locale['user2']; }
	elseif ($group == "103") { return $locale['user3'];
	} else {
		$gsql = dbquery("SELECT group_id,group_name FROM ".DB_PREFIX."user_groups WHERE group_id='$group'");
		if (dbrows($gsql)!=0) {
			$gdata = dbarray($gsql);
			return $gdata['group_name'];
		} else {
			return "N/A";
		}
	}
}

function groupaccess($field) {
	if (iSUPERADMIN) { $res = "($field='0' OR $field='101' OR $field='102' OR $field='103'";
	} elseif (iADMIN) { $res = "($field='0' OR $field='101' OR $field='102'";
	} elseif (iMEMBER) { $res = "($field='0' OR $field='101'";
	} elseif (iGUEST) { $res = "($field='0'"; }
	if (iUSER_GROUPS != "") $res .= " OR $field='".str_replace(".", "' OR $field='", iUSER_GROUPS)."'";
	$res .= ")";
	return $res;
}

// Create a list of files or folders and store them in an array
function makefilelist($folder, $filter, $sort=true, $type="files") {
	$res = array();
	$filter = explode("|", $filter); 
	$temp = opendir($folder);
	while ($file = readdir($temp)) {
		if ($type == "files" && !in_array($file, $filter)) {
			if (!is_dir($folder.$file)) $res[] = $file;
		} elseif ($type == "folders" && !in_array($file, $filter)) {
			if (is_dir($folder.$file)) $res[] = $file;
		}
	}
	closedir($temp);
	if ($sort) sort($res);
	return $res;
}

// Create a selection list from an array created by makefilelist()
function makefileopts($files, $selected="") {
	$res = "";
	for ($i=0;$i < count($files);$i++) {
		$sel = ($selected == $files[$i] ? " selected" : "");
		$res .= "<option value='".$files[$i]."'$sel>".$files[$i]."</option>\n";
	}
	return $res;
}

// Universal page pagination function by CrappoMan
function makepagenav($start,$count,$total,$range=0,$link=""){
	global $locale;
	if ($link == "") $link = FUSION_SELF."?";
	$res="";
	$pg_cnt=ceil($total / $count);
	if ($pg_cnt > 1) {
		$idx_back = $start - $count;
		$idx_next = $start + $count;
		$cur_page=ceil(($start + 1) / $count);
		$res.="<table cellspacing='1' cellpadding='1' border='0' class='tbl-border'>\n<tr>\n";
		$res.="<td class='tbl2'><span class='small'>".$locale['052']."$cur_page".$locale['053']."$pg_cnt</span></td>\n";
		if ($idx_back >= 0) {
			if ($cur_page > ($range + 1)) $res.="<td class='tbl2'><a class='small' href='$link"."rowstart=0'>&lt;&lt;</a></td>\n";
			$res.="<td class='tbl2'><a class='small' href='$link"."rowstart=$idx_back'>&lt;</a></td>\n";
		}
		$idx_fst=max($cur_page - $range, 1);
		$idx_lst=min($cur_page + $range, $pg_cnt);
		if ($range==0) {
			$idx_fst = 1;
			$idx_lst=$pg_cnt;
		}
		for($i=$idx_fst;$i<=$idx_lst;$i++) {
			$offset_page=($i - 1) * $count;
			if ($i==$cur_page) {
				$res.="<td class='tbl1'><span class='small'><b>$i</b></span></td>\n";
			} else {
				$res.="<td class='tbl1'><a class='small' href='$link"."rowstart=$offset_page'>$i</a></td>\n";
			}
		}
		if ($idx_next < $total) {
			$res.="<td class='tbl2'><a class='small' href='$link"."rowstart=$idx_next'>&gt;</a></td>\n";
			if ($cur_page < ($pg_cnt - $range)) $res.="<td class='tbl2'><a class='small' href='$link"."rowstart=".($pg_cnt-1)*$count."'>&gt;&gt;</a></td>\n";
		}
		$res.="</tr>\n</table>\n";

	}
	return $res;
}

// Format the date & time accordingly
function showdate($format, $val) {
global $settings;
$timestamp = time();
$tos_date=strftime("%Y-%m-%d %H:%M:%S", $val+($settings['timeoffset']*3600));

$date_time = explode(" ", $tos_date);
$date = explode("-", $date_time[0]);
$months = array("01" => "Января",
"02" => "Февраля",
"03" => "Марта",
"04" => "Апреля",
"05" => "Мая",
"06" => "Июня",
"07" => "Июля",
"08" => "Августа",
"09" => "Сентября",
"10" => "Октября",
"11" => "Ноября",
"12" => "Декабря"
);
$month="";
foreach ($months as $key => $text){
if ($key==$date[1]) {$month=$text; break;}
}
return $rus_date=$date[2]." ".$month." ".$date[0].", ".$date_time[1];
}

// Translate bytes into kb, mb, gb or tb by CrappoMan
function parsebytesize($size,$digits=2,$dir=false) {
	$kb=1024; $mb=1024*$kb; $gb=1024*$mb; $tb=1024*$gb;
	if (($size==0)&&($dir)) { return "Empty"; }
	elseif ($size<$kb) { return $size."Bytes"; }
	elseif ($size<$mb) { return round($size/$kb,$digits)."Kb"; }
	elseif ($size<$gb) { return round($size/$mb,$digits)."Mb"; }
	elseif ($size<$tb) { return round($size/$gb,$digits)."Gb"; }
	else { return round($size/$tb,$digits)."Tb"; }
}

// User level, Admin Rights & User Group definitions
define("iGUEST",$userdata['user_level'] == 0 ? 1 : 0);
define("iMEMBER", $userdata['user_level'] >= 101 ? 1 : 0);
define("iADMIN", $userdata['user_level'] >= 102 ? 1 : 0);
define("iSUPERADMIN", $userdata['user_level'] == 103 ? 1 : 0);
define("iUSER", $userdata['user_level']);
define("iUSER_RIGHTS", $userdata['user_rights']);
define("iUSER_GROUPS", substr($userdata['user_groups'], 1));

if (iADMIN) {
	define("iAUTH", substr($userdata['user_password'],16,32));
	$aidlink = "?aid=".iAUTH;
}

if (file_exists(LOCALE.LOCALESET."dynamic_titles.php")) {
	include LOCALE.LOCALESET."dynamic_titles.php";
} else { include LOCALE."English/dynamic_titles.php"; }

function dynamic_title($column, $table, $compare1, $compare2, $begin, $alt) {
	global $db_prefix;
	if (!isnum($compare2)) { $compare2 = 0; }
	$result = dbquery("SELECT $column FROM ".$db_prefix."$table WHERE $compare1 = $compare2");
	if ($result) {
		$data = dbarray($result);
		$title = $begin.$data[$column];
	} else {
		$title = $alt;
	}
	return $title;
}

if(FUSION_SELF == "submit.php") {
	if($_GET['stype'] == "l") $title = $locale['DTM_059'];
	if($_GET['stype'] == "n") $title = $locale['DTM_060'];
	if($_GET['stype'] == "a") $title = $locale['DTM_061'];
} elseif(FUSION_SELF == "register.php") {
	$title = $locale['DTM_062'];
} elseif(FUSION_SELF == "search.php") {
	$title = $locale['DTM_063'];
} elseif(FUSION_SELF == "edit_profile.php") {
	$title = $locale['DTM_064'];
} elseif(FUSION_SELF == "members.php") {
	$title = $locale['DTM_065'];
} elseif(FUSION_SELF == "guestbook.php") {
	$title = $locale['DTM_068'];
} elseif(FUSION_SELF == "lostpassword.php") {
	$title = $locale['DTM_066'];
} elseif(FUSION_SELF == "contact.php") {
	$title = $locale['DTM_067'];
} elseif(FUSION_SELF == "post.php") {
	if($_GET['action'] == "newthread") {
		$title = dynamic_title("forum_name", "forums", "forum_id", $_GET['forum_id'], $locale['DTM_020'], $locale['DTM_021']);
	} elseif($_GET['action'] == "edit") {
		$title = dynamic_title("post_subject", "posts", "post_id", $_GET['post_id'], $locale['DTM_026'], $locale['DTM_027']);
	} elseif($_GET['action'] == "reply") {
		$title = dynamic_title("thread_subject", "threads", "thread_id", $_GET['thread_id'], $locale['DTM_032'], $locale['DTM_033']);
	}
} elseif(FUSION_SELF == "postify.php") {
	if($_GET['post'] == "new" && $_GET['error'] == 0) {
		$title = dynamic_title("forum_name", "forums", "forum_id", $_GET['forum_id'], $locale['DTM_022'], $locale['DTM_023']);
	} elseif($_GET['post'] == "new" && $_GET['error'] != 0) {
		$title = dynamic_title("forum_name", "forums", "forum_id", $_GET['forum_id'], $locale['DTM_024'], $locale['DTM_025']);
	} elseif($_GET['post'] == "edit" && $_GET['error'] == 0) {
		$title = dynamic_title("post_subject", "posts", "post_id", $_GET['post_id'], $locale['DTM_028'], $locale['DTM_029']);
	} elseif($_GET['post'] == "edit" && $_GET['error'] != 0) {
		$title = dynamic_title("post_subject", "posts", "post_id", $_GET['post_id'], $locale['DTM_030'], $locale['DTM_031']);
	} elseif($_GET['post'] == "reply" && $_GET['error'] == 0) {
		$title = dynamic_title("thread_subject", "threads", "thread_id", $_GET['thread_id'], $locale['DTM_034'], $locale['DTM_035']);
	} elseif($_GET['post'] == "reply" && $_GET['error'] != 0) {
		$title = dynamic_title("thread_subject", "threads", "thread_id", $_GET['thread_id'], $locale['DTM_036'], $locale['DTM_037']);
	}
} elseif(FUSION_SELF == "messages.php") {
	if(isset($msg_view)) {
		$title = dynamic_title("message_subject", "messages", "message_id", $msg_view, $locale['DTM_044'], $locale['DTM_045']);
	} elseif(isset($msg_reply)) {
		$title = dynamic_title("message_subject", "messages", "message_id", $msg_reply, $locale['DTM_046'], $locale['DTM_047']);
	} elseif(isset($_POST['reply_preview'])) {
		$title = dynamic_title("message_subject", "messages", "message_id", $msg_reply_preview, $locale['DTM_048'], $locale['DTM_049']);
	} elseif(isset($msg_send)) {
		$title = dynamic_title("user_name", "users", "user_id", $msg_send, $locale['DTM_050'], $locale['DTM_051']);
	} elseif(isset($_POST['send_preview'])) {
		$title = dynamic_title("user_name", "users", "user_id", $msg_to, $locale['DTM_052'], $locale['DTM_053']);
	} elseif(isset($folder)) {
		if($folder == "inbox") $title = $locale['DTM_040'];
		elseif($folder == "sentbox") $title = $locale['DTM_041'];
		elseif($folder == "savebox") $title = $locale['DTM_042'];
		elseif($folder == "options") $title = $locale['DTM_043'];
		else $title = $locale['DTM_028'];
	} else {
		$title = $locale['DTM_039'];
	}
} elseif(FUSION_SELF == "photogallery.php") {
	if(isset($album_id)) {
		$title = dynamic_title("album_title", "photo_albums", "album_id", $album_id, $locale['DTM_055'], $locale['DTM_056']);
	} elseif(isset($photo_id)) {
		$title = dynamic_title("photo_title", "photos", "photo_id", $photo_id, $locale['DTM_057'], $locale['DTM_058']);
	} else {
		$title = $locale['DTM_054'];
	}
} elseif(FUSION_SELF == "index.php") {
	if(BASEDIR.basename(dirname($_SERVER['PHP_SELF']))."/" == FORUM) $title = $locale['DTM_038'];
} else {
	@$page_array = array(
		array("news.php", "news_subject", "news", "news_id", $readmore, $locale['DTM_000'], $locale['DTM_001']),
		array("news_cats.php", "news_cat_name", "news_cats", "news_cat_id", $cat_id, $locale['DTM_002'], $locale['DTM_003']),
		array("articles.php", "article_cat_name", "article_cats", "article_cat_id", $cat_id, $locale['DTM_004'], $locale['DTM_005']),
		array("readarticle.php", "article_subject", "articles", "article_id", $article_id, $locale['DTM_006'], $locale['DTM_007']),
		array("downloads.php", "download_cat_name", "download_cats", "download_cat_id", $cat_id, $locale['DTM_008'], $locale['DTM_009']),
		array("downloads.php", "download_title", "downloads", "download_id", $page_id, "", $locale['DTM_009']),
		array("faq.php", "faq_cat_name", "faq_cats", "faq_cat_id", $cat_id, $locale['DTM_010'], $locale['DTM_011']),
		array("profile.php", "user_name", "users", "user_id", $lookup, $locale['DTM_012'], $locale['DTM_013']),
		array("weblinks.php", "weblink_cat_name", "weblink_cats", "weblink_cat_id", $cat_id, $locale['DTM_014'], $locale['DTM_015']),
		array("viewforum.php", "forum_name", "forums", "forum_id", $forum_id, $locale['DTM_016'], $locale['DTM_017']),
		array("viewthread.php", "thread_subject", "threads", "thread_id", $thread_id, $locale['DTM_018'], $locale['DTM_019']),
		array("viewpage.php", "page_title", "custom_pages", "page_id", $page_id, "", "")
	);
	foreach($page_array as $value) {
		if($value[0] == FUSION_SELF && $value[4] > "") {
			$title = dynamic_title($value[1], $value[2], $value[3], $value[4], $value[5],$value[6]);
		} elseif($value[0] == FUSION_SELF) {
				$title = $value[6];
		}
	}
}

if(!empty($title)) $title = $title." - ";
?>