<?php
if (!defined("FUNC_FILE")) die("Illegal File Access");

define("BLOCK_FILE", true);
define("FUNC_FILE", true);

// Format head
function head() {
	global $slogan, $keywords, $bodytext, $hometext, $sitename, $pagetitle, $power, $defis, $keywords_status, $version, $home, $index, $redaktor, $module_name;
	online();
	$ThemeSel = get_theme();
	if (file_exists("templates/$ThemeSel/index.php")) {
		require_once("templates/$ThemeSel/index.php");
	} else {
		require_once("function/template.php");
	}
	if (!$defis) $defis = "%7C";
	$defis_dec = urldecode($defis);
	$index = (file_exists("templates/".$ThemeSel."/index-".$module_name.".html")) ? file_get_contents("templates/".$ThemeSel."/index-".$module_name.".html") : file_get_contents("templates/".$ThemeSel."/index.html");
	if ($power != base64_decode('UG93ZXJlZCBieSA8YSBocmVmPSJodHRwOi8vd3d3LnNsYWVkLm5ldCIgdGFyZ2V0PSJfYmxhbmsiIHRpdGxlPSJTTEFFRCBDTVMiPlNMQUVEIENNUzwvYT4gJmNvcHk7IDIwMDUtMjAwNyBTTEFFRC4gQWxsIHJpZ2h0cyByZXNlcnZlZC4=') || !preg_match("#{%LICENSE%}#", $index)) die(base64_decode('PGJyPjxicj48Y2VudGVyPjxpbWcgc3JjPSJpbWFnZXMvbG9nb3MvbG9nby5naWYiPjxicj48YnI+PGI+RGFyaW5nIGNvcHlyaWdodHMgb2Ygc3lzdGVtLCB5b3UgYnJlYWsgdGhlIGxpY2Vuc2Ugb2YgdXNlITwvY2VudGVyPjwvYj4='));
	$index = str_replace("{%LICENSE%}", $power, $index);
	preg_match("#^(.*){%MODULE%}#iUs", $index, $head);
	$head = (isset($head[1])) ? $head[1] : die("Error in Head!");
	preg_match("#{%MODULE%}(.*)$#iUs", $index, $index);
	$index = (isset($index[1])) ? $index[1] : die("Error in Foot!");
	$strhead = "<meta http-equiv=\"content-type\" content=\"text/html; charset="._CHARSET."\">\n";
	if ($home) {
		$strhead .= "<title>$sitename $defis_dec $slogan</title>\n";
	} else {
		$ptitle_dec = explode($defis, $pagetitle);
		foreach ($ptitle_dec as $key => $val) $i++;
		foreach ($ptitle_dec as $key => $val) {
			if ($val) $pagetitle_dec .= "".trim($ptitle_dec[$i])." ".$defis_dec." ";
			$i--;
		}
		$strhead .= "<title>".$pagetitle_dec."".$sitename."</title>\n";
	}
	if (!defined("ADMIN_FILE")) {
		$hour = gmdate("H");
		if (intval($hour)) $hour = $hour - 1;
		@Header("Last-Modified: ".gmdate("D, d M Y ".intval($hour).":i:s")." GMT");
		@Header("Content-Type: text/html; charset="._CHARSET."");
		if (!empty($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache/2')) {
			@Header("Cache-Control: no-cache, pre-check=0, post-check=0");
		} else {
			@Header("Cache-Control: private, pre-check=0, post-check=0, max-age=0");
		}
		@Header("Expires: 0");
		@Header("Pragma: no-cache");
		$strhead .= "<meta name=\"resource-type\" content=\"document\">\n"
		."<meta name=\"document-state\" content=\"dynamic\">\n"
		."<meta name=\"distribution\" content=\"global\">\n"
		."<meta name=\"author\" content=\"$sitename\">\n"
		."<meta name=\"copyright\" content=\"Copyright (c) SLAED CMS $version\">\n";
		$pagetitle = trim(str_replace(" $defis ", ", ", $pagetitle));
		$pagetitle = trim(str_replace("$defis ", "", $pagetitle));
		if ((($hometext == "") && ($bodytext == "")) || ($keywords_status == "0")) {
			$strhead .= "<meta name=\"keywords\" content=\"$pagetitle, $keywords\">\n"
			."<meta name=\"description\" content=\"$slogan, $pagetitle.\">\n";
		} else {
			$key_words = "$pagetitle";
			$keywords_gen = "$hometext $bodytext";
			$keywords_gen = text_filter(bb_decode($keywords_gen), 1);
			$keywords_gen = trim(preg_replace('/("|\?|!|:|\.|\(|\)|;|\\\\)+/', ' ', $keywords_gen));
			$keywords_gen = preg_replace('/( |'.CHR(10).'|'.CHR(13).')+/', ',', $keywords_gen);
			$keywords_gen = substr($keywords_gen, 0, 1600);
			$keywords_gen = array_unique(explode(",", $keywords_gen));
			for ($a = 0, $b = 7; $a < sizeof($keywords_gen) && $b < 800; $a++) {
				if (($c = strlen($keywords_gen[$a])) > 3) {
					$key_words = "".$key_words.", ".$keywords_gen[$a]."";
					$b += $c+2;
				}
			}
			$strhead .= "<meta name=\"keywords\" content=\"$key_words\">\n"
			."<meta name=\"description\" content=\"$slogan, $pagetitle.\">\n";
		}
		$strhead .= "<meta name=\"robots\" content=\"index, follow\">\n"
		."<meta name=\"revisit-after\" content=\"1 days\">\n"
		."<meta name=\"rating\" content=\"general\">\n"
		."<meta name=\"generator\" content=\"SLAED CMS $version\">\n"
		."<link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\">\n"
		."<link rel=\"alternate\" href=\"rss.php\" title=\"$sitename - RSS\" type=\"application/rss+xml\">\n";
	}
	$strhead .= "<link rel=\"stylesheet\" href=\"templates/$ThemeSel/style.css\" type=\"text/css\">";
	if (!defined("ADMIN_FILE")) {
		if (file_exists("config/config_header.php")) {
			ob_start();
			require_once("config/config_header.php");
			$strhead .= ob_get_contents();
			ob_end_clean();
		}
	} else {
		if ($redaktor == 2 && file_exists("config/config_header.php")) {
			ob_start();
			require_once("config/config_redaktor.php");
			$strhead .= ob_get_contents();
			ob_end_clean();
		}
	}
	$head = addblocks($head);
	$head = str_replace('{%HEAD%}', $strhead, $head);
	themeheader($head);
	unset($head, $strhead);
	if (!defined("ADMIN_FILE")) update_points(13);
}

// Format foot
function foot() {
	global $module, $name, $index, $gzip_status, $do_gzip_compress, $rewrite_mod;
	$index = addblocks($index);
	if ($module == 1 && file_exists("modules/$name/copyright.php")) {
		$index = "<script language=\"JavaScript\" type=\"text/javascript\" src=\"javascripts/OpenWindow.js\"></script>"
		."<div align=\"right\"><a href=\"javascript:OpenWindow('modules/$name/copyright.php', 'Copyright', '400', '200')\">".str_replace("_", " ", $name)." &copy;</a></div>".$index."";
	}
	themefooter($index);
	unset($index);
	if ($rewrite_mod == 1) rewrite();
	if ($gzip_status == 1) {
		if ($do_gzip_compress) {
			$gzip_contents = ob_get_contents();
			ob_end_clean();
			$gzip_size = strlen($gzip_contents);
			$gzip_crc = crc32($gzip_contents);
			$gzip_contents = gzcompress($gzip_contents, 9);
			$gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
			echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
			echo $gzip_contents;
			echo pack('V', $gzip_crc);
			echo pack('V', $gzip_size);
		}
	}
	exit;
}

// Check admin
function is_admin($admin) {
	global $prefix, $db;
	static $admintrue;
    if (!isset($admintrue)) {
		$id = intval(substr($admin[0], 0, 11));
		$name = substr($admin[1], 0, 25);
		$pwd = substr($admin[2], 0, 50);
		$ip = getenv("REMOTE_ADDR");
		if ($id != "" && $name != "" && $pwd != "" && $ip != "") {
			list($aname, $apwd, $aip) = $db->sql_fetchrow($db->sql_query("SELECT name, pwd, ip FROM ".$prefix."_admins WHERE id='$id'"));
			if ($aname == $name && $aname != "" && $apwd == $pwd && $apwd != "" && $aip == $ip && $aip != "") {
				$admintrue = 1;
				return 1;
			}
		}
		$admintrue = 0;
		return 0;
	}
	if ($admintrue == 1) {
		return 1;
	} else {
		return 0;
	}
}

// Check module
function is_active($module) {
    global $prefix, $db;
	static $name;
	if (!is_array($name)) {
		$result = $db->sql_query("SELECT title FROM ".$prefix."_modules WHERE active='1'");
		while (list($title) = $db->sql_fetchrow($result)) $name[] = $title;
	}
	foreach ($name as $key => $val) {
		if ($val == $module) {
			$a = 1;
			break;
		} else {
			$a = 0;
		}
	}
	return $a;
}

// Rewrite mod
function rewrite() { 
	$contents = ob_get_contents(); 
	ob_end_clean();
	include("config/config_rewrite.php");
	$rewrite = preg_replace($rewrite_in, $rewrite_out, $contents);
	echo $rewrite;
}

// Decode BB
function bb_decode($sourse) {
	global $user;
	$bb[] = "#\[img\]([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#i";
	$html[] = "<img src=\"\\1\" border=\"0\" alt=\"\\1\" title=\"\\1\" />";
	$bb[] = "#\[img=([a-zA-Z]+)\]([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img src=\"\\2\" align=\"\\1\" border=\"0\" alt=\"\\2\" title=\"\\2\" />";
	$bb[] = "#\[img\ alt=([a-zA-Zа-яА-Я0-9\_\-\. ]+)\]([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img src=\"\\2\" align=\"\\1\" border=\"0\" alt=\"\\1\" title=\"\\1\" />";
	$bb[] = "#\[img=([a-zA-Z]+) alt=([a-zA-Zа-яА-Я0-9\_\-\. ]+)\]([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img src=\"\\3\" align=\"\\1\" border=\"0\" alt=\"\\2\" title=\"\\2\" />";
	$bb[] = "#\[url\]([\w]+?://([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
	$html[] = "<a href=\"\\1\" target=\"_blank\" title=\"\\1\">\\1</a>";
	$bb[] = "#\[url\]((www|ftp)\.([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
	$html[] = "<a href=\"http://\\1\" target=\"_blank\" title=\"\\1\">\\1</a>";
	$bb[] = "#\[url=([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
	$html[] = "<a href=\"\\1\" target=\"_blank\" title=\"\\1\">\\2</a>";
	$bb[] = "#\[url=((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
	$html[] = "<a href=\"http://\\1\" target=\"_blank\" title=\"\\1\">\\3</a>";
	$bb[] = "#\[mail\](\S+?)\[/mail\]#i";
	$html[] = "<a href=\"mailto:\\1\">\\1</a>";
	$bb[] = "#\[mail\s*=\s*([\.\w\-]+\@[\.\w\-]+\.[\w\-]+)\s*\](.*?)\[\/mail\]#i";
	$html[] = "<a href=\"mailto:\\1\">\\2</a>";
	$bb[] = "#\[color=(\#[0-9A-F]{6}|[a-z]+)\](.*?)\[/color\]#si";
	$html[] = "<span style=\"color: \\1\">\\2</span>";
	$bb[] = "#\[family=([A-Za-z ]+)\](.*?)\[/family\]#si";
	$html[] = "<span style=\"font-family: \\1\">\\2</span>";
	$bb[] = "#\[size=([0-9]+)\](.*?)\[/size\]#si";
	$html[] = "<span style=\"font-size: \\1\">\\2</span>";
	$bb[] = "#\[(left|right|center|justify)\](.*?)\[/\\1\]#is";
	$html[] = "<div align=\"\\1\">\\2</div>";
	$bb[] = "#\[b\](.*?)\[/b\]#si";
	$html[] = "<b>\\1</b>";
	$bb[] = "#\[i\](.*?)\[/i\]#si";
	$html[] = "<i>\\1</i>";
	
	
	//=====добавлено=====

   $bb[] = "#\[swf w=(.*?) h=(.*?)\](.*?)\[/swf\]#is";
   $html[] = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"\\1\" height=\"\\2\" id=\"Untitled-1\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"movie\" value=\"\\3\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><embed src=\"\\3\" quality=\"high\" bgcolor=\"#ffffff\" width=\"\\1\" height=\"\\2\" name=\"Untitled-1\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" /></object>";
   //=====добавлено=====
   
   
   //Спойлер
    $bb[] = "#[spoiler=(.*?)](.*?)[/spoiler]#is";
    $html[] = "<table width=\"90%\" border=\"0\" cellspacing=\"1\" cellpadding=\"3\"><div id=\"cont\"><tr><th onclick=\"SwitchMenu('pokaz54');SwitchMenu('pokaz55');SwitchMenu('pokaz56');\" style=\"cursor:pointer;\" nowrap=\"nowrap\"><div align=\"left\" id=\"pokaz55\" style=\"display:block;\"><img src=\"images/icon_plu.gif\" align=\"bottom\"> \1</div><div align=\"left\" id=\"pokaz56\" style=\"display:none;\"><img src=\"images/icon_min.gif\" align=\"bottom\"> \1</div></th></tr></div><tr><td><div id=\"pokaz54\" style=\"display:none;\">\2</div></td></tr></table>";
   //Спойлер
   
   
	
	$bb[] = "#\[u\](.*?)\[/u\]#si";
	$html[] = "<u>\\1</u>";
	$bb[] = "#\[s\](.*?)\[/s\]#si";
	$html[] = "<s>\\1</s>";
	$bb[] = "#\[li\]#si";
	$html[] = "<li>";
	$bb[] = "#\[hr\]#si";
	$html[] = "<hr>";
	$bb[] = "#\*(\d{2})#";
	$html[] = "<img src=\"images/smilies/\\1.gif\" border=\"0\" />";
	
	
	
	$sourse = preg_replace($bb, $html, $sourse);
	if (preg_match("#\[quote\](.*?)\[/quote\]#si", $sourse)) $sourse = encode_quote($sourse);
	if (preg_match("#\[hide\](.*?)\[/hide\]#si", $sourse)) $sourse = encode_hide($sourse);
	if (preg_match("#\[code\](.*?)\[/code\]#si", $sourse)) $sourse = encode_code($sourse);
	if (preg_match("#\[php\](.*?)\[/php\]#si", $sourse)) $sourse = encode_php($sourse);
	return $sourse; 
}

// Format hide
function encode_hide($text) {
	$start_html = "<div align=\"center\"><div style=\"width: 90%; overflow: auto\">"
	."<table width=\"100%\" cellspacing=\"1\" cellpadding=\"3\" border=\"0\" align=\"center\" class=\"bgcolor4\">"
	."<tr bgcolor=\"E5FFE9\"><td><font class=\"block-title\">"._HIDE."</font></td></tr>"
	."<tr class=\"bgcolor1\"><td>";
	$end_html = "</td></tr></table></div></div>";
	$text = (defined("ADMIN_FILE") || is_user($user)) ? preg_replace("#\[hide\](.*?)\[/hide\]#si", "".$start_html."\\1".$end_html."", $text) : preg_replace("#\[hide\](.*?)\[/hide\]#si", "".$start_html.""._HIDETEXT."".$end_html."", $text);
	return $text;
} 

// Format quote
function encode_quote($text) {
	$start_html = "<div align=\"center\"><div style=\"width: 90%; overflow: auto\">"
	."<table width=\"100%\" cellspacing=\"1\" cellpadding=\"3\" border=\"0\" align=\"center\" class=\"bgcolor4\">"
	."<tr bgcolor=\"FFE5E0\"><td><font class=\"block-title\">"._QUOTE."</font></td></tr>"
	."<tr class=\"bgcolor1\"><td>";
	$end_html = "</td></tr></table></div></div>";
	$text = preg_replace("#\[quote\](.*?)\[/quote\]#si", "".$start_html."\\1".$end_html."", $text);
	return $text;
} 

// Format code
function encode_code($text) {
	$start_html = "<div align=\"center\"><div style=\"width: 90%; overflow: auto\">"
	."<table width=\"100%\" cellspacing=\"1\" cellpadding=\"3\" border=\"0\" align=\"center\" class=\"bgcolor4\">"
	."<tr bgcolor=\"E5EFFF\"><td colspan=\"2\"><font class=\"block-title\">"._CODE."</font></td></tr>"
	."<tr class=\"bgcolor1\"><td align=\"right\" class=\"code\" style=\"width: 5px; border-right: none\">{ZEILEN}</td><td class=\"code\">";
	$end_html = "</td></tr></table></div></div>";
	$match_count = preg_match_all("#\[code\](.*?)\[/code\]#si", $text, $matches);
	for ($i = 0; $i < $match_count; $i++) {
		$before_replace = $matches[1][$i];
		$after_replace = $matches[1][$i];
		$after_replace = trim($after_replace);
		$zeilen_array = explode("<br />", $after_replace);
		$j = 1;
		$zeilen = '';
		foreach($zeilen_array as $str) {
			$zeilen .= "".$j."<br />";
			$j++;
		}
		$after_replace = str_replace("\n", "", $after_replace);
		$after_replace = str_replace('&amp;', '&', $after_replace);
		$after_replace = str_replace("  ", "&nbsp; ", $after_replace);
		$after_replace = str_replace("  ", " &nbsp;", $after_replace);
		$after_replace = str_replace("\t", "&nbsp; &nbsp;", $after_replace);
		$after_replace = preg_replace("/^ {1}/m", "&nbsp;", $after_replace);
		$str_to_match = "[code]".$before_replace."[/code]";
		$replace = str_replace("{ZEILEN}", $zeilen, $start_html);
		$replace .= $after_replace;
		$replace .= $end_html;
		$text = str_replace($str_to_match, $replace, $text);
	}
	$text = str_replace("[code]", $start_html, $text);
	$text = str_replace("[/code]", $end_html, $text);
	return $text;
} 

// Format PHP code
function encode_php($text) {
	$start_html = "<div align=\"center\"><div style=\"width: 90%; overflow: auto\">"
	."<table width=\"100%\" cellspacing=\"1\" cellpadding=\"3\" border=\"0\" align=\"center\" class=\"bgcolor4\">"
	."<tr bgcolor=\"F3E8FF\"><td colspan=\"2\"><font class=\"block-title\">PHP - "._CODE."</font></td></tr>"
	."<tr class=\"bgcolor1\"><td align=\"right\" class=\"code\" style=\"width: 5px; border-right: none\">{ZEILEN}</td><td>";
	$end_html = "</td></tr></table></div></div>";
	$match_count = preg_match_all("#\[php\](.*?)\[/php\]#si", $text, $matches);
	for ($i = 0; $i < $match_count; $i++) {
		$before_replace = $matches[1][$i];
		$after_replace = $matches[1][$i];
		$after_replace = trim($after_replace);
		$after_replace = str_replace("&lt;", "<", $after_replace);
		$after_replace = str_replace("&gt;", ">", $after_replace);
		$after_replace = str_replace("&quot;", '"', $after_replace);
		$after_replace = preg_replace("/<br.*/i", "", $after_replace);
		$after_replace = (substr($after_replace, 0, 2 ) != "<?php") ? "<?php\n".$after_replace."" : "".$after_replace."";
		$after_replace = (substr($after_replace, -2 ) != "?>") ? "".$after_replace."\n?>" : "".$after_replace."";
		ob_start();
		highlight_string($after_replace);
		$after_replace = ob_get_contents();
		ob_end_clean();
		$zeilen_array = explode("<br />", $after_replace);
		$j = 1;
		$zeilen = '';
		foreach($zeilen_array as $str) {
			$zeilen .= "".$j."<br />";
			$j++;
		}
		$after_replace = str_replace("\n", "", $after_replace);
		$after_replace = str_replace("&amp;", "&", $after_replace);
		$after_replace = str_replace("  ", "&nbsp; ", $after_replace);
		$after_replace = str_replace("  ", " &nbsp;", $after_replace);
		$after_replace = str_replace("\t", "&nbsp; &nbsp;", $after_replace);
		$after_replace = preg_replace("/^ {1}/m", "&nbsp;", $after_replace);
		$str_to_match = "[php]".$before_replace."[/php]";
		$replace = str_replace("{ZEILEN}", $zeilen, $start_html);
		$replace .= $after_replace;
		$replace .= $end_html;
		$text = str_replace($str_to_match, $replace, $text);
	}
	$text = str_replace("[php]", $start_html, $text);
	$text = str_replace("[/php]", $end_html, $text);
	return $text;
} 

// Mail check
function checkemail($mail) {
	global $stop;
	$mail = strtolower($mail);
	if ((!$mail) || ($mail=="") || (!preg_match("/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$/", $mail))) $stop = "<center>"._ERROR1."<br>"._ERROR2." (<b>email@domain.com</b>)</center>";
	if ((strlen($mail) >= 4) && (substr($mail, 0, 4) == "www.")) $stop = "<center>"._ERROR1."<br>"._ERROR3." (<b>www.</b>)</center>";
	if (strrpos($mail, " ") > 0) $stop = "<center>"._ERROR1."<br>"._ERROR4.".</center>";
	return $stop;
}

// Mail send
function mail_send($email, $smail, $subject, $message, $id="", $pr="") {
	$email = text_filter($email);
	$smail = text_filter($smail);
	$subject = text_filter($subject);
	$id = intval($id);
	$pr = (!$pr) ? "3" : "".intval($pr)."";
	$message = (!$id) ? "".$message."" : "".$message."<br /><br />IP: ".getenv("REMOTE_ADDR")."<br />User agent: ".getenv("HTTP_USER_AGENT")."";
	$mheader = "MIME-Version: 1.0\n"
	."Content-Type: text/html; charset="._CHARSET."\n"
	."Reply-To: \"$smail\" <$smail>\n"
	."From: \"$smail\" <$smail>\n"
	."Return-Path: <$smail>\n"
	."X-Priority: $pr\n"
	."X-Mailer: SLAED CMS Mailer\n";
	mail($email, $subject, $message, $mheader);
}

// Format admin block
function adminblock() {
	global $admin, $prefix, $db, $admin_file;
    if (is_admin($admin)) {
		$a_content = "<script language=\"JavaScript\" type=\"text/javascript\" src=\"javascripts/OpenWindow.js\"></script>"
		."<table><tr><td><img src=\"images/navi.gif\" border=\"0\"></td><td><a href=\"".$admin_file.".php\" title=\""._HOME."\">"._HOME."</a></td></tr>"
		."<tr><td><img src=\"images/navi.gif\" border=\"0\"></td><td><a href=\"".$admin_file.".php?op=LogOut\"  title=\""._LOGOUT."\">"._LOGOUT."</a></td></tr></table>";
		list($title, $content) = $db->sql_fetchrow($db->sql_query("SELECT title, content FROM ".$prefix."_blocks WHERE bkey='admin'"));
		$a_content .= $content;
		$a_title = ($title) ? $title : ""._ADMINISTR."";
		themesidebox($a_title, $a_content, 5);
		$strip = 5;
		$who_online = array('0' => '', '1' => '', '2' => '');
		$content_who = "";
		$i = 0;
		$result = $db->sql_query("SELECT uname, host_addr, guest, module, url, UNIX_TIMESTAMP(now())-time AS time FROM ".$prefix."_session ORDER BY uname");
		while (list($s_uname, $s_host_addr, $s_guest, $s_module, $s_url, $s_time) = $db->sql_fetchrow($result)) {
			$linkstrip = cutstr($s_module, $strip);
			$linkstrip_admin = cutstr($s_url, $strip);
			$guest = intval($s_guest);
			if ($guest == 2) {
				$title_who = "<a href=\"http://www.dnsstuff.com/tools/whois.ch?ip=$s_host_addr\" title=\"".displayTime($s_time)." - IP: $s_host_addr\" target=\"_blank\">$s_uname</a> - <a href=\"$s_url\" title=\"$s_url\" target=\"_blank\">$linkstrip_admin</a><br>";
			} elseif ($guest == 0) {
				if ($linkstrip != "") {
					$title_who = "<a href=\"index.php?name=Account&op=info&uname=$s_uname\" title=\"".displayTime($s_time)." - IP: $s_host_addr\" target=\"_blank\">$s_uname</a> - <a href=\"$s_url\" title=\"$s_url\" target=\"_blank\">$linkstrip</a><br>";
				} else {
					$title_who = "<a href=\"index.php?name=Account&op=info&uname=$s_uname\" title=\"".displayTime($s_time)." - IP: $s_host_addr\" target=\"_blank\">$s_uname</a> - <a href=\"$s_url\" title=\"$s_url\" target=\"_blank\">$linkstrip_admin</a><br>";
				}
			} else {
				$title_who = "<a href=\"http://www.dnsstuff.com/tools/whois.ch?ip=$s_host_addr\" title=\"".displayTime($s_time)."\" target=\"_blank\">$s_uname</a> - <a href=\"$s_url\" title=\"$s_url\" target=\"_blank\">$linkstrip</a><br>";
			}
			$who_online[$guest] .= $title_who;
			$i++;
		}
		if ($who_online[2] != "") $content_who .= "<img src=\"images/blocks/admin.gif\">&nbsp;<span class=\"content\"><b>"._ADMINISTR."</b></span><br>$who_online[2]<br>";
		if ($who_online[0] != "") $content_who .= "<img src=\"images/blocks/member.gif\">&nbsp;<span class=\"content\"><b>"._MEMBRES."</b></span><br>$who_online[0]<br>";
		if ($who_online[1] != "") $content_who .= "<img src=\"images/blocks/anony.gif\">&nbsp;<span class=\"content\"><b>"._VISITEURS."</b></span><br>$who_online[1]<br>";
		$title = ""._WHO."";
		$content_who .= "<img src=\"images/blocks/group.gif\">&nbsp;<span class=\"content\"><b>"._OVERALL.": $i</b></span>";
		themesidebox($title, $content_who, 6);
	}
}

// Format add block
function addblocks($str) {
	global $blocks, $blocks_c, $home, $showbanners, $foot, $db, $total_time, $start_time, $time_db, $foot, $time_db_query, $variables;
	preg_match_all('#{%BLOCKS([^%]+)%}#iUs',$str,$blk);
	$ci = sizeof($blk[1]);
	for ($i = 0; $i < $ci; $i++) {
		$blk[0][$i] = '#'.$blk[0][$i].'#';
		$telo = trim($blk[1][$i]);
		$pos = strtolower($telo[0]);
		switch($pos) {
			case 'l':
			if ($blocks == "" || $blocks == "0"|| $blocks == "1") {
				ob_start();
				blocks('l');
				$blk[1][$i] = ob_get_contents();
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 'r':
			if ($blocks == "" || $blocks == "0"|| $blocks == "2") {
				ob_start();
				blocks('r');
				$blk[1][$i] = ob_get_contents();
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 'c':
			if ($blocks_c == "" || $blocks_c == "0" || $blocks_c == "1") {
				ob_start();
				blocks('c');
				$blk[1][$i] = ob_get_contents();
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 'd':
			if ($blocks_c == "" || $blocks_c == "0"|| $blocks_c == "2") {
				ob_start();
				blocks('d');
				$blk[1][$i] = ob_get_contents();
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 'b':
			blocks('b');
			$blk[1][$i] = $showbanners;
			break;
			case 'f':
			blocks('f');
			$blk[1][$i] = $foot;
			break;
			case 'm':
			if ($home == 1) {
				ob_start();
				message_box();
				$blk[1][$i] = ob_get_contents();
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 't':
			if ($time_db == "1") {
				$mtime = microtime();
				$mtime = explode(" ",$mtime);
				$mtime = $mtime[1] + $mtime[0];
				$end_time = $mtime;
				$total_time = ($end_time - $start_time);
				$sqlnums = $db->num_queries;
				$total_time_db = $db->total_time_db;
				$total_time = ""._PAGEGENERATION.": ".substr($total_time,0,5)." "._SEC.". "._AND." ".$sqlnums." "._PAGEGENERATION_DB." ".substr($total_time_db,0,5)." "._SEC.".";
				$footer .= $total_time;
			}
			$blk[1][$i] = $footer;
			break;
			case 'v':
			if ($variables == "1" && is_admin($admin)) {
				ob_start();
				variables();
				$blk[1][$i] = "<div align=\"left\">".ob_get_contents()."</div><br /><br />";
				ob_end_clean();
			} else {
				$blk[1][$i] = "";
			}
			break;
			case 'q':
			if ($time_db_query == "1" && is_admin($admin)) {
				$total_time_query = $db->time_query;
				$blk[1][$i] = "<div align=\"left\">".$total_time_query."</div>";
			} else {
				$blk[1][$i] = "";
			}
			break;
			default:
			$telo = explode(",", $telo);
			ob_start();
			blocks($telo[0], $telo[1]);
			$blk[1][$i] = ob_get_contents();
			ob_end_clean();
		}
	}
	return preg_replace($blk[0], $blk[1], $str);
}

// Format block
function blocks($side, $fly="") {
	global $b_id, $prefix, $multilingual, $currentlang, $db, $admin, $user, $name, $home, $pos, $blockfile;
	static $barr;
	$querylang = ($multilingual == 1) ? "AND (blanguage='$currentlang' OR blanguage='')" : "";
	$pos = strtolower($side[0]);
	$side = $pos;
	if (!isset($barr)) {
		$result = $db->sql_query("SELECT bid, bkey, title, content, url, blockfile, view, expire, action, bposition, which FROM ".$prefix."_blocks WHERE active='1' $querylang ORDER BY weight ASC");
		while(list($bid, $bkey, $title, $content, $url, $blockfile, $view, $expire, $action, $bposition, $which) = $db->sql_fetchrow($result)) {
			$bid = intval($bid);
			$view = intval($view);
			$where_mas = explode(",", $which);
			$barr[] = array($bid, $bkey, $title, $content, $url, $blockfile, $view, $expire, $action, $bposition, $where_mas);
		}
	}
	if ($fly != "") {
		$b_id = 0;
		$flag = 0;
		$blockfile = "";
		if (false === strpos($fly, "-")) {
			$b_id = intval($fly);
		} else {
			$blockfile = trim($fly);
		}
		$ci = sizeof($barr);
		for ($i = 0; $i < $ci; $i++) {
			if (($b_id != 0 && $barr[$i][0] == $b_id) || ($blockfile != "" && $barr[$i][5] == $blockfile)) {
				list($bid, $bkey, $title, $content, $url, $blockfile, $view, $expire, $action, $bposition, $where_mas) = $barr[$i];
				$b_id = $bid;
				$flag = 1;
				break;
			}
		}
		if ($flag == 1) {
			if ($view == 0) {
				return render_blocks($side, $blockfile, $title, $content, $bid, $url);
			} elseif ($view == 1 && is_user($user) || is_admin($admin)) {
				return render_blocks($side, $blockfile, $title, $content, $bid, $url);
			} elseif ($view == 2 && is_admin($admin)) {
				return render_blocks($side, $blockfile, $title, $content, $bid, $url);
			} elseif ($view == 3 && !is_user($user) || is_admin($admin)) {
				return render_blocks($side, $blockfile, $title, $content, $bid, $url);
			}
		}
	} else {
		$ci = sizeof($barr);
		for ($i = 0; $i < $ci; $i++) {
			if ($barr[$i][9] != $side) continue;
			$flag_where = 0;
			$where_mas = $barr[$i][10];
			switch ($where_mas[0]) {
				case "all":
				$flag_where = 1;
				break;
				case "":
				$flag_where = 1;
				break;
				case "infly":
				$flag_where = 0;
				break;
				case "home":
				$flag_where = ($home == 1) ? 1 : 0;
				break;
				case "ihome":
				if ($home == 1) $flag_where = 1;
				default:
				foreach ($where_mas as $key => $val) {
					if ($val == $name) $flag_where = 1;
				}
				break;
			}
			if ($flag_where == 1) {
				list($bid, $bkey, $title, $content, $url, $blockfile, $view, $expire, $action, $bposition, $where_mas) = $barr[$i];
				$b_id = $bid;
				if ($expire && $expire < time()) {
					if ($action == "d") {
						$db->sql_query("UPDATE ".$prefix."_blocks SET active='0', expire='0' WHERE bid='$bid'");
						return;
					} elseif ($action == "r") {
						$db->sql_query("DELETE FROM ".$prefix."_blocks WHERE bid='$bid'");
						return;
					}
				}
				switch ($bkey) {
					case "admin":
					adminblock();
					break;
					case "userbox":
					userblock();
					break;
					default:
					if ($view == 0) {
						render_blocks($side, $blockfile, $title, $content, $bid, $url);
					} elseif ($view == 1 && is_user($user) || is_admin($admin)) {
						render_blocks($side, $blockfile, $title, $content, $bid, $url);
					} elseif ($view == 2 && is_admin($admin)) {
						render_blocks($side, $blockfile, $title, $content, $bid, $url);
					} elseif ($view == 3 && !is_user($user) || is_admin($admin)) {
						render_blocks($side, $blockfile, $title, $content, $bid, $url);
					}
					break;
				}
			}
		}
	}
}

// Format block
function render_blocks($side, $blockfile, $blocktitle, $content, $bid, $url) {
	global $showbanners, $foot;
	if ($url == "") {
		if ($blockfile != "") {
			if (file_exists("blocks/".$blockfile."")) {
				require("blocks/".$blockfile."");
			} else {
				$content = "<center>"._BLOCKPROBLEM."</center>";
			}
		}
		if (!isset($content) || empty($content)) $content = "<center>"._BLOCKPROBLEM2."</center>";
		switch($side) {
			case "b":
			$showbanners = $content;
			break;
			case "f":
			$foot = $content;
			break;
			case "n":
			echo $content;
			break;
			case "p":
			return $content;
			break;
			case "o":
			return themesidebox($blocktitle, $content);
			break;
			default:
			themesidebox($blocktitle, $content);
			break;
		}
	} else {
		rss($bid);
	}
}

// Format RSS
function rss($bid) {
    global $prefix, $db;
    $bid = intval($bid);
    list($title, $content, $url, $refresh, $otime) = $db->sql_fetchrow($db->sql_query("SELECT title, content, url, refresh, time FROM ".$prefix."_blocks WHERE bid='$bid'"));
	$past = time() - $refresh;
	if ($otime < $past) {
        $btime = time();
        $rdf = parse_url($url);
        $fp = fsockopen($rdf['host'], 80, $errno, $errstr, 15);
		if ($fp) {
			fputs($fp, "GET ".$rdf['path']."?".$rdf['query']." HTTP/1.0\r\n");
			fputs($fp, "HOST: ".$rdf['host']."\r\n\r\n");
			$string = "";
			while(!feof($fp)) {
				$pagetext = fgets($fp, 300);
				$string .= chop($pagetext);
			}
			fputs($fp,"Connection: close\r\n\r\n");
			fclose($fp);
			$items = explode("</item>",$string);
			for ($i = 0; $i < 10; $i++) {
				if ($items[$i] != "") {
					$title_rss = preg_replace("/.*<title>/", "", $items[$i]);
					$title_rss = preg_replace("/<\/title>.*/", "", $title_rss);
					$title_rss = text_filter(html_entity_decode($title_rss));
					$link_rss = preg_replace("/.*<link>/", "", $items[$i]);
					$link_rss = preg_replace("/<\/link>.*/", "", $link_rss);
					$link_rss = text_filter(html_entity_decode($link_rss));
					$description_rss = preg_replace("/.*<description>/", "", $items[$i]);
					$description_rss = preg_replace("/<\/description>.*/", "", $description_rss);
					$description_rss = text_filter(html_entity_decode(str_replace("]]>", "", $description_rss)));
					$pubdate_rss = preg_replace("/.*<pubDate>/", "", $items[$i]);
					$pubdate_rss = preg_replace("/<\/pubDate>.*/", "", $pubdate_rss);
					$pubdate_rss = text_filter(html_entity_decode(date("d.m.Y H:m:s", strtotime($pubdate_rss))));
					$content_rss .= "<tr><td><img src=\"images/arrow.gif\" border=\"0\"> $pubdate_rss - <a href=\"$link_rss\" target=\"_blank\" title=\"$title_rss\">$title_rss</a></td></tr><tr><td>$description_rss</td></tr>";
				} else {
					$content_rss = "<tr><td align=\"center\">"._RSS_PROBLEM."</td></tr>";
				}
			}
		} else {
			$content_rss = "<tr><td align=\"center\">"._RSS_PROBLEM."</td></tr>";
		}
		$content = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" align=\"center\">$content_rss</table>";
		$db->sql_query("UPDATE ".$prefix."_blocks SET content='$content', time='$btime' WHERE bid='$bid'");
	}
	themesidebox($title, $content);
}

// Load RSS
function rss_load($url, $hid=0) {
	global $prefix, $db;
	if ($hid != 0 OR ($hid == 0 AND $url != "0" AND $url != "http://") AND $url != "") {
		if ($hid != 0) {
			$hid = intval($hid);
			$result = $db->sql_query("SELECT sitename, headlinesurl FROM ".$prefix."_headlines WHERE hid='$hid'");
			list($nsitename, $url) = $db->sql_fetchrow($result);
			$siteurl = preg_replace("/http\:\/\//", "", $url);
			$siteurl = explode("/", $siteurl);
			$title = $nsitename;
		} else {
			if (!preg_match("/http\:\/\//", $url)) $url = "http://$url";
			$siteurl = preg_replace("/http\:\/\//", "", $url);
			$siteurl = explode("/", $siteurl);
			$title = "http://$siteurl[0]";
		}
		$rdf = parse_url($url);
		$fp = @fsockopen($rdf['host'], 80, $errno, $errstr, 15);
		if ($fp) {
			fputs($fp, "GET ".$rdf['path']."?".$rdf['query']." HTTP/1.0\r\n");
			fputs($fp, "HOST: ".$rdf['host']."\r\n\r\n");
			$string = "";
			while (!feof($fp)) {
				$pagetext = fgets($fp, 300);
				$string .= chop($pagetext);
			}
			fputs($fp,"Connection: close\r\n\r\n");
			fclose($fp);
			$items = explode("</item>",$string);
			$rss_limit = end(explode("=", $url));
			if (preg_match("/[^0-9]/", $rss_limit) || $rss_limit == "") $rss_limit = "10";
			for ($i = 0; $i < $rss_limit; $i++) {
				if ($items[$i] != "") {
					$title_rss = preg_replace("/.*<title>/", "", $items[$i]);
					$title_rss = preg_replace("/<\/title>.*/", "", $title_rss);
					$title_rss = text_filter(html_entity_decode($title_rss));
					$link_rss = preg_replace("/.*<link>/", "", $items[$i]);
					$link_rss = preg_replace("/<\/link>.*/", "", $link_rss);
					$link_rss = text_filter(html_entity_decode($link_rss));
					$description_rss = preg_replace("/.*<description>/", "", $items[$i]);
					$description_rss = preg_replace("/<\/description>.*/", "", $description_rss);
					$description_rss = text_filter(html_entity_decode(str_replace("]]>", "", $description_rss)));
					$pubdate_rss = preg_replace("/.*<pubDate>/", "", $items[$i]);
					$pubdate_rss = preg_replace("/<\/pubDate>.*/", "", $pubdate_rss);
					$pubdate_rss = text_filter(html_entity_decode(date("d.m.Y H:m:s", strtotime($pubdate_rss))));
					$content .= "<tr><td><img src=\"images/arrow.gif\" border=\"0\"> $pubdate_rss - <a href=\"$link_rss\" target=\"_blank\" title=\"$title_rss\">$title_rss</a></td></tr><tr><td>$description_rss</td></tr>";
				} else {
					$content = "<tr><td align=\"center\">"._RSS_PROBLEM."</td></tr>";
				}
			}
		} else {
			$content = "<tr><td align=\"center\">"._RSS_PROBLEM."</td></tr>";
		}
		echo "<center><font class=\"option\"><b>"._RSS_FROM."</b></font> <a href=\"http://$siteurl[0]\" target=\"_blank\" title=\"$title\"><b>$title</b></a></center><br /><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" align=\"center\">$content</table>";
	}
}

// Format language
function get_lang($module="") {
	global $multilingual, $currentlang, $language, $user_cookie_t;
	if (isset($_REQUEST['newlang']) && $multilingual == "1") {
		if (file_exists("language/lang-".$_REQUEST['newlang'].".php")) {
			setcookie("lang", $_REQUEST['newlang'], time() + intval($user_cookie_t));
			require_once("language/lang-".$_REQUEST['newlang'].".php");
			$currentlang = $_REQUEST['newlang'];
		} else {
			setcookie("lang", $language, time() + intval($user_cookie_t));
			require_once("language/lang-".$language.".php");
			$currentlang = $language;
		}
	} elseif (isset($_COOKIE['lang']) && $multilingual == "1") {
		if (file_exists("language/lang-".$_COOKIE['lang'].".php")) {
			require_once("language/lang-".$_COOKIE['lang'].".php");
			$currentlang = $_COOKIE['lang'];
		} else {
			require_once("language/lang-".$language.".php");
			$currentlang = $language;
		}
	} else {
		setcookie("lang", $language, time() + intval($user_cookie_t));
		require_once("language/lang-".$language.".php");
		$currentlang = $language;
	}
	if ($module != "") {
		if (file_exists("modules/$module/language/lang-".$currentlang.".php")) {
			if ($module == "admin") {
				include_once("admin/language/lang-".$currentlang.".php");
			} else {
				include_once("modules/$module/language/lang-".$currentlang.".php");
			}
		} else {
			if ($module == "admin") {
				include_once("admin/language/lang-".$currentlang.".php");
			} else {
				include_once("modules/$module/language/lang-".$language.".php");
			}
		}
	}
}

// Format Page
function get_page($module_name) {
	OpenTable();
	echo "<center>[ <a href=\"javascript:history.go(-1)\">"._PAGEBACK."</a> | <a href=index.php?name=$module_name>"._PAGEHOME."</a> | <a href=#>"._PAGETOP."</a> ]</center>";
	CloseTable();
}

// Format Nummer Page
function num_page($module_name="", $numstories, $numpages, $storynum, $module_link="") {
	global $pagenum, $admin_file;
	$pagenum = (intval($pagenum)) ? $pagenum : 1;
	if ($numpages > 1) {
		if (defined("ADMIN_FILE")) {
			$index = $admin_file;
			$module = "";
		} else {
			$index = "index";
			$module = "name=".$module_name."&";
		}
		OpenTable();
		echo "<center><b>"._OVERALL." $numstories "._ON." $numpages "._PAGE_S." $storynum "._PERPAGE."</b><br />";
        if ($pagenum > 1) {
			$prevpage = $pagenum - 1;
			echo "<a href=\"".$index.".php?".$module."".$module_link."pagenum=$prevpage\">[&lt;&lt;]&nbsp;</a>";
        }
		echo "[ ";
        for ($i = 1; $i < $numpages+1; $i++) {
            if ($i == $pagenum) {
                echo " $i ";
            } else {
				if ((($i > ($pagenum - 8)) && ($i < ($pagenum + 8))) OR ($i == $numpages) || ($i == 1)) {
					echo "<a href=\"".$index.".php?".$module."".$module_link."pagenum=$i\"><b>$i</b></a>";
				}
			}
			if ($i < $numpages) {
				if (($i > ($pagenum - 9)) && ($i < ($pagenum + 8))) echo " | ";
				if (($pagenum > 9) && ($i == 1)) echo " | ...";
				if (($pagenum < ($numpages - 8)) && ($i == ($numpages - 1))) echo "... | ";
			} else {
				echo " ]"; 
			} 
        }
        if ($pagenum < $numpages) {
            $nextpage = $pagenum + 1;
			echo "<a href=\"".$index.".php?".$module."".$module_link."pagenum=$nextpage\">&nbsp;[&gt;&gt;]</a>";
        }
        echo "</center>" ;
		CloseTable();
    }
}

// Format Password
function gen_pass($m) {
	$m = intval($m);
	$pass = "";
	for ($i = 0; $i < $m; $i++) {
		$te = mt_rand(48, 122);
		if (($te > 57 && $te < 65) || ($te > 90 && $te < 97)) $te = $te - 9;
		$pass .= chr($te);
	}
	return $pass;
}

// Format Sessions
function online() {
	global $user, $prefix, $db, $admin, $name, $siteclose, $sess_t;
    $ip = getenv("REMOTE_ADDR");
	$url = htmlspecialchars(getenv("REQUEST_URI"));
	if ($siteclose == 1) {
		if (!is_admin($admin) && !defined('ADMIN_FILE')) die("<br /><br /><center><img src=\"images/logos/logo.gif\" /><br /><br /><b>"._CLOSE_TEXT."</b></center>");
	}
    if (is_admin($admin)) {
		$uname = text_filter(substr($admin[1], 0, 25), 1);
		$guest = 2;
	} elseif (!defined("ADMIN_FILE") && is_user($user)) {
		$uname = text_filter(substr($user[1], 0, 25), 1);
		$guest = 0;
	} elseif (!defined("ADMIN_FILE") && !is_user($user)) {
		$uname = $ip;
		$guest = 1;
	}
    $past = time() - intval($sess_t); 
    $db->sql_query("DELETE FROM ".$prefix."_session WHERE time < '$past'"); 
    $ctime = time();
    if ($uname) {
		$name = addslashes($name);
		$db->sql_query("UPDATE ".$prefix."_session SET uname='$uname', time='$ctime', host_addr='$ip', guest='$guest', module='$name', url='$url' WHERE uname='$uname'");
		$e = @mysql_info();
		preg_match("/^\D+(\d+)/", $e, $matches);
		if ($matches[1] == 0) $db->sql_query("INSERT INTO ".$prefix."_session (uname, time, host_addr, guest, module, url) VALUES ('$uname', '$ctime', '$ip', '$guest', '$name', '$url')");
	}
}

// Format BB Code
function get_code($id) {
	global $redaktor, $smilies;
	if ((defined("ADMIN_FILE") && $redaktor == 1) || (!defined("ADMIN_FILE"))) {
		$code = "<script language=\"JavaScript\" type=\"text/javascript\" src=\"javascripts/InsertCode.js\"></script>"
		
		."<div class=\"editor\">"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"RowsTextarea('".$id."', 1)\"><img title=\""._EPLUS."\" src=\"images/editor/plus.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"RowsTextarea('".$id."', 0)\"><img title=\""._EMINUS."\" src=\"images/editor/minus.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('b', '', '', '', '".$id."')\"><img title=\""._EBOLD."\" src=\"images/editor/bold.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('i', '', '', '', '".$id."')\"><img title=\""._EITALIC."\" src=\"images/editor/italic.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('u', '', '', '', '".$id."')\"><img title=\""._EUNDERLINE."\" src=\"images/editor/underline.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('s', '', '', '', '".$id."')\"><img title=\""._ESTRIKET."\" src=\"images/editor/striket.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('li', '', '', '', '".$id."')\"><img title=\""._ELI."\" src=\"images/editor/li.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('hr', '', '', '', '".$id."')\"><img title=\""._EHR."\" src=\"images/editor/hr.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('left', '', '', '', '".$id."')\"><img title=\""._ELEFT."\" src=\"images/editor/left.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('center', '', '', '', '".$id."')\"><img title=\""._ECENTER."\" src=\"images/editor/center.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('right', '', '', '', '".$id."')\"><img title=\""._ERIGHT."\" src=\"images/editor/right.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('justify', '', '', '', '".$id."')\"><img title=\""._EYUSTIFY."\" src=\"images/editor/justify.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('code', '', '', '', '".$id."')\"><img title=\""._CODE."\" src=\"images/editor/code.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('php', '', '', '', '".$id."')\"><img title=\"PHP - "._CODE."\" src=\"images/editor/php.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('hide', '', '', '', '".$id."')\"><img title=\""._HIDE."\" src=\"images/editor/hide.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('url', '"._JINFO."', '"._JTYPE."', '"._JERROR."', '".$id."')\"><img title=\""._EURL."\" src=\"images/editor/url.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('mail', '"._JINFO."', '"._JTYPE."', '"._JERROR."', '".$id."')\"><img title=\""._EEMAIL."\" src=\"images/editor/mail.gif\"></div>"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('img', '', '', '', '".$id."')\"><img title=\""._EIMG."\" src=\"images/editor/img.gif\"></div>"
		."</div>"
		
		
		."<div class=\"editor\">"
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('quote', '', '', '', '".$id."')\"><img title=\""._EQUOTE."\" src=\"images/editor/quote.gif\"></div>";
		if (substr(""._LOCALE."", 0, 2) == "ru") {
			$code .= "<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"translateAlltoCyrillic()\"><img title=\""._ERUS."\" src=\"images/editor/rus.gif\"></div>"
			."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"translateAlltoLatin()\"><img title=\""._ELAT."\" src=\"images/editor/eng.gif\"></div>"
		////////////////////
		."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"InsertCode('swf', '', '', '', '".$id."')\"><img title=\"Вставить флэш (swf)\" src=\"images/editor/swf.gif\"></div>"
		///////////////////		
			."<div class='editorbutton' OnMouseOver=\"this.className='editorbuttonover';\" OnMouseOut=\"this.className='editorbutton';\" OnClick=\"changelanguage()\"><img title=\""._EAUTOTR."\" src=\"images/editor/auto.gif\"></div>";
		}
		$fonts = 0;
		$font = array("Arial", "Courier New", "Mistral", "Impact", "Sans Serif", "Tahoma", "Helvetica", "Verdana");
		foreach ($font as $val) if ($val != "") $fonts .= "<option style=\"font-family: ".$val.";\" value=\"".$val."\">".$val."</option>";
		$colors = 0;
		$color = array("black", "silver", "gray", "white", "maroon", "orange", "orangered", "red", "purple", "fuchsia", "green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua");
		foreach ($color as $val) if ($val != "") $colors .= "<option style=\"color: ".$val.";\" value=\"".$val."\">"._ECOLOR."</option>";
		$fsizes = 0;
		$fsize = array("8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "32");
		foreach ($fsize as $val) if ($val != "") $fsizes .= "<option value=\"".$val."\">"._ESIZE." ".$val."</option>";
		$code .= "<div class='editorselec'><select style=\"font-size: 10px;\" name=\"family\" onChange=\"InsertCode('family', this.options[this.selectedIndex].value, '', '', '".$id."')\">".$fonts."</select></div>"
		."<div class='editorselec'><select style=\"font-size: 10px;\" name=\"color\" onChange=\"InsertCode('color', this.options[this.selectedIndex].value, '', '', '".$id."')\">".$colors."</select></div>"
		."<div class='editorselec'><select style=\"font-size: 10px;\" name=\"size\" onChange=\"InsertCode('size', this.options[this.selectedIndex].value, '', '', '".$id."')\">".$fsizes."</select></div></div>";
		if ($smilies) {
			$code .= "<div class=\"smilies\">";
			$i = 1;
			$dir = opendir("images/smilies");
			while ($entry = readdir($dir)) {
				if (preg_match("/(\.gif|\.png|\.jpg|\.jpeg)$/is", $entry) && $entry != "." && $entry != "..") {
					$i = ($i < 10) ? "0".$i ."" : $i;
					$code .= " <img src=\"images/smilies/$i.gif\" OnClick=\"AddSmile(' *$i');\" style=\"cursor: pointer; margin: 3px 2px 0px 0px;\" alt=\""._SMILIE." - $i\" title=\""._SMILIE." - $i\">";
					$i++;
				}
			}
			closedir($dir);
			$code .= "</div>";
		}
		return $code;
	}
}

// Check type upload file
function check_file($type, $atypefile) {
	$strtypefile = str_replace(",", "|", $atypefile);
	if (!preg_match("/".$strtypefile."/i", $type) || preg_match("/php|php3|php4|php5|php6|js|htm|html|phtml|cgi|pl|perl|asp/i", $type)) return ""._ERROR_FILE."";
}

// Check size upload file
function check_size($file, $width, $height) {
	list($imgwidth, $imgheight) = getimagesize($file);
	if ($imgwidth > $width || $imgheight > $height) return ""._ERROR_SIZE."";
}

// Upload file
function upload($directory, $atypefile, $maxsize, $namefile, $width, $height) {
	global $stop;
	if ($_POST['sitefile'] != "") {
		$afile = str_replace(array("&", "?", "#"), "", $_POST['sitefile']);
		$type = strtolower(end(explode(".", $afile)));
		if (!check_file($type, $atypefile) && !check_size($_POST['sitefile'], $width, $height)) {
			$fn = $_POST['sitefile'];
			$path_sitefile = fopen($fn, "rb"); 
			if (!$path_sitefile) { 
				$stop = ""._ERROR_DOWN."";
				return 0;
			} else {
				$newname = ($namefile) ? "".$namefile."-".gen_pass(10).".".$type."" : "".gen_pass(15).".".$type."";
				$directoryp = "".$directory."/".basename($newname)."";
				if (file_exists($directoryp)) {
					$stop = ""._ERROR_EXIST."";
					return 0;
				} else {
					while (!feof($path_sitefile)) $data .= fread($path_sitefile, 1024);
					fclose($path_sitefile);
					$path_sitefile = fopen("".$directory."/".basename($newname)."", "wb");
					if (!$path_sitefile) {
						$stop = ""._ERROR_UP."";
						return 0;
					} else {
						fwrite($path_sitefile, $data); 
						fclose($path_sitefile);
						if (file_exists($directoryp)) {
							if (filesize($directoryp) > $maxsize) {
								unlink($directoryp);
								$stop = ""._ERROR_BIG."";
								return 0;
							} else {
								return $newname;
							}
						}
					}
				}
			}
		} else {
			$stop = (!check_file($type, $atypefile)) ? "".check_size($_POST['sitefile'], $width, $height)."" : "".check_file($type, $atypefile)."";
			return 0;
		}
	}
	if (intval($_FILES['userfile']['size'])) {
		if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
			if ($_FILES['userfile']['size'] > $maxsize) {
				$stop = ""._ERROR_BIG."";
				return 0;
			} else {
				$type = strtolower(end(explode(".", $_FILES['userfile']['name'])));
				if (!check_file($type, $atypefile) && !check_size($_FILES['userfile']['tmp_name'], $width, $height)) {
					if (file_exists("".$directory."/".$type."")) {
						$stop = ""._ERROR_EXIST."";
						return 0;
					} else {
						$newname = ($namefile) ? "".$namefile."-".gen_pass(10).".".$type."" : "".gen_pass(15).".".$type."";
						$res = copy($_FILES['userfile']['tmp_name'], "".$directory."/".$newname."");
						if (!$res) {
							$stop = ""._ERROR_UP."";
							return 0;
						} else {
							return $newname;
						}
					}
				} else {
					$stop = (!check_file($type, $atypefile)) ? "".check_size($_FILES['userfile']['tmp_name'], $width, $height)."" : "".check_file($type, $atypefile)."";
					return 0;
				}
			}
		} else {
			$stop = ""._ERROR_DOWN."";
			return 0;
		}
	}
}

// Preview
function preview($text) {
	OpenTable();
	echo "<fieldset><legend>"._PREVIEW."</legend><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\" align=\"center\"><tr><td>".$text."</td></tr></table></fieldset>";
	CloseTable();
}

// Format language
function language($lang="") {
	$dir = opendir("language");
	$content = "<option value=\"\">"._ALL."</option>";
	while ($file = readdir($dir)) {
		if (preg_match("/^lang\-(.+)\.php/", $file, $matches)) {
			$langfound = $matches[1];
			$title = ucfirst($langfound);
			$selected = ($lang == $langfound) ? "selected" : "";
			$content .= "<option value=\"$langfound\" $selected>".$title."</option>";
		}
	}
	closedir($dir);
	return $content;
}

// Format image preview PHP GD
function create_img_gd($imgfile, $imgthumb, $newwidth) {
	if (function_exists("imagecreate")) {
		$imginfo = @getimagesize($imgfile);
		switch($imginfo[2]) {
			case 1:
			$type = IMG_GIF;
			break;
			case 2:
			$type = IMG_JPG;
			break;
			case 3:
			$type = IMG_PNG;
			break;
			case 4:
			$type = IMG_WBMP;
			break;
			default:
			return $imgfile;
			break;
		}
		switch($type) {
			case IMG_GIF:
			if (!function_exists("imagecreatefromgif")) return $imgfile;
			$srcImage = @imagecreatefromgif("$imgfile");
			break;
			case IMG_JPG:
			if (!function_exists("imagecreatefromjpeg")) return $imgfile;
			$srcImage = @ImageCreateFromJpeg($imgfile);
			break;
			case IMG_PNG:
			if(!function_exists("imagecreatefrompng")) return $imgfile;
			$srcImage = @imagecreatefrompng("$imgfile");
			break;
			case IMG_WBMP:
			if (!function_exists("imagecreatefromwbmp")) return $imgfile;
			$srcImage = @imagecreatefromwbmp("$imgfile");
			break;
			default:
			return $imgfile;
		}
		if ($srcImage){
			$srcWidth = $imginfo[0];
			$srcHeight = $imginfo[1];
			$ratioWidth = $srcWidth / $newwidth;
			$destWidth = $newwidth;
			$destHeight = $srcHeight / $ratioWidth;
			$destImage = @imagecreatetruecolor($destWidth, $destHeight);
            @imagealphablending($destImage, true);
            @imagealphablending($srcImage, false);
			@imagecopyresized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
			switch($type) {
				case IMG_GIF:
				@imagegif($destImage, "$imgthumb");
				break;
				case IMG_JPG:
				@imagejpeg($destImage, "$imgthumb");
				break;
				case IMG_PNG:
				@imagepng($destImage, "$imgthumb");
				break;
				case IMG_WBMP:
				@imagewbmp($destImage, "$imgthumb");
				break;
			}
			@imagedestroy($srcImage);
			@imagedestroy($destImage);
			return $imgthumb;
		} else {
			return $imgfile;
		}
	} else {
		return $imgfile;
	}
}

// Format image preview
function create_img($dir, $img, $width) {
	if (file_exists("".$dir."/".$img."") && !file_exists("".$dir."/thumb/".$img."")) {
		if (!file_exists("".$dir."/thumb")) mkdir("".$dir."/thumb");
		$thumb = create_img_gd("".$dir."/".$img."", "".$dir."/thumb/".$img."", $width);
		$img = ($thumb) ? "".$dir."/thumb/".$img."" : "".$dir."/".$img."";
	} elseif (file_exists("".$dir."/".$img."") && file_exists("".$dir."/thumb/".$img."")) {
		$img = "".$dir."/thumb/".$img."";
	} elseif (file_exists("".$dir."/".$img."")) {
		$img = "".$dir."/".$img."";
	} else {
		$img = $img;
	}
	return $img;
}

// Replace break
function replace_break($text) {
	global $redaktor;
	$out = (($redaktor == 1 && defined('ADMIN_FILE')) || (!defined('ADMIN_FILE'))) ? preg_replace("/<br>|<br \/>/", "", $text) : $text;
	return $out;
}

// Save text
function save_text($text) {
	global $redaktor;
	$out = ($redaktor == 1) ? nl2br(stripslashes(text_filter($text, 2))) : stripslashes($text);
	return $out;
}

// Fields in
function fields_in($fieldb, $fieldc) {
	if (!isset($_POST['field'])) {
		$fieldb = $fieldb;
	} else {
		$fieldb = fields_save($_POST['field']);
	}
	$fieldb = explode("|", $fieldb);
	$fieldc = explode("||", $fieldc);
	$i = 0;
	foreach ($fieldc as $val) {
		if ($val != "") {
			preg_match("#(.*)\|(.*)\|(.*)\|(.*)#i", $val, $out);
			if ($out[1] != "0") {
				$fieldin = ($fieldb[$i]) ? $fieldb[$i] : $out[2];
				if ($out[3] == 1) {
					$field = "<input type=\"text\" name=\"field[]\" value=\"".$fieldin."\" size=\"65\" style=\"width:400px\">";
				} elseif ($out[3] == 2) {
					$field = "<textarea name=\"field[]\" cols=\"15\" rows=\"5\" style=\"width:400px\">".$fieldin."</textarea>";
				} elseif ($out[3] == 3) {
					$field = "<select name=\"field[]\" style=\"width:400px\">";
					$field .= "<option value=\"0\">"._NO."</option>";
					$fieldcs = explode(",", $out[2]);
					$i = 0;
					foreach ($fieldcs as $val) {
						if ($val != "") {
							$sel = ($val == $fieldin) ? "selected" : "";
							$field .= "<option value=\"$val\" $sel>$val</option>\n";
						}
					}
					$field .= "</select></td></tr>";
				}
				$fields .= "<tr class=\"bgcolor1\"><td>".$out[1].":</td><td>".$field."</td></tr>";
			}
		}
		$i++;
	}
	return $fields;
}

// Fields out
function fields_out($fieldb, $fieldc) {
	$fieldb = explode("|", $fieldb);
	$fieldc = explode("||", $fieldc);
	$i = 0;
	$fields = "";
	foreach ($fieldc as $val) {
		if ($val != "" && $fieldb[$i] != "" && $fieldb[$i] != "0") {
			preg_match("#(.*)\|(.*)\|(.*)\|(.*)#i", $val, $out);
			$fields .= "".$out[1].": ".$fieldb[$i]."<br />";
		}
		$i++;
	}
	return $fields;
}

// Fields save
function fields_save($field) {
	$b = 0;
	foreach ($field as $val) {
		if ($val != "") {
			if ($b == 0) {
				$fields = $val;
				$b++;
			} else {
				$fields .= "|".$val."";
			}
		}
	}
	return $fields;
}

// Format image key for captcha
switch(isset($_GET['captcha'])) {
	case "1":
		session_start();
		unset($_SESSION['captcha']);
		$random = gen_pass(10);
		$_SESSION['captcha'] = $random;
		$code = substr(hexdec(md5("".date("F j")."".$random."".$conf['sitekey']."")), 2, 6);
		$image = ImageCreateFromJpeg("images/code_bg.jpg");
		$text_color = ImageColorAllocate($image, 100, 100, 100);
		Header("Content-type: image/jpeg");
		ImageString($image, 5, 12, 2, $code, $text_color);
		ImageJpeg($image, "", 50);
		ImageDestroy($image);
		exit;
	break;
}

// Format captcha random
function captcha_random() {
	global $user;
	if (extension_loaded("gd") && !is_user($user)) {
		$content = "<tr><td>"._SECURITYCODE.":</td><td><img src=\"index.php?captcha=1\" border=\"1\" title=\""._SECURITYCODE."\" alt=\""._SECURITYCODE."\"></td></tr>"
		."<tr><td>"._TYPESECCODE.":</td><td><input type=\"text\" name=\"check\" size=\"10\" maxlength=\"6\"></td></tr>";
		return $content;
	}
}

// Format captcha check
function captcha_check($id="") {
	global $conf, $user;
	if (($id == 1 && !is_user($user)) || ($_POST['posttype'] == "save" && !is_user($user))) {
		session_start();
		$code = substr(hexdec(md5("".date("F j")."".$_SESSION['captcha']."".$conf['sitekey']."")), 2, 6);
		unset($_SESSION['captcha']);
		if (extension_loaded("gd") && $code != intval($_POST['check'])) {
			return 1;
		} else {
			return 0;
		}
	} else {
		return 0;
	}
}
?>