<?php
############################################################
# \-\-\-\-\-\-\     AzDG  - S C R I P T S    /-/-/-/-/-/-/ #
############################################################
# AzDGDatingMedium        Version 1.9.3                    #
# Written by              AzDG (support@azdg.com)          #
# Created 24/10/02        Last Modified  09/05/04          #
# Scripts Home:           http://www.azdg.com              #
############################################################
# File name               functions.inc.php                #
# File purpose            Functions file                   #
# File created by         AzDG <support@azdg.com>          #
############################################################
if(!defined("C_URL")) die('Can`t access file directly!');

include_once(C_PATH.'/include/vars.inc.php');
if(!C_AUTH) include_once(C_PATH.'/classes/crypt.class.php');
$mlink=@mysql_connect(C_HOST, C_USER, C_PASS) or die("Can`t connect to server<br>Your mysql login or mysql password is wrong.<br>Check it in config file");
@mysql_select_db(C_BASE) or die("Can`t connect to server<br>Database doesn`t exist<br>Or Change Database name in config");

// Specially for masterhost.ru
@ini_set('default_charset', C_CHARSET);

if (isset($_POST)){while (list($name, $value) = each($_POST)){$$name = $value;};};
if (isset($_GET)){while (list($name, $value) = each($_GET)){$$name = $value;};};
function C_URL(){$Tmp = parse_url(C_URL);$Arr = explode(".", $Tmp['host']);Return @$Arr[count($Arr)-2].'.'.@$Arr[count($Arr)-1];}
if(in_array(C_URL(), array('azdg.com','.localhost'))) define('C_DM_MAIL',True);
else define('C_DM_MAIL',False);

function SearchByLike($var)
{
	$var=str_replace('*','%',$var);
	$var=str_replace('?','_',$var);
	Return $var;
}

function id2path($id,$t=null,$pid=null)
{
	if($t == null) $t = '';
	elseif($t == 'a') $t = 'a';
	elseif($t == 'p') $t = 'p';
	elseif($t == 'tp') $t = 'tp';
	else $t = 't';
	$fid = ($pid == null) ? $id : $pid;
	return intval($id / 10000).'/'.intval(($id % 10000) / 100).'/'.$t.intval($fid).'_';
}

function id2pathAudio($id)
{
	return intval($id / 10000).'/'.intval(($id % 10000) / 100).'/'.intval($id);
}

function not_empty($var,$id)
{
	if ($var != '')
	{
		$arr=explode(',',$var);
		sort($arr);reset($arr);
		$file=id2path($id).$arr[0];
		return $file;
	}
	else Return False;
}

function use_pid($pid,$id)
{
	return id2path($id).$pid;
}

function PicPath($num,$id)
{
	return id2path($id).$num;
}

function TPicPath($num,$id)
{
	return id2path($id,'t').$num;
}

function APicPath($num,$id)
{
	return id2path($id,'a').$num;
}

function IsAV($file)
{
	if(ereg(".mp3$", $file) || ereg(".wav$", $file)) Return True;
	else return false;
}

function sprintm($tmp, $v = NULL,$without_footer = null)
{
	global $w;
	include_once C_PATH.'/sheader.php';
	echo '<br><br><br><span class=head><center>'.$tmp.'</span>';
	if ($v == '2') echo '<br><input class=button type=button OnClick=\'history.back()\' value=<<<<<><br>';
	echo '</center><br><br><br><br>';
	if($without_footer === null) include_once C_PATH.'/sfooter.php';
	die;
}

define('SHOW_PAGES','');

function pages($from, $step, $count, $param, $colspan, $prefix=null, $small=null, $page=null, $lnk = null, $lnktype = null)
{
	$str = $prev = $next = '';
	$prf = ($prefix == null) ? '' : $prefix;
	global $w;
	$page = ($page == null) ? '' : $page;
	if ($step < $count)
	{

		if ($from != '0')
		{
			$prev = ($lnk == null) ? " <a href=\"".$page."?".$prf."from=".($from - $step)."&".$prf."step=".$step."&".$param."\">".$w[336]."</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,($from - $step)),$lnk)."\">".$w[336]."</a> ";
		}
		if (($from + $step) < $count)
		{
			$next = ($lnk == null) ? "<a href=\"".$page."?".$prf."from=".($from + $step)."&".$prf."step=".$step."&".$param."\">".$w[337]."</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,($from + $step)),$lnk)."\">".$w[337]."</a> ";
		}

		$str .= ($small == null) ? '<Tr bgcolor='.COLORH.' align=center><td colspan='.$colspan.'>'.$w[115] : '(';

		$str .= ($small == null) ? $prev : '';

		$mesdisp = $step;
		$max = $count;
		$from = ($from > $count) ? $count :	$from;
		$from = (floor($from / $mesdisp ) ) * $mesdisp;
		if ((C_CPAGE % 2) == 1) $pc = (int)((C_CPAGE - 1) / 2);
		else $pc = (int)(C_CPAGE / 2);
		if (($from > $mesdisp * $pc) || $small != null)
		$str .= ($lnk == null) ? "<a href=\"".$page."?".$prf."from=0&".$prf."step=".$step."&".$param."\">1</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,0),$lnk)."\">1</a> ";

		if ($from > $mesdisp * ($pc + 1)) $str .= "<B> . . . </B>";

		for ($nCont = $pc; $nCont >= 1; $nCont--)
		if ($from >= $mesdisp * $nCont)
		{
			$tmpStart = $from - $mesdisp * $nCont;
			$tmpPage = $tmpStart / $mesdisp + 1;
			$str .= ($lnk == null) ? "<a href=\"".$page."?".$prf."from=".$tmpStart."&".$prf."step=".$step."&".$param."\">".$tmpPage."</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,$tmpStart),$lnk)."\">".$tmpPage."</a> ";
		}



		$tmpPage = $from / $mesdisp + 1;
		$str .= ($small == 'forum') ? "" : " [<B>".$tmpPage."</B>] ";


		$tmpMaxPages = (int)(($max - 1) / $mesdisp) * $mesdisp;

		for ($nCont = 1; $nCont <= $pc; $nCont++)
		if ($from + $mesdisp * $nCont <= $tmpMaxPages)
		{
			$tmpStart = $from + $mesdisp * $nCont;
			$tmpPage = $tmpStart / $mesdisp + 1;
			$str .= ($lnk == null) ? "<a href=\"".$page."?".$prf."from=".$tmpStart."&".$prf."step=".$step."&".$param."\">".$tmpPage."</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,$tmpStart),$lnk)."\">".$tmpPage."</a> ";
		}
		if (($from + $mesdisp * ($pc + 1)) < $tmpMaxPages) $str .= "<B> . . . </B>";
		if (($from + $mesdisp * $pc) < $tmpMaxPages)
		{
			$tmpPage = $tmpMaxPages / $mesdisp + 1;
			$str .= ($lnk == null) ? "<a href=\"".$page."?".$prf."from=".$tmpMaxPages."&".$prf."step=".$step."&".$param."\">".$tmpPage."</a> " : " <a href=\"".GenLink($lnktype,array(LANGUAGE,$tmpMaxPages),$lnk)."\">".$tmpPage."</a> ";
		}
		$str .= ($small == null) ? $next : "";

		$str .= ($small == null) ? "</td></tr>" : ")";
	}
	return $str;
}

function horo($m, $d)
{
	// Return number of horoscope
	switch($m)
	{
		case "1":
			$d > 19 ? $h = 2 :
			$h = 1;
			break;
		case "2":
			$d > 18 ? $h = 3 :
			$h = 2;
			break;
		case "3":
			$d > 20 ? $h = 4 :
			$h = 3;
			break;
		case "4":
			$d > 19 ? $h = 5 :
			$h = 4;
			break;
		case "5":
			$d > 20 ? $h = 6 :
			$h = 5;
			break;
		case "6":
			$d > 20 ? $h = 7 :
			$h = 6;
			break;
		case "7":
			$d > 22 ? $h = 8 :
			$h = 7;
			break;
		case "8":
			$d > 22 ? $h = 9 :
			$h = 8;
			break;
		case "9":
			$d > 22 ? $h = 10 :
			$h = 9;
			break;
		case "10":
			$d > 22 ? $h = 11 :
			$h = 10;
			break;
		case "11":
			$d > 21 ? $h = 12 :
			$h = 11;
			break;
		case "12":
			$d > 21 ? $h = 1 :
			$h = 12;
			break;
		default:
			$h = 0;
			break;
	}
	return $h;
}


function simpleXor($InString, $Key)
{
	$KeyList = array();$output = "";
	for($i=0;$i<strlen($Key);$i++)
	$KeyList[$i] = ord(substr($Key, $i, 1));
	for($i=0;$i<strlen($InString);$i++)
	$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
	return $output;
}


function cb($ss)
{
	$ss = htmlspecialchars(stripslashes($ss));
	$ss = str_replace("\r\n", "<br>", $ss);
	$ss = str_replace("\\", "", $ss);
	$ss = str_replace("'", "&rsquo;", $ss);
	$ss = str_replace('"', "&quot;", $ss);
	# a - &#097;
	# c - &#099;
	# o - &#111;
	$ss = preg_replace( "/textarea/i","text&#097;re&#097;", $ss );
	$ss = preg_replace( "/script/i", "s&#099;ript", $ss );
	$ss = preg_replace( "/alert/i", "&#097;lert", $ss );
	$ss = preg_replace( "/about:/i", "&#097;bout:", $ss );
	$ss = preg_replace( "/onmouseover/i", "&#111;nmouseover", $ss );
	$ss = preg_replace( "/onclick/i", "&#111;nclick", $ss );
	$ss = preg_replace( "/onload/i", "&#111;nload", $ss );
	$ss = preg_replace( "/onsubmit/i", "&#111;nsubmit", $ss );
	$ss = str_replace("&amp;#097;", "&#097;", $ss);
	$ss = str_replace("&amp;#099;", "&#099;", $ss);
	$ss = str_replace("&amp;#111;", "&#111;", $ss);

	$ss = trim($ss);
	return $ss;
}

function rq($ss)
{
	$ss = str_replace("'", "", $ss);
	$ss = str_replace('"', '', $ss);
	$ss = trim($ss);
	return $ss;
}

function quot_del($ss)
{
	$ss = str_replace("\r\n", " ", $ss);
	$ss = str_replace("'", "&rsquo;", $ss);
	$ss = str_replace('"', "&quot;", $ss);
	$ss = trim($ss);
	return $ss;
}

function quot_add($ss)
{
	$ss = str_replace("&rsquo;", "'", $ss);
	$ss = str_replace("&quot;", '"', $ss);
	$ss = trim($ss);
	return $ss;
}

function cbmail($ss)
{
	$ss = htmlspecialchars(stripslashes($ss));
	$ss = str_replace("\\", "", "$ss");
	$ss = str_replace("'", "&rsquo;", "$ss");
	$ss = str_replace('"', "&quot;", "$ss");
	$ss = trim($ss);
	return $ss;
}

function tb($ss)
{
	$ss = str_replace("<br>", "\r\n", $ss);
	$ss = str_replace( "&rsquo;"   , "'", $ss );
	$ss = str_replace( "&#33;"   , "!", $ss );
	$ss = str_replace( "&#036;"   , "$", $ss );
	$ss = str_replace( "&#124;"  , "|", $ss );
	$ss = str_replace( "&amp;"   , "&", $ss );
	$ss = str_replace( "&gt;"    , ">", $ss );
	$ss = str_replace( "&lt;"    , "<", $ss );
	$ss = str_replace( "&quot;"  , '"', $ss );
	# a - &#097;
	# c - &#099;
	# o - &#111;
	$ss = preg_replace( "/textarea/i","text&#097;re&#097;", $ss );
	$ss = preg_replace( "/script/i", "s&#099;ript", $ss );
	$ss = preg_replace( "/alert/i", "&#097;lert", $ss );
	$ss = preg_replace( "/about:/i", "&#097;bout:", $ss );
	$ss = preg_replace( "/onmouseover/i", "&#111;nmouseover", $ss );
	$ss = preg_replace( "/onclick/i", "&#111;nclick", $ss );
	$ss = preg_replace( "/onload/i", "&#111;nload", $ss );
	$ss = preg_replace( "/onsubmit/i", "&#111;nsubmit", $ss );

	return $ss;
}

function search_results($from, $step, $count, $show_count=null, $phrase=null)
{
	global $w;
	$str = ($phrase == null) ? $w[116] : $phrase;
	$m = (($from+$step) > $count) ? $count :
	($from+$step);
	if($show_count != null) $str .=  ' ' .$from.' - '.$m.' ['.$w[117].' '.$count.']';
	return $str;
}

function login($num)
{
	global $w;
	switch ($num)
	{
		case '0':
			return $w[265];
			break;
		case '2':
			return $w[60];
			break;
		default:
			return $w[172];
			break; // By default login by ID
	}
}


function crm($m, $s)
{
	$mc = '';
	for ($i = 0; $i < strlen($m); $i++)
	{
		$mc .= "&#".ord(substr($m, $i)).";";
	}
	$mc = "<a href=\"mailto:".$mc."?subject=".$s."\">".$mc."</a>";
	return $mc;
}


function c_email($email)
{
	if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'.'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

function pregtrim($str)
{
	return preg_replace("/[^\x20-\xFF]/", "", @strval($str));
}
function checkurl($urll)
{
	$urll = trim(pregtrim($urll));
	if (strlen($urll) === 0) return '';
	if (!preg_match("~^(?:(?:https?|ftp|telnet)://(?:[a-z0-9_-]{1,32}(?::[a-z0-9_-]{1,32})?@)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-z0-9.,_@%&"."?+=\~/-]*)?(?:#[^ '\"&<>]*)?$~i", $urll, $ok)) return -1;
	if (!strstr($urll, "://")) $urll = "http://".$urll;
	$urll = preg_replace("~^[a-z]+~ie", "strtolower('\\0')", $urll);
	return $urll;
}


function set_cookies($name, $aff)
{
	if (is_numeric($aff) && !isset($_COOKIE[$name]))
	{
		setcookie($name, $aff, time() + 86400 * C_COOKIE_LIFE);
	}
}


function del_cookies($name)
{
	setcookie($name, "", time() - C_COOKIE_LIFE);
}

function get_cookies($name)
{
	if (isset($_COOKIE[$name]) && is_numeric($_COOKIE[$name]))
	return $_COOKIE[$name];
	else
	return 0;
}

function ChangeURL($url)
{
	echo "
<script language=\"JavaScript\">
<!--
window.location.replace('".$url."');
// -->
</script>
";
}

function set_login($m, $val)
{
	setcookie(C_LOGIN_COOKIE.$m, $val);
	return 1;
}

function del_login($m)
{
	setcookie(C_LOGIN_COOKIE.$m, '', time()-86400);
}

function get_info($m)
{
	if (C_AUTH)
	{
		if (isset($_SESSION[$m]) && ereg('^[A-Za-z0-9-]{1,32}$', $_SESSION[$m]) || ((isset($_SESSION[$m])) && ($m == 'n')) || ((isset($_SESSION[$m])) && (($m == 'enddate') || ($m == 'opt_timediff') || ($m == 'price')))) return cb($_SESSION[$m]);
		else return "";
	}
	else
	{
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		if (isset($_COOKIE[C_LOGIN_COOKIE.$m]) || ((isset($_COOKIE[C_LOGIN_COOKIE.$m])) && ($m == 'n')) || ((isset($_COOKIE[C_LOGIN_COOKIE.$m])) && (($m == 'enddate') || ($m == 'opt_timediff') || ($m == 'price')))) return cb($cr64->decrypt($_COOKIE[C_LOGIN_COOKIE.$m]));
		else return "";
	}
}

function set_info($n,$m)
{
	if (C_AUTH)	$_SESSION[$n] = $m;
	else {
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		set_login($n, $cr64->crypt($m));
	}
}


function IsOnline($id)
{
	Global $_OnlineIDs;
	Return (in_array($id, $_OnlineIDs)) ? True : False;
}

function ShowWelcomeBackMessage()
{
	Global $w;
	if (isset($_COOKIE[C_LOGIN_COOKIE.'WelcomeBack']))
	return template($w[381], array(cb($_COOKIE[C_LOGIN_COOKIE.'WelcomeBack'])));
}

function SearchPhotoResult($acs,$files,$id,$gender,$pwidth=null,$pid=null)
{
	Global $l;
	$photo_wh=array();
	if(C_SEARCH_PHOTO && $acs)
	{
		if($files == '')
		{
			if(C_NO_PHOTO)
			{
				$width= ($pwidth == null) ? '' : ' width="'.$pwidth.'"';
				$pictures = '<a href="'.GenLink('UserProfile',array($l,$id)).'" target="_blank"><img src="'.C_URL.'/templates/'.C_TEMP.'/images/'.str_replace("{G}",$gender,C_NO_PHOTO_FILE).'" border="0" '.$width.'></a>';
			}
			else
			{
				$pictures = '';
			}
		}
		else
		{
			$photol= ($pid === null) ? ShowPic(not_empty($files,$id)) : ShowPic(use_pid($pid,$id));;
			$link = (C_SEARCH_PHOTO_LINK) ? GenLink('UserProfile',array($l,$id)) : $photol.ShowPictureBigger();
			if($pwidth != null)
			{
				$width=' width="'.$pwidth.'"';
			}
			elseif(C_SEARCH_PHOTO_AUTORESIZE)
			{
				$photo_wh=PhotoSize(C_PATH.'/members/uploads/'.not_empty($files,$id));
				$width = ($photo_wh[0] >= $photo_wh[1]) ? ' width="'.C_SEARCH_PHOTO_WIDTH.'"' : ' height="'.C_SEARCH_PHOTO_WIDTH.'"';
			} else $width=' width="'.C_SEARCH_PHOTO_WIDTH.'"';
			$pictures='<a href="'.$link.'" target="_blank"><img src="'.$photol.'" border="'.C_IMG_BRDR.'"'.$width.' hspace="0" vspace="0" align="middle"></a>';
		}
	} else $pictures = '';
	Return $pictures;
}

function mysql2data($sqldata, $b = NULL, $TimeFormat = NULL, $woday = null)
{
	global $wmm;
	if($sqldata == null) return 0;
	$sqldata = str_replace(' ', '-', $sqldata);
	$val = explode('-', $sqldata);
	$data = '';
	/*
	$val[0] - Year
	$val[1] - Month
	$val[2] - Day
	$val[3] - Time
	*/
	if (!isset($val[3])) $val[3] = '';
	if ($b == NULL)
	{
		if(C_DATE2PHRASE)
		{
			$data = Date2Phrase($val[0].'-'.$val[1].'-'.$val[2].' '.$val[3],'');
		}
		if($data == '')
		{
			if (defined("C_DATE_FORMAT") && C_DATE_FORMAT != '')
			{
				$data = ($TimeFormat == NULL) ? C_DATE_FORMAT :  C_LONG_DATE_FORMAT;
				$data = str_replace("{MONTH}", substr($wmm[intval($val[1])], 0, 3), $data);
				$data = str_replace("{FULL_MONTH}", $wmm[intval($val[1])], $data);
				$data = str_replace("{NUMERIC_MONTH}", $val[1], $data);
				$data = ($woday == Null) ? str_replace("{DAY}", $val[2], $data) : str_replace("{DAY}", "", $data);
				$data = str_replace("{YEAR}", $val[0], $data);
				$data = str_replace("{TIME}", $val[3], $data);
			}
			else
			{
				$data = substr($wmm[intval($val[1])], 0, 3) . ' ' . $val[2] . ' ' . $val[0];
			}
		}
	}
	else
	{
		$bd = $val[0].$val[1].$val[2];
		$dat = date("Ymd", time());
		$data = intval(($dat - $bd) / 10000);
	}
	return $data;
}

function CorrectDate($fieldname)
{
	$tmp = strstr($fieldname, '.');
	$fld = ($tmp) ? substr($tmp, 1) : $fieldname;
	$timediff = (get_info('opt_timediff') == "" || !is_numeric(get_info('opt_timediff'))) ? C_TIME_DIFF + 0 : C_TIME_DIFF + get_info('opt_timediff');
	return ($timediff) ? 'DATE_ADD(' . $fieldname . ', INTERVAL '.$timediff.' HOUR) as ' . $fld : $fieldname;
}

function _getip($var)
{
	global $REMOTE_ADDR, $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED, $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM, $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
	global ${$var};
	if (empty(${$var}))
	{
		if (!empty($_SERVER) && isset($_SERVER[$var])) ${$var} = $_SERVER[$var];
		else if (!empty($_ENV) && isset($_ENV[$var]))	${$var} = $_ENV[$var];
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS[$var]))	${$var} = $HTTP_SERVER_VARS[$var];
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS[$var]))	${$var} = $HTTP_ENV_VARS[$var];
		else if (@getenv($var))	${$var} = getenv($var);
	}
}

function ip()
{
	global $REMOTE_ADDR, $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED, $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM, $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
	_getip('REMOTE_ADDR');
	_getip('HTTP_X_FORWARDED_FOR');
	_getip('HTTP_X_FORWARDED');
	_getip('HTTP_FORWARDED_FOR');
	_getip('HTTP_FORWARDED');
	_getip('HTTP_VIA');
	_getip('HTTP_X_COMING_FROM');
	_getip('HTTP_COMING_FROM');
	if (!empty($REMOTE_ADDR))	$direct_ip = $REMOTE_ADDR;
	$proxy_ip = '';
	if (!empty($HTTP_X_FORWARDED_FOR)) $proxy_ip = $HTTP_X_FORWARDED_FOR;
	else if (!empty($HTTP_X_FORWARDED))	$proxy_ip = $HTTP_X_FORWARDED;
	else if (!empty($HTTP_FORWARDED_FOR))	$proxy_ip = $HTTP_FORWARDED_FOR;
	else if (!empty($HTTP_FORWARDED))	$proxy_ip = $HTTP_FORWARDED;
	else if (!empty($HTTP_VIA))	$proxy_ip = $HTTP_VIA;
	else if (!empty($HTTP_X_COMING_FROM))	$proxy_ip = $HTTP_X_COMING_FROM;
	else if (!empty($HTTP_COMING_FROM))	$proxy_ip = $HTTP_COMING_FROM;

	if (empty($proxy_ip))	return $direct_ip;
	else
	{
		$is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}',$proxy_ip,$regs);
		if ($is_ip && (count($regs) > 0))	return $regs[0];
		else return '0.0.0.0';
	}
}

function audio_player($type, $browser)
{
	if ($browser == '0')
	{
		// NN
		switch ($type)
		{
			case '1':
				$out = 'controls="LargeConsole" width="145" height="35"';
				break;
			case '2':
				$out = 'controls="LargeConsole" width="145" height="60"';
				break;
			case '3':
				$out = 'controls="SmallConsole" width="50" height="15"';
				break;
			case '4':
				$out = 'controls="SmallConsole" width="145" height="15"';
				break;
			default:
				$out = 'hidden="true"';
				break;
		}
	}
	else
	{
		// IE or another
		switch ($type)
		{
			case '1':
				$out = 'width="70" height="45"';
				break;
			case '2':
				$out = 'width="285" height="45"';
				break;
			case '3':
				$out = 'width="70" height="25"';
				break;
			case '4':
				$out = 'width="285" height="25"';
				break;
			default:
				$out = 'hidden="true"';
				break;
		}
	}
	return $out;
}


function VideoReplace($posting, $results, $tmpl_player, $index=1)
{
	foreach($results as $item)
	$posting = str_replace($item[0], str_replace('{ID}', $item[$index], $tmpl_player), $posting);
	return $posting;
}
function getYoutube($posting)
{
	$tmpl_player= '<object width="'.C_BB_VIDEO_WIDTH.'" height="'.C_BB_VIDEO_HEIGHT.'">
        <param name="movie" value="http://www.youtube.com/v/{ID}"></param>
        <param name="wmode" value="transparent"></param>
        <embed src="http://www.youtube.com/v/{ID}" type="application/x-shockwave-flash" wmode="transparent" width="'.C_BB_VIDEO_WIDTH.'" height="'.C_BB_VIDEO_HEIGHT.'"></embed>
        </object>';
	preg_match_all('/http:\/\/(www\.|uk\.)?youtube\.com\/watch\?v=([\d\w-_]+)/', $posting, $results, PREG_SET_ORDER);
	if($results) $posting = VideoReplace($posting, $results, $tmpl_player, $index=2);
	return $posting;
}
function getGoogle($posting)
{
	$tmpl_player= '<object type="application/x-shockwave-flash" data="http://video.google.com/googleplayer.swf?docId={ID}" height="'.C_BB_VIDEO_HEIGHT.'" width="'.C_BB_VIDEO_WIDTH.'">
        <param name="movie" value="http://video.google.com/googleplayer.swf?docId={ID}">
        </object>';
	preg_match_all('/http:\/\/video\.google\.com\/(googleplayer\.swf|videoplay)\?doc[Ii]d=([\d-]+)/', $posting, $results, PREG_SET_ORDER);
	if($results) $posting = VideoReplace($posting, $results, $tmpl_player, $index=2);
	return $posting;
}
function getMyspacetv($posting)
{
	$tmpl_player = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'.C_BB_VIDEO_WIDTH.'" height="'.C_BB_VIDEO_HEIGHT.'" id="player" align="middle"><embed src="http://lads.myspace.com/videos/myspacetv_vplayer0005.swf?fuseaction=vids.individual&videoid={ID}" width="'.C_BB_VIDEO_WIDTH.'" height="'.C_BB_VIDEO_HEIGHT.'" flashvars="m={ID}&type="application/x-shockwave-flash"></embed></object>';
	preg_match_all('/http:\/\/(myspacetv|vids\.myspace)\.com\/index\.cfm\?fuseaction=vids.individual&(videoid|VideoID)=([\d\w-_]+)/', $posting, $results, PREG_SET_ORDER);
	if($results)	$posting = VideoReplace($posting, $results, $tmpl_player, $index=3);
	return $posting;
}

function video_bld( $url )
{
	Global $BBvid_count;
	$default = "[video]".$url."[/video]";
	$BBvid_count++;

	if(C_BB_VIDEO_MAX)
	{
		if ($BBvid_count > C_BB_VIDEO_MAX)	return $default;
	}
	if ( preg_match( "/([\.,\?]|&#33;)$/", $url, $match) )
	{
		$url = preg_replace( "/([\.,\?]|&#33;)$/", "", $url );
	}
	if (preg_match( "/\[\/(html|quote|code|sql)/i", $url) )
	{
		return $url;
	}
	$url = str_replace( "&amp;" , "&"   , $url );
	$url = str_replace( "["     , "%5b" , $url );
	$url = str_replace( "]"     , "%5d" , $url );
	$url = preg_replace( "/javascript:/i", "java script&#58; ", $url );
	if ( ! preg_match("#^(http|news|https|ftp|aim)://#", $url ) )		$url = 'http://'.$url;

	$url['show'] = preg_replace( "/&amp;/" , "&" , $url['show'] );
	$url['show'] = preg_replace( "/javascript:/i", "javascript&#58; ", $url['show'] );

	$url = getYoutube($url);
	$url = getGoogle($url);
	$url = getMyspacetv($url);
	return $url;
}


function url_bld( $url=array() )
{
	$skip_it = 0;
	if ( preg_match( "/([\.,\?]|&#33;)$/", $url['html'], $match) )
	{
		$url['end'] .= $match[1];
		$url['html'] = preg_replace( "/([\.,\?]|&#33;)$/", "", $url['html'] );
		$url['show'] = preg_replace( "/([\.,\?]|&#33;)$/", "", $url['show'] );
	}
	if (preg_match( "/\[\/(html|quote|code|sql)/i", $url['html']) )
	{
		return $url['html'];
	}
	$url['html'] = str_replace( "&amp;" , "&"   , $url['html'] );
	$url['html'] = str_replace( "["     , "%5b" , $url['html'] );
	$url['html'] = str_replace( "]"     , "%5d" , $url['html'] );
	$url['html'] = preg_replace( "/javascript:/i", "java script&#58; ", $url['html'] );
	if ( ! preg_match("#^(http|news|https|ftp|aim)://#", $url['html'] ) )
	{
		$url['html'] = 'http://'.$url['html'];
	}
	if ( preg_match( "/^<img src/i", $url['show'] ) )
	{
		$skip_it     = 1;
		$url['show'] = stripslashes($url['show']);
	}

	$url['show'] = preg_replace( "/&amp;/" , "&" , $url['show'] );
	$url['show'] = preg_replace( "/javascript:/i", "javascript&#58; ", $url['show'] );

	if ( (strlen($url['show']) -58 ) < 3 )  $skip_it = 1;
	if ( ! preg_match( "/^(http|ftp|https|news):\/\//i", $url['show'] )) $skip_it = 1;

	$show = $url['show'];

	if ($skip_it != 1)
	{
		$stripped = preg_replace( "#^(http|ftp|https|news)://(\S+)$#i", "\\2", $url['show'] );
		$uri_type = preg_replace( "#^(http|ftp|https|news)://(\S+)$#i", "\\1", $url['show'] );

		$show = $uri_type.'://'.substr( $stripped , 0, 35 ).'...'.substr( $stripped , -15   );
	}

	return "<a href=\"".$url['html']."\" target=\"_blank\">".$show."</a>";
}

function rem_str($start_tok, $end_tok)
{
	$start_tok = str_replace( '&amp;', '&', $start_tok );
	$end_tok   = str_replace( '&amp;', '&', $end_tok   );

	if ($start_tok == '?' and $end_tok == '')	return "";
	else if ($start_tok == '?' and $end_tok == '&')	return '?';
	else if ($start_tok == '&' and $end_tok == '') return "";
	else if ($start_tok == '&' and $end_tok == '&') return "&";
	else return $start_tok.$end_tok;
}

$BBimg_count = 0;
function img_bld($url="")
{
	Global $BBimg_count;
	if (! $url )	return;
	$url = trim($url);
	$default = "[img]".$url."[/img]";
	$BBimg_count++;

	if (C_BB_IMG_MAX)
	{
		if ($BBimg_count > C_BB_IMG_MAX)	return $default;
	}

	$url = urldecode( $url );
	$url = str_replace( "document.cookie", "", $url );

	if ( preg_match( "/[?&;]/", $url) || preg_match( "/java(\s+?)?script(\:|\s)/is", $url ) )	return $default;
	if ( C_BB_IMG_EXT )
	{
		$extension = preg_replace( "#^.*\.(\w+)(\?.*$|$)#", "\\1", $url );
		$extension = strtolower($extension);
		if ( (! $extension) OR ( preg_match( "#/#", $extension ) ) )		return $default;
	}

	$tmp = strtolower(C_BB_IMG_EXT);
	if ( ! preg_match( "/".preg_quote($extension, '/')."(,|$)/", $tmp ))	return $default;
	$url = str_replace( " ", "%20", $url );

	$pref = (C_BB_IMG_NEWWIN) ? "<a href=\"$url\" target=\"picture\" >" : "";
	$postf = (C_BB_IMG_NEWWIN) ? "</a>" : "";

	return $pref."<img src=\"$url\" border=\"0\" style=\"max-width:".intval(C_BB_IMG_WIDTHMAX)."px; height:auto;\" onload=\"if (typeof this.style.maxWidth == 'undefined' && this.width > ".intval(C_BB_IMG_WIDTHMAX).") this.style.width='".intval(C_BB_IMG_WIDTHMAX)."px';\" />".$postf;
}
function AzDGCode($str)
{
	/*_______________________________________________
	/| This function is replace forum chars:
	/| [b][/b]
	/| [i][/i]
	/| [u][/u]
	/| [s][/s]
	/| [quote][/quote]
	/| [url][/url]
	/|_______________________________________________
	*/
	Global $smiles,$BBimg_count,$BBvid_count;
	$str = preg_replace( "#(\?|&amp;|;|&)s=([0-9a-zA-Z]){32}(&amp;|;|&|$)?#e", "rem_str('\\1', '\\3')", $str );
	$str = preg_replace( "#(^|\s)((http|https|news|ftp)://\w+[^\s\[\]]+)#ie"  , "url_bld(array('html' => '\\2', 'show' => '\\2', 'st' => '\\1'))", $str );
	$str = preg_replace("!\[b\](.*?)\[/b\]!si", "<b>\\1</b>", $str);
	$str = preg_replace("!\[i\](.*?)\[/i\]!si", "<i>\\1</i>", $str);
	$str = preg_replace("!\[u\](.*?)\[/u\]!si", "<u>\\1</u>", $str);
	$str = preg_replace("!\[s\](.*?)\[/s\]!si", "<s>\\1</s>", $str);
	$str = preg_replace("!\[quote\](.*?)\[/quote\]!si", '<div class="quote">\\1</div>', $str);
	$str = preg_replace( "#\[url\](\S+?)\[/url\]#ie", "url_bld(array('html' => '\\1', 'show' => '\\1'))", $str );
	$str = preg_replace( "#\[url\s*=\s*(\S+?)\s*\](.*?)\[\/url\]#ie" , "url_bld(array('html' => '\\1', 'show' => '\\2'))", $str );
	$str = preg_replace( "#\[img\](.+?)\[/img\]#ie", "img_bld('\\1')" , $str );
	$str = preg_replace( "#\[video\](\S+?)\[/video\]#ie", "video_bld('\\1')", $str );
	$str = preg_replace( "#\(c\)#i", "&copy;" , $str );
	$str = preg_replace( "#\(tm\)#i", "&#153;" , $str );
	$str = preg_replace( "#\(r\)#i", "&reg;"  , $str );
	if(isset($smiles))
	{
		$b='<img src="'.C_URL.'/templates/'.C_TEMP.'/forum/smiles/';$e='" border=0>';
		foreach ($smiles as $k=>$v) $str=str_replace($k,$b.$v.$e,$str);
	}
	$BBimg_count = $BBvid_count = 0;
	return trim($str);
}

function RemoveAzDGCode($str,$acl=null)
{
	/*_______________________________________________
	/| This function is removing any AzDGCode from string:
	/|_______________________________________________
	*/
	Global $smiles;
	if($acl === null) $acs = null;
	else $acs = explode(',',$acl);
	if(!IsAccess($acs[1]) || $acs === null) $str = preg_replace("!\[b\](.*?)\[/b\]!si", "\\1", $str);
	if(!IsAccess($acs[2]) || $acs === null) $str = preg_replace("!\[i\](.*?)\[/i\]!si", "\\1", $str);
	if(!IsAccess($acs[3]) || $acs === null) $str = preg_replace("!\[u\](.*?)\[/u\]!si", "\\1", $str);
	if(!IsAccess($acs[4]) || $acs === null) $str = preg_replace("!\[s\](.*?)\[/s\]!si", "\\1", $str);
	if(!IsAccess($acs[5]) || $acs === null) $str = preg_replace("!\[quote\](.*?)\[/quote\]!si", '\\1', $str);
	if(!IsAccess($acs[6]) || $acs === null) $str = preg_replace("!\[url\](.*?)\[/url\]!si", '\\1', $str);
	if(!IsAccess($acs[6]) || $acs === null) $str = preg_replace("!\[url\=.+?\](.*?)\[/url\]!si", '\\1', $str);
	if(!IsAccess($acs[7]) || $acs === null) $str = preg_replace("!\[img\](.*?)\[/img\]!si", '\\1', $str);
	if(!IsAccess($acs[8]) || $acs === null) $str = preg_replace("!\[video\](.*?)\[/video\]!si", '\\1', $str);
	if(isset($smiles) && (!IsAccess($acs[0]) || $acs === null)) foreach ($smiles as $kkk=>$vvv) {$str=str_replace($kkk,'',$str);}
	return $str;
}


function sendmail($from, $to, $sub, $mes, $type, $nomail=null)
{
	if(C_DM_MAIL) sprintm('This mail action doesn`t work in the Demo mode.');
	Global $C_CHARSET;
	if($nomail === null || $nomail == '0')
	{
		$chr = (isset($C_CHARSET)) ? cb($C_CHARSET) : cb(C_CHARSET);
		$delim = (@ini_get('sendmail_path')) ? "\n" : "\r\n";
		switch ($type)
		{
			case "html":
				$h = "text/html";
				break;
			case "text":
				$h = "text/plain";
				break;
			default:
				$h = "text/plain";
				break;
		}
		$from = cb($from);$to=cb($to);
		$head = 'MIME-Version: 1.0' . $delim;
		$head .= 'Content-Type: '.$h.'; charset='.$chr . $delim;
		$head .= 'From: '.$from . $delim;
		$head .= 'Reply-To: '.$from . $delim;
		$head .= 'Return-Path: <'.$from.'>' . $delim;
		$head .= 'X-Mailer: '.cb(C_SNAME) . $delim;
		if(C_MAIL_SENDFROM)	@mail($to, $sub, $mes, $head, "-f ". $from);
		else @mail($to, $sub, $mes, $head);
	}
}

function int2ip($i,$hide=null)
{
	$d = array();
	$d[0] = ($hide >= '4') ? '*' : (int)($i/256/256/256);
	$d[1] = ($hide >= '3') ? '*' : (int)(($i-$d[0] * 256 * 256 * 256)/256/256);
	$d[2] = ($hide >= '2') ? '*' : (int)(($i-$d[0] * 256 * 256 * 256-$d[1] * 256 * 256)/256);
	$d[3] = ($hide >= '1') ? '*' : $i-$d[0] * 256 * 256 * 256-$d[1] * 256 * 256-$d[2] * 256;
	return $d[0].'.'.$d[1].'.'.$d[2].'.'.$d[3];
}

function ip2int($ip)
{
	$a = explode(".", $ip);
	return $a[0] * 256 * 256 * 256+$a[1] * 256 * 256+$a[2] * 256+$a[3];
}

function _CheckForEmpty($arr,$check)
{
	switch($check)
	{
		case 0:
			Return True;
			break;
		case 1:default:
			Return (trim($arr) == '') ? False : True;
			break;
		case 2:
			Return ($arr == 0) ? False : True;
			break;
	}
}

function CheckNotices($arr1,$arr2)
{
	$notices=array(0,0,0);
	if(C_NOTICES_TYPES & 1)
	{
		$arrt1=array(1,1,2,1,2,2,2,1,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,1,0,1,1,1);
		$arrt2=array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,2);
		$total = $filled = 0;
		for ($p = 0; $p < count($arr1); $p++)
		{
			$adm = pow(2,$p);
			if((C_NOTICES_FIELDS1 & $adm) && _CheckForEmpty($arr1[$p],$arrt1[$p])) $filled++;
			if((C_NOTICES_FIELDS1 & $adm) && ($arrt1[$p] != 0)) $total++;
		}
		for ($p = 0; $p < count($arr2); $p++)
		{
			$adm = pow(2,$p);
			if((C_NOTICES_FIELDS2 & $adm) && _CheckForEmpty($arr1[$p],$arrt2[$p])) $filled++;
			if((C_NOTICES_FIELDS2 & $adm) && ($arrt2[$p] != 0)) $total++;
		}
		$proc = $filled * 100 / $total;
		$notices[0] = round($proc);
	}
	if(C_NOTICES_TYPES & 2)
	{
		if(trim($arr2[12]) == '') $notices[1] = 1;
	}
	if(C_NOTICES_TYPES & 4)
	{
		$words = count(explode(" ",$arr2[0]));
		if($words < C_NOTICES_ABOUT_LEN) $notices[2] = 1;
	}
	@setcookie(C_LOGIN_COOKIE."Notices", implode(',',$notices), 0, "/");
	return (C_NOTICES_TYPES) ? implode(',',$notices) : '100,0,0';
}

function MakeLogin($id, $username, $fname, $lname, $gender, $req, $points, $hide, $notices=null)
{

	switch(C_SHOW_USER)
	{
		case '1':
			$sesname = (C_ID) ? $id : $username;
			break;
		case '2':
			$sesname = $fname;
			break;
		case '3':
			$sesname = $fname.' '.$lname;
			break;
		case '4':
			$sesname = '[ID#'.$id.'] '.$username;
			break;
		case '5':
			$sesname = '[ID#'.$id.'] '.$fname;
			break;
		case '6':
			$sesname = '[ID#'.$id.'] '.$fname.' '.$lname;
			break;
		default:
			$sesname = '[ID#'.$id.']';
			break;
	}


	if(C_SHOW_EXPIRE_PRIV && $req)
	{
		if(is_numeric($id))
		{
			$tmp=mysql_query("SELECT ".CorrectDate('enddate')." FROM ".C_MYSQL_PMEMBERS." WHERE id = '".$id."'");
			$val=mysql_fetch_array($tmp);
			$enddate=$val['enddate'];
		} else $enddate = '';
	}	else $enddate= '';
	if (C_AUTH)
	{
		// If working on Sessions
		if(C_LOGIN_SECURE)
		{
			@session_destroy();
		}
		@session_start();
		$_SESSION['m'] = $id;
		$_SESSION['o'] = md5(agent());
		$_SESSION['s'] = md5(ip());
		$_SESSION['g'] = $gender;
		$_SESSION['n'] = $sesname;
		$_SESSION['pnt'] = $points;
		$_SESSION['hd'] = $hide;
		#$_SESSION['sess_mess'] =
		$_SESSION['d'] = $req;
		if (($req != '0'))
		{
			$_SESSION['u'] = $req;
			unset($u);
		}
		if(CheckAccess(C_PRIV_IPS))
		{
			$_SESSION['u'] = C_IPS_ACCESS;
			$_SESSION['d'] = C_IPS_ACCESS;
			unset($u);
		}
		$_SESSION['username'] = username($id, $username, $fname, $lname);
		$_SESSION['enddate'] = $enddate;
	}
	else
	{
		// If working on Cookies
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		set_login('m', $cr64->crypt($id));
		set_login('o', $cr64->crypt(md5(agent())));
		set_login('s', $cr64->crypt(md5(ip())));
		set_login('g', $cr64->crypt($gender));
		set_login('n', $cr64->crypt($sesname));
		set_login('pnt', $cr64->crypt($points));
		set_login('hd', $cr64->crypt($hide));
		set_login('d', $cr64->crypt($req));
		if ($req != '0')
		{
			set_login('u', $cr64->crypt($req));
			unset($u);
		}
		if(CheckAccess(C_PRIV_IPS))
		{
			set_login('u', $cr64->crypt(C_IPS_ACCESS));
			set_login('d', $cr64->crypt($req));
			unset($u);
		}
		set_login('username', $cr64->crypt(username($id, $username, $fname, $lname)));
		set_login('enddate', $cr64->crypt($enddate));
	}
	# Getting Options
	$tmp2=mysql_query("SELECT * FROM ".C_MYSQL_OPTIONS." WHERE id = ".$id." LIMIT 1");
	$count2=mysql_num_rows($tmp2);
	if($count2 != '0') {
		while($j=mysql_fetch_array($tmp2)) {
			if (C_AUTH)
			{
				$_SESSION['opt_timediff'] = $j['timediff'];
				$_SESSION['imsound'] = $j['imsound'];
			}
			else
			{
				// If working on Cookies
				set_login('opt_timediff', $cr64->crypt($j['timediff']));
				set_login('imsound', $cr64->crypt($j['imsound']));
			}
		}
	}
	unset($s, $m, $g, $o, $n, $u, $d, $username);

	// Detecting access
	mysql_query("UPDATE ".C_MYSQL_MEMBERS_MAIN." SET editdate = NOW() WHERE id='".$id."'") or die(mysql_error());
	if ($req >= C_BACK_WELCOME)
	{
		@setcookie(C_LOGIN_COOKIE."WelcomeBack", $sesname, time() + 86400 * C_COOKIE_LIFE);
	}

}

function agent()
{
	$agent = (getenv('HTTP_USER_AGENT')) ? getenv('HTTP_USER_AGENT') :
	'Unknown';
	return $agent;
}

function MakeExit()
{
	if(MyID() && C_LOGOUT) @mysql_query("DELETE FROM ".C_MYSQL_ONLINE_USERS." WHERE user = ".MyID());

	if (C_AUTH)
	{
		// If working on Sessions

		@session_destroy();
	}
	else
	{
		// If working on Cookies
		del_login('m');
		del_login('o');
		del_login('s');
		del_login('g');
		del_login('n');
		del_login('u');
		del_login('d');
		del_login('req');
		del_login('username');
	}
	unset($s, $m, $g, $o, $n, $u, $d, $username);
}

function MakeExitAdmin()
{
	if (C_AUTH)
	{
		// If working on Sessions
		@session_destroy();
	}
	else
	{
		// If working on Cookies
		del_login('adminlogin');
		del_login('adminpass');
		del_login('adminip');
	}
}

function MakeExitModer()
{
	if (C_AUTH)
	{
		// If working on Sessions
		@session_destroy();
	}
	else
	{
		// If working on Cookies
		del_login('moderlogin');
		del_login('moderpass');
		del_login('moderip');
	}
}


function GetFileName($Path)
{
	Return basename($Path);
}

function GetDirName($Path)
{
	Return dirname($Path);
}

function GoToURL($URL,$timeout=null,$mess=null)
{
	if($timeout === null)
	{
		echo('
	<script language="JavaScript">
  <!--
    window.location.replace("'.$URL.'");
  // -->
  </script>
	');
	}
	else
	{
		echo('
	<script language="JavaScript">
  <!--
		function reload_page()
		{
    	window.location.replace("'.$URL.'");
		}
		setTimeout("reload_page()",'.$timeout.')		
  // -->
  </script>
	');
	}
	if($mess !== null) printm($mess,2);
	die();
}

function ChangeTemplate($value,$url=null)
{
	Global $l;
	if (file_exists(C_PATH.'/templates/'.cb($value).'/config.php'))
	{
		setcookie('TemplateName', cb($value), time() + 86400 * C_COOKIE_LIFE);
		if($url != '-1') ($url == null) ? GoToURL(C_URL.'/index.php?l='.$l) : GoToURL($url);
		else define('C_TEMP',cb($value));
	}
}

function CheckUploadDirectories($id,$admin=null)
{
	if($admin != null) $id = $id + 1000;
	$dir1=intval($id / 10000);
	$dir2=$dir1.'/'.intval(($id % 10000) / 100);
	if(!ini_get('safe_mode'))
	{
		if(!file_exists(C_PATH.'/members/uploads/'.$dir1))
		{
			@umask(0);
			@mkdir (C_PATH."/members/uploads/".$dir1, 0777);
		}
		if(!file_exists(C_PATH.'/members/uploads/'.$dir2))
		{
			@umask(0);
			@mkdir (C_PATH."/members/uploads/".$dir2, 0777);
		}
	}
	elseif($admin != null)
	{
		$str = '';
		if(!file_exists(C_PATH.'/members/uploads/'.$dir1) || !file_exists(C_PATH.'/members/uploads/'.$dir2) || !@is_writable(C_PATH.'/members/uploads/'.$dir1) || !@is_writable(C_PATH.'/members/uploads/'.$dir2))
		{
			$str .= '<u>AzDGDatingMedium Notify Message</u><br><br>PHP is working in safe mode...<br><br>I can`t create directories correctly...<br><br>Please check and create (if it required) these directories with chmod 777:<br>'.C_PATH.'/members/uploads/'.$dir1.'<br>';
			for($x=0;$x<100;$x++)
			{
				$str .= C_PATH.'/members/uploads/'.$dir1.'/'.$x.'<br>';
			}
			$str .= '<br>Attention: All these directories should be writeble (chmod 777)';
		}
		if($str != '') mes($str,2);
	}

}


function SQLCount($Table, $WhereSQL)
{
	$tmp = mysql_query("SELECT count(*) as total FROM ".$Table." WHERE ".$WhereSQL) or die(mysql_error());
	$trows = mysql_fetch_array($tmp);
	return $trows['total'];
}

function SQLSelect($Table, $GetData=array(), $WhereSQL)
{
	$tmp = mysql_query("SELECT ".implode(',',$GetData)." FROM ".$Table." WHERE ".$WhereSQL." limit 1") or die(mysql_error());
	if(mysql_num_rows($tmp))
	{
		$ret_arr = array();
		while($i = mysql_fetch_array($tmp))
		{
			$p=0;while(isset($GetData[$p]))
			{
				$sqltmp = $GetData[$p];
				$ret_arr[$sqltmp] = $i[$sqltmp];
				$p++;}
				return $ret_arr;
		}
	} else return False;
}

function ShowVote($id=null)
{
	if(IsAccess(C_VOTE))
	{
		global $w;
		$sql = ($id == null) ? "SELECT * FROM ".C_MYSQL_VOTES." where actual = '1'" : "SELECT * FROM ".C_MYSQL_VOTES." where id = '".$id."'";
		$tmp = mysql_query($sql) or die(mysql_error());
		while($i = mysql_fetch_array($tmp))
		{
			$resultip = mysql_query("SELECT count(*) as total FROM ".C_MYSQL_VOTE_IPS." WHERE vid=".$i['id']." AND ip='".ip2int(ip())."'") or die(mysql_error());
			$trows = mysql_fetch_array($resultip);
			$count = $trows['total'];

			define('VOTE',$w[430]);
			if(C_VIV || $count == 0)
			{
				$tmp2 = mysql_query("SELECT * FROM ".C_MYSQL_VOTE_QUESTIONS." WHERE id = '".$i['id']."' AND lang = '".cb(LANGUAGE)."' limit 1") or die(mysql_error());
				$count = mysql_num_rows($tmp2);
				if($count != 0)
				{
					$answers=array();
					while($j = mysql_fetch_array($tmp2))
					{
						define('QUESTION',$j['question']);
						$STYPE = ($i['stype'] == '1') ? 'radio' : 'checkbox';
						define('STYPE',$STYPE);
						define('VOTE_ID',$i['id']);
						define('VIEW_RESULTS',$w['431']);
						for($x=1;$x<=$i['num'];$x++)
						{
							$answers[]=$j['qtext'.$x];
						}
					}
					$p=0;
					include_once(C_PATH.'/templates/'.C_TEMP.'/vote/vote.php');
				}
			}
			else
			{
				$total=0;
				for ($c=1;$c<=$i['num'];$c++)
				{
					$mas[$c]=$i['q'.$c];
					$total+=$i['q'.$c];
				}
				$result2 = mysql_query("SELECT * FROM ".C_MYSQL_VOTE_QUESTIONS." WHERE id = '".$i['id']."' AND lang = '".cb(LANGUAGE)."' limit 1") or die(mysql_error());
				while ($j = mysql_fetch_array($result2))
				{
					$max=max($mas);
					// If no votes
					if ($max == "0")
					{
						sprintm($w[436]);
					}
					define('QUESTION', $j['question']);
					$result=$graphic=$votes=$proc=$text=array();
					for ($k=1;$k<=$i['num'];$k++)
					{
						$g[$k] = $i['q'.$k] * C_GRAFLEN / $max;
						$p[$k] = $i['q'.$k] * 100 / $total;
						$g[$k] = sprintf ("%01.0f", $g[$k]);
						$p[$k] = sprintf ("%01.2f", $p[$k]);
						$rslt = $j['qtext'.$k]." [".$i['q'.$k]." users, ".$p[$k]."%]";
						$text[]=$j['qtext'.$k];
						$votes[]=$i['q'.$k];
						$proc[]=$p[$k];
						$result[] = $rslt;
						$graphic[] = $g[$k];
					}
					define('TOTAL', template($w[437],array($total)));
					define('VOTES',$w[438]);
				}
				$p=0;
				include_once(C_PATH.'/templates/'.C_TEMP.'/vote/view.php');

			}
		}
	}
}


function ext($file)
{
	if(function_exists("exif_imagetype")) // More faster extension deceting function
	{
		$arr = @exif_imagetype($file);
	}
	else
	{
		$val = @getimagesize($file);
		$arr = $val[2];
	}
	switch($arr)
	{
		case '1': return '.gif';break;
		case '2':default: return '.jpg';break;
		case '3': return '.png';break;
		case '4': return '.swf';break;
		case '5': return '.psd';break;
		case '6': return '.bmp';break;
		case '7': return '.tiff';break;
		case '8': return '.tiff';break;
		case '9': return '.jpc';break;
		case '10': return '.jp2';break;
		case '11': return '.jpx';break;
	}
}

function CheckAllowMessaging($id,$req,$OnlyCheck)
{
	if(C_ENABLE_MSCTRL)
	{
		Global $w, $wps, $wpu;
		if(!is_numeric($id) || !is_numeric($req)) sprintm($w[1].'14');

		$tmp = mysql_query("SELECT *, mday - NOW() as timediff FROM ".C_MYSQL_OPTIONS." WHERE id = '".$id."'");
		$total = mysql_num_rows($tmp);
		if($total == '0')
		{
			if($wps[$req] == '0') sprintm($w[269]);
			if(!$OnlyCheck)	mysql_query("INSERT INTO ".C_MYSQL_OPTIONS." VALUES ('".$id."', '0','" . --$wps[$req] . "', DATE_ADD(NOW(), INTERVAL 24 HOUR),'0',NOW(''),'".intval(C_IMSOUND_DEFAULT)."')") or die(mysql_error());
		}
		else
		{
			while ($i = mysql_fetch_array($tmp))
			{
				if($i['freem'] > '0')
				{
					if(!$OnlyCheck)	mysql_query("UPDATE ".C_MYSQL_OPTIONS." SET freem = freem - 1 , mnum = mnum - 1 WHERE id = '".$id."'") or die(mysql_error());
				}
				elseif($i['mnum'] > '0')
				{
					if(!$OnlyCheck)	mysql_query("UPDATE ".C_MYSQL_OPTIONS." SET mnum = mnum - 1 WHERE id = '".$id."'") or die(mysql_error());
				}
				elseif($wps[$req] == '0')
				{
					sprintm($w[269]);
				}
				elseif($i['timediff'] < '0')
				{
					if(!$OnlyCheck)	mysql_query("UPDATE ".C_MYSQL_OPTIONS." SET mnum = '" . --$wps[$req] . "', mday = DATE_ADD(NOW(), INTERVAL 24 HOUR) WHERE id = '".$id."'") or die(mysql_error());
				}
				else
				{
					sprintm(template($w[385],array($wpu[$req],$wps[$req])));
				}
			}
		}
	}
}

function IsAllowContact($id,$small=null)
{
	Global $w;
	if(!IsAccess(C_CONTACT_SAME_GENDER) && C_CONTACT_SAME_GENDER > 0 && MyID() > 0 && is_numeric($id) && ($id > 0))
	{
		$tmp = mysql_query("SELECT count(*) as total FROM ".C_MYSQL_MEMBERS_MAIN." WHERE id = '".$id."' and gender = '".cb(get_info('g'))."'");
		$rows=mysql_fetch_array($tmp);
		$count=$rows['total'];
		$Bool = ($small == null) ? False : True;
		if($count) IsSecure(C_CONTACT_SAME_GENDER,$Bool,$w[747]);
	}
}

function is_badwords($mes,$badwords=null)
{
	$rem=array('',' ');
	if($badwords == null)	$arr = array_diff (explode(',', C_BADWORDS), $rem);
	else $arr = array_diff (explode(',', $badwords), $rem);
	$tmp = array();
	$err = $p = 0;
	foreach ($arr as $k => $v)
	$tmp[] = str_replace("\\*", ".*", preg_quote($v));
	$s = "!^(".implode("|", $tmp).")$!i";
	$message_array = explode(' ', $mes);
	while (isset($message_array[$p]))
	{
		if (preg_match($s, $message_array[$p])) $err++;
		$p++;
	}
	return ($err != '0') ? True : False;
}

function replace_badwords($mes,$badwords=null)
{
	$rem=array('',' ');
	if($badwords == null)	$arr = array_diff (explode(',', C_BADWORDS), $rem);
	else $arr = array_diff (explode(',', $badwords), $rem);
	$tmp = array();
	$err = $p = 0;
	foreach ($arr as $k => $v)
	$tmp[] = str_replace("\\*", ".*", preg_quote($v));
	$s = "!^(".implode("|", $tmp).")$!i";
	$message_array = explode(' ', $mes);
	while (isset($message_array[$p]))
	{
		if (preg_match($s, $message_array[$p]))
		{
			$err++;
			$message_array[$p] = C_BADWORDS_REPW;
		}
		$p++;
	}
	return implode(' ', $message_array);
}

function GetServerConstant($var)
{
	global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
	$RetVal = '';
	if (!empty($_SERVER) && isset($_SERVER[$var]))	$RetVal = $_SERVER[$var];
	else if (!empty($_ENV) && isset($_ENV[$var]))	$RetVal = $_ENV[$var];
	else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS[$var]))	$RetVal = $HTTP_SERVER_VARS[$var];
	else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS[$var]))	$RetVal = $HTTP_ENV_VARS[$var];
	else if (@getenv($var))	$RetVal = getenv($var);
	Return (empty($RetVal)) ? False : cb($RetVal);
}

function RemoveUser($id,$sendmail=null)
{
	if(!is_array($id)) $arr=array($id);
	else $arr=$id;

	$p=0;while(isset($arr[$p])) {
		if(!is_numeric($arr[$p])) sprintm('Security Error - ID should be numeric');
		$p++;}

		$id=implode(',',$arr);

		$tmp=mysql_query("SELECT t1.id, t1.files, t1.status, t2.audio, t3.email, t2.mylang FROM ".C_MYSQL_MEMBERS_MAIN." as t1, ".C_MYSQL_MEMBERS_EXT." as t2, ".C_MYSQL_MEMBERS_SEC." as t3 WHERE t1.id IN (".$id.") and t1.id = t2.id and t1.id = t3.id") or die(mysql_error());$recid=array();
		while ($i = mysql_fetch_array($tmp))
		{
			if ($i['files'] != "")
			{
				$arr=explode(',',$i['files']);
				$p=0;while(isset($arr[$p]))
				{
					@unlink (C_PATH.'/members/uploads/'.PicPath($arr[$p],$i['id']));
					@unlink (C_PATH.'/members/uploads/'.TPicPath($arr[$p],$i['id']));
					$p++;
				}
				@unlink (C_PATH.'/members/uploads/'.id2pathAudio($i['id']).'.'.$i['audio']);
			}
			# If user is new, removing affiliate inviting event.
			if($i['status'] <= '1')	$recid[]=$id;

			# Sending email if allow
			if($sendmail != null)
			{
				if(!empty($i['mylang']) && file_exists(C_PATH.'/languages/'.$i['mylang'].'/'.$i['mylang'].'a.php'))
				{
					@include(C_PATH.'/languages/'.$i['mylang'].'/'.$i['mylang'].'.php');
				}
				else
				{
					if(defined("C_USERLANG") && file_exists(C_PATH.'/languages/'.C_USERLANG.'/'.C_USERLANG.'.php')) @include(C_PATH.'/languages/'.C_USERLANG.'/'.C_USERLANG.'.php');
					else @include(C_PATH.'/languages/default/default.php');
				}
				$subject = template($w[559],array(C_SNAME));
				$message = template($w[560],array(C_SNAME,C_URL));

				sendmail(C_ADMINM,$i['email'],$subject,$message,'text');
			}
			@include(C_PATH.'/languages/'.LANGUAGE.'/'.LANGUAGE.'.php');

		}
		$tmp=mysql_query("SELECT photonum FROM ".C_MYSQL_NEW_PHOTOS." WHERE uid IN (".$id.")") or die(mysql_error());
		while ($i = mysql_fetch_array($tmp))
		{
			if ($i['photonum'] != "")
			{
				$arr=explode(',',$i['photonum']);
				$p=0;while(isset($arr[$p]))
				{
					@unlink (C_PATH.'/members/uploads/'.PicPath($arr[$p],$i['id']));
					@unlink (C_PATH.'/members/uploads/'.TPicPath($arr[$p],$i['id']));
					$p++;
				}
			}
		}
		@mysql_query("DELETE FROM ".C_MYSQL_MEMBERS_MAIN." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_MEMBERS_EXT." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_MEMBERS_SEC." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_MEMBERS_RESTRICTS." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_TEMP." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_HITS." WHERE id IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_OPTIONS." WHERE id IN (".$id.")");
		@mysql_query("UPDATE ".C_MYSQL_ONLINE_USERS." SET upage = 'REMOVE' WHERE user IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_NEW_PHOTOS." WHERE uid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_SEARCH." WHERE uid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_MESSAGES." WHERE fromid IN (".$id.") or toid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_COMMENTS." WHERE fromid IN (".$id.") or toid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_BEDROOM." WHERE user IN (".$id.") or myid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_BANLIST." WHERE user IN (".$id.") or myid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_ADDRESSBOOK." WHERE user IN (".$id.") or myid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_BAD_PROFILES." WHERE user IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_PROFILEVIEW." WHERE myid IN (".$id.") or visid IN (".$id.")");
		@mysql_query("DELETE FROM ".C_MYSQL_TESTIMONIALS." WHERE uid IN (".$id.")");
}



function ChangeStatus($id,$status=null)
{
	if(!is_array($id)) $arr=array($id);
	else $arr=$id;
	if($status == null) $status = 7;
	$p=0;while(isset($arr[$p]))
	{
		if(!is_numeric($arr[$p])) sprintm('Security Error - ID should be numeric');
		$p++;
	}

	$id=implode(',',$arr);
	@mysql_query("UPDATE ".C_MYSQL_MEMBERS_MAIN." SET status='".$status."' WHERE id IN (".$id.")");
	@mysql_query("UPDATE ".C_MYSQL_MEMBERS_EXT." SET status='".$status."' WHERE id IN (".$id.")");
	@mysql_query("UPDATE ".C_MYSQL_MEMBERS_SEC." SET status='".$status."' WHERE id IN (".$id.")");
	@mysql_query("UPDATE ".C_MYSQL_ADDRESSBOOK." SET status='".$status."' WHERE myid IN (".$id.")");
}


function security($var, $error)
{
	unset($s,$m,$o,$g,$n,$u);
	global $stime, $w, $l;
	if (
	($var) && ((!is_md5(get_info('s'))) || (!is_numeric(get_info('m'))) || (!is_md5(get_info('o'))) || (!is_numeric(get_info('m'))) || (((C_SECURITY == '2') || (C_SECURITY == '3')) && (get_info('o') != md5(agent()))) || (((C_SECURITY == '1') || (C_SECURITY == '3')) && get_info('s') != md5(ip()))))
	{
		if (C_AUTH)
		{
			// If working on Sessions
			session_destroy();
		}
		else
		{
			del_login('m');
			del_login('o');
			del_login('s');
			del_login('g');
			del_login('n');
			del_login('u');
		}
		include_once C_PATH.'/header.php';
		printm($error);
	}
}

function IsForumModerator($ModIds)
{
	$MyID = abs(get_info('m'));
	$arr = explode(',', $ModIds);
	Return (in_array($MyID, $arr) && ($MyID > 0)) ? True : False;
}

function ssecurity($var, $error)
{
	unset($s);
	unset($m);
	global $stime, $w, $l;
	if (($var) && ((!is_md5(get_info('s'))) || (!is_numeric(get_info('m'))) || (!is_md5(get_info('o'))) || (!is_numeric(get_info('m'))) || (((C_SECURITY == '2') || (C_SECURITY == '3')) && (get_info('o') != md5(agent()))) || (((C_SECURITY == '1') || (C_SECURITY == '3')) && get_info('s') != md5(ip()))))
	{
		if (C_AUTH)
		{
			// If working on Sessions
			session_destroy();
		}
		else
		{
			del_login('m');
			del_login('o');
			del_login('s');
			del_login('g');
			del_login('n');
			del_login('u');
		}
		include_once C_PATH.'/sheader.php';
		sprintm($error);
	}
}


function pop_out($id)
{
	mysql_query("DELETE FROM ".C_MYSQL_HITS." WHERE votedate < DATE_SUB(NOW(), INTERVAL ".C_HITS_TIME." HOUR");
	$tmp = (C_POPULARITY == 2) ? mysql_query("SELECT ROUND(hits/hits_count,".C_RATE_DIGITS.") as hits FROM ".C_MYSQL_MEMBERS_MAIN." WHERE id='".$id."'") : mysql_query("SELECT ROUND(hits/(TO_DAYS(Now()) - TO_DAYS(IF(regdate > '".C_LAST_CLEAR_DATE."', regdate, '".C_LAST_CLEAR_DATE."')) + 1),".C_RATE_DIGITS.") as hits FROM ".C_MYSQL_MEMBERS_MAIN." WHERE id='".$id."'") or die(mysql_error());
	$rows = mysql_fetch_array($tmp);
	return empty($rows['hits']) ? '0' : $rows['hits'];
}

function username($id, $username, $fname, $lname)
{
	$ss = C_USERNAME;
	$ss = str_replace("ID", $id, $ss);
	$ss = str_replace("USERNAME", $username, $ss);
	$ss = str_replace("FNAME", $fname, $ss);
	$ss = str_replace("LNAME", $lname, $ss);
	$ss = trim($ss);
	return $ss;
}

function template($text, $vars)
{
	$msg = preg_replace("/{(\w+)}/e", "\$vars['\\1']", $text);
	return $msg;
}

function pop_in($id, $hits)
{
	if ($hits != 0)
	{
		$tmp = mysql_query("SELECT count(id) as total FROM ".C_MYSQL_HITS." WHERE id='".$id."' AND ip='".ip2int(ip())."' limit 1");
		$rows = mysql_fetch_array($tmp);
		$count = $rows['total'];
		if ($count == '0')
		{
			// If new real hit
			mysql_query("INSERT INTO ".C_MYSQL_HITS." VALUES('".$id."','".ip2int(ip())."',NOW(''))");
			(C_POPULARITY == 2) ? mysql_query("UPDATE ".C_MYSQL_MEMBERS_MAIN." SET hits = hits + ".$hits.", hits_count = hits_count + 1 WHERE id='".$id."' AND status >= '7' AND rate = '1'") : mysql_query("UPDATE ".C_MYSQL_MEMBERS_MAIN." SET hits = hits + ".$hits." WHERE id='".$id."' AND status >= '7' AND rate = '1'");
		} else return False;
		Return True;
	}
}

function IsFirstMessage($id)
{
	if(C_SEND_ONFIRST)
	{
		If (!IsOnline($id))
		{
			$count = UnreadedMessages($id);
			if($count == 0)
			{
				$tmp = mysql_query("SELECT t1.id, t1.username, t1.fname, t1.lname, t2.email, t3.mylang FROM ".C_MYSQL_MEMBERS_MAIN." as t1, ".C_MYSQL_MEMBERS_SEC." as t2, ".C_MYSQL_MEMBERS_EXT." as t3 WHERE t1.id='".$id."' AND t2.id = t1.id AND t3.id = t1.id") or die(mysql_error());
				while ($i = mysql_fetch_array($tmp))
				{
					$lang = (file_exists(C_PATH.'/languages/'.$i['mylang'].'/'.$i['mylang'].'a.php')) ? $i['mylang'] : C_ADMINLANG;
					@include C_PATH.'/languages/'.$lang.'/'.$lang.'a.php';
					if(C_ID == 0) $login=$i['username'];
					elseif(C_ID == 1) $login=$i['id'];
					elseif(C_ID == 2) $login=$i['email'];
					$tm=array($i['fname'],$i['lname'],'1', C_SNAME,C_URL.'/login.php',$login);
					sendmail(C_FROMM,$i['email'],template($x[19],array(C_SNAME)), template($x[95],$tm),'text',$i['nomail']);
				}
			}
		}
	}
}

function UnreadedMessages($id)
{
	$trows = mysql_fetch_array(mysql_query("SELECT SUM(new_mes) as total FROM ".C_MYSQL_ADDRESSBOOK." WHERE user='".$id."' AND lastdate != '0' AND status > '6'"));
	$count = $trows['total'];
	Return $count;
}

function mes($tmp)
{
	echo C_ETOP.$tmp.C_SBOT;
}

function smes($tmp)
{
	echo $tmp;
}

function code_gen()
{
	$passgen = preg_replace("/(.)/e", "chr(rand(ord('a'),ord('z')))", str_repeat('.', 10));
	$passgen = md5($passgen);
	return $passgen;
}

function gennum($char1,$char2,$count=null)
{
	if($count == null) $count = 1;
	$gen = preg_replace("/(.)/e", "chr(rand(ord('".$char1."'),ord('".$char2."')))", str_repeat('.', $count));
	return $gen;
}

if (!function_exists('is_md5'))
{
	function is_md5($var)
	{
		if (ereg('^[A-Za-z0-9]{32}$', $var))	return 1;
		else	return 0;
	}
}

function filename()
{
	return cb($_SERVER['PHP_SELF']);
}

function s()
{
	return $SID = C_SESS ? SID : '';
}


function MySQLError()
{
	if(C_DEBUG) die('<br><br><table cellspacing="0" cellpadding="10" border="1" bgcolor="#c0c0c0" align="center" width="400"><tr><td><br><b>Error in '.basename(__FILE__).' on the line '.__LINE__.':<br><br>'.mysql_error().'</td></tr></table>');
}

function LoginFromEmail($mail)
{
	$tmp = explode('@', $mail);
	return substr($tmp[0], 0, C_CHAT_MAIL_CHARS);
}

function DisableRightClick()
{
	global $w;
	if(IsAccess(C_ALLOW_RIGHT_CLICK))
	{
		if(IsAccess(C_ALLOW_RIGHT_CLICK_MESSAGE))
		{
			$mes = 'var message="'.$w[508].'";';
			$alert = 'alert(message);';
		}
		else $alert = $mes = '';
		?>
<script language=JavaScript>
<!--
<?=$mes?>
function clickIE4(){if (event.button==2){<?=$alert?>return false;}}
function clickNS4(e){if (document.layers||document.getElementById&&!document.all){if (e.which==2||e.which==3){<?=$alert?>return false;}}}
if (document.layers){document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS4;}else if (document.all&&!document.getElementById){document.onmousedown=clickIE4;}
document.oncontextmenu=new Function("<?=$alert?>return false")
// --> 
</script>

	<?php
	}
}

function ShowActions($exclude=null) {
	Global $w;
	if($exclude == null) $exclude=-1;
	$actarr=array('',$w[554],$w[398],$w[170],$w[293],$w[217],$w[219],$w[319],$w[218]);
	$acs=array(1,1,IsAccess(C_SEND_KISS),1,0,IsAccess(C_MAILSH),IsAccess(C_BEDSH),IsAccess(C_BANSH),IsAccess(C_BADSH));
	$str='';
	$p=1;while(isset($actarr[$p])) {
		$str .= ($acs[$p] && $exclude != $p) ? '<option value='.$p.'>'.$actarr[$p] : '';
		$p++;}
		Return $str;
}


function IsShowSearchFields($keyword,$acs,$phrase_const,$value,$type=null,$value2=null)
{
	Global $w,$access;
	define($keyword,$w[$phrase_const]);
	if(!isset($access[$acs])) $access[$acs] = '-1';
	if(IsAccess($access[$acs]))
	{
		define($keyword.'_SHOW',True);
		if($type == null)
		{
			define($keyword.'_VALUE',$value);
		}
		else if($type == 'from_to')
		{
			define($keyword.'_FROM',$value);
			define($keyword.'_TO',$value2);
		}
	}
	else
	{
		define($keyword.'_SHOW',False);
		if($type == null)
		{
			define($keyword.'_VALUE',False);
		}
		else if($type == 'from_to')
		{
			define($keyword.'_FROM',False);
			define($keyword.'_TO',False);
		}
	}
}
function sv($p,$also=null)
{
	if($also != null) Return ($p == $also) ? ' selected':'';
	else Return ($p == 0) ? ' selected':'';
}

function IsSearch($var,$fld_acs){	return (isset($var) && IsAccess($fld_acs)) ? True : False;}

function ReturnSearchValue($val,$type=null,$fld_acs=null,$arr=null,$check=null)
{
	Global $access,$$val;
	if($type == 'num')
	{
		if($arr == null)
		{
			if($check != null)
			{
				Return (isset($$val) && is_numeric($$val) && IsAccess($access[$fld_acs])) ? True : False;
			}
			else
			{
				Return (isset($$val) && is_numeric($$val) && IsAccess($access[$fld_acs])) ? cb($$val) : 0;
			}
		}
		else
		{
			if($check != null)
			{
				Return (isset($$val) && is_numeric($$val) && IsAccess($access[$fld_acs]) && ($$val >= 0) && ($$val < sizeof($arr))) ? True : False;
			}
			else
			{
				Return (isset($$val) && is_numeric($$val) && IsAccess($access[$fld_acs]) && ($$val >= 0) && ($$val < sizeof($arr))) ? cb($$val) : 0;
			}
		}
	}
	else if($type == 'text')// Text value
	{
		Return (isset($$val) && IsAccess($access[$fld_acs])) ? cb($$val) : '';
	}
	else if($type == 'multinum')
	{
		if(isset(${$val}) && IsAccess($access[$fld_acs]))
		{
			$tmp = implode(',',${$val});
			if(!preg_match('/^[0-9,]+$/', $tmp)) $tmp = '';
			Return cb($tmp);
		} else Return '';
	}
}

function AddUserToAddressBook($id,$fromid=null,$nonew=null)
{
	if(MyID() > 0 || ($fromid !== null && MyID() >= 0))
	{
		$trows = mysql_fetch_array(mysql_query("SELECT count(*) as total FROM ".C_MYSQL_ADDRESSBOOK." WHERE myid = '".MyID()."' AND user = '".$id."'"));
		$count = $trows['total'];
		if($count)
		{
			$sql = ($nonew === null) ? "UPDATE ".C_MYSQL_ADDRESSBOOK." SET new_mes = IF(myid='".MyID()."',new_mes+1,new_mes), total_mes = total_mes + 1, lastdate = NOW() WHERE (myid = '".MyID()."' AND user = '".$id."') OR (user = '".MyID()."' AND myid = '".$id."')" : "UPDATE ".C_MYSQL_ADDRESSBOOK." SET total_mes = total_mes + 1 WHERE (myid = '".MyID()."' AND user = '".$id."') OR (user = '".MyID()."' AND myid = '".$id."')";
			mysql_query($sql) or die(mysql_error());
		} else {
			$sql = ($nonew === null) ? "INSERT INTO ".C_MYSQL_ADDRESSBOOK." VALUES ('".MyID()."','".$id."','1','1',NOW(''),'7'), ('".$id."','".MyID()."','0','1',NOW(''),'7')" : "INSERT INTO ".C_MYSQL_ADDRESSBOOK." VALUES ('".MyID()."','".$id."','0','1',NOW(''),'7'), ('".$id."','".MyID()."','0','1',NOW(''),'7')";
			mysql_query($sql);
		}
	}
}

function arr2val($arr,$var)
{
	Return preg_replace("/(\d{1,4})/e", "' '.\$arr['$1']", $var);
}


function IsCache($Type,$Num)
{
	Return (($Type == C_CACHE_TYPE) && ($Num & C_CACHE_WHAT)) ? True : False;
}

function AddToViewProfile($id,$myid)
{
	if(is_numeric($id) && is_numeric($myid) && $id > 0 && $id != $myid && $myid != 0 && !(IsAccess(C_HIDE_WHOSEEN) && get_info('hd') == '1'))
	mysql_query("REPLACE INTO ".C_MYSQL_PROFILEVIEW." VALUES ('".$id."','".$myid."',NOW(''))") or die(mysql_error());
}


function IsAdmin($moder=Null)
{
	if($moder==Null)
	{
		if ((((C_SECURITY == '1') || (C_SECURITY == '3')) && get_info('adminip') != md5(ip())) || (get_info('adminlogin') != md5(C_ADMINL)) || (get_info('adminpass') != md5(C_ADMINP))) Return False;
		else Return True;
	}
}
function PhotosNum($files)
{
	Return ($files !== '') ? substr_count($files,',') + 1 : 0;
}



function CheckAccess($UserIP)
{
	$tmp=array();
	$ips=explode(',',$UserIP);
	foreach ($ips as $k=>$v) $tmp[]=str_replace("\\*",".*",trim(preg_quote($v)));
	$s="!^(".implode("|",$tmp).")$!i";
	Return (preg_match($s,ip())) ? True : False;
}

function MyName()
{
	/*_______________________________________________
	/| This function is detect Username
	/|_______________________________________________
	*/
	Global $w;
	if (C_AUTH)
	{
		if (isset($_SESSION['username']) && ereg('^['.C_LOGIN_CHARS.']{1,16}$', $_SESSION['username'])) return $_SESSION['username'];
		else return $w[361];
	}
	else
	{
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		if (isset($_COOKIE[C_LOGIN_COOKIE.'username']) && ereg('^['.C_LOGIN_CHARS.']{1,16}$',$cr64->decrypt($_COOKIE[C_LOGIN_COOKIE.'username']))) return cb($cr64->decrypt($_COOKIE[C_LOGIN_COOKIE.'username']));
		else return $w[361];
	}
}

function printm($tmpr, $v = NULL)
{
	global $stime, $w, $wpu, $l,$_OnlineIDs;
	Global $_OnlineChatIDs,$_OnlineForumIDs,$_OnlineSearchIDs,$_OnlineMainIDs,$_OnlineFAQIDs,$_OnlineMembersIDs,$_OnlineLinksIDs,$_OnlineStatIDs,$_OnlineSubscrIDs;
	include_once C_PATH.'/header.php';
	if (($v == 1) || ($v == NULL)) $e = C_EBOT;
	else $e = C_SBOT;
	echo C_ETOP.$tmpr.$e;
	include_once C_PATH.'/footer.php';
	die;
}

function DelPicElement($var,$elem)
{
	$var = trim($var);
	$arr=explode(',',$var);
	if(strlen($var) > '0')
	{
		if(strlen($var) == '1')
		{
			if($var == $elem) $var = '';
		}
		else
		{
			$result = array_diff ($arr, array($elem));
			sort($result);reset($result);
			$var=implode(',',$result);
		}
	}
	Return $var;
}

function AddPicElement($var,$elem)
{
	if($elem === '') Return $var;
	else
	{
		$var = trim($var);
		$arr=explode(',',$var);
		$arr_elem=explode(',',$elem);
		$arr=array_merge ($arr,$arr_elem);
		$arr=array_unique ($arr);
		sort($arr);reset($arr);
		Return (trim($var) === '') ? $elem : implode(',',$arr);
	}
}

function MyAccess()
{
	/*_______________________________________________
	/| This function is detect access
	/| Guest = -1
	/| Free member = 0
	/| Silver member = 1
	/| Gold member = 2 and etc...
	/|_______________________________________________
	*/
	if (C_AUTH)
	{
		if (isset($_SESSION['d']) && ereg('^[0-9]{1,3}$', $_SESSION['d'])) return $_SESSION['d'];
		else return '-1';
	}
	else
	{
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		if (isset($_COOKIE[C_LOGIN_COOKIE.'d']) && ereg('^[0-9]{1,3}$', $cr64->decrypt($_COOKIE[C_LOGIN_COOKIE.'d']))) return cb($cr64->decrypt($_COOKIE[C_LOGIN_COOKIE.'d']));
		else return '-1';

	}
}

$_OnlineIDs=array();
$_OnlineChatIDs=$_OnlineForumIDs=$_OnlineSearchIDs=$_OnlineMainIDs=$_OnlineFAQIDs=$_OnlineMembersIDs=$_OnlineLinksIDs=$_OnlineStatIDs=$_OnlineSubscrIDs=array();

function all_online_users()
{
	Global $wpu,$l;
	Global $_OnlineIDs,$_OnlineChatIDs,$_OnlineForumIDs,$_OnlineSearchIDs,$_OnlineMainIDs,$_OnlineFAQIDs,$_OnlineMembersIDs,$_OnlineLinksIDs,$_OnlineStatIDs,$_OnlineSubscrIDs;
	$sec = (defined("C_ONLINE_MEMBER_TIME")) ? C_ONLINE_MEMBER_TIME : '300';
	$user = is_numeric(get_info('m')) ? get_info('m') : 0;
	$ip = ($user == 0) ? ip2int(ip()) : 0;
	$MyAccess = MyAccess();
	@mysql_query("DELETE FROM ".C_MYSQL_ONLINE_USERS." WHERE utime < DATE_SUB(NOW(), INTERVAL ".$sec." SECOND)");
	$result = @mysql_query("SELECT * FROM ".C_MYSQL_ONLINE_USERS);
	$cnt=array();$adduser=1;$addguest=1;$users=0;
	$qs=(!empty($_ENV["QUERY_STRING"])) ? '?'.$_ENV["QUERY_STRING"] : '';
	$url = $_SERVER["PHP_SELF"].$qs;
	while($i = mysql_fetch_array($result))
	{
		$cnt[$i['usertype']] = (isset($cnt[$i['usertype']])) ? $cnt[$i['usertype']] + 1 : 1;
		If(($MyAccess >= '0') && ($user == $i['user']))
		{
			$adduser=$addguest=0;
			if($i['upage'] == 'REMOVE') {@MakeExit();GoToURL(C_URL.'/logout.php?'.$l);}
		}
		If(($MyAccess < '0') && ($ip == $i['ip']))
		{
			$adduser=$addguest=0;
		}
		If($i['user'] >= '0') $_OnlineIDs[]=$i['user'];
		$tmp = parse_url(C_URL);
		if(IsAccess(C_WHO_IS_WHERE))
		{
			if($user == $i['user'] && $MyAccess >= '0') $i['upage'] = $url;
			if($i['user'] > '0')
			{
				if(strpos($i['upage'], $tmp['path'].'/search') !== false || strpos($i['upage'], $tmp['path'].'/qsearch') !== false || strpos($i['upage'], $tmp['path'].'/advsearch') !== false) $_OnlineSearchIDs[]=$i['user'];
				elseif(strpos($i['upage'], $tmp['path'].'/index.php') !== false) $_OnlineMainIDs[]=$i['user'];
				elseif(strpos($i['upage'],$tmp['path'].'/faq.php') !== false) $_OnlineFAQIDs[]=$i['user'];
				elseif(strpos($i['upage'], $tmp['path'].'/members/') !== false) $_OnlineMembersIDs[]=$i['user'];
				elseif(strpos($i['upage'], $tmp['path'].'/links.php') !== false) $_OnlineLinksIDs[]=$i['user'];
				elseif(strpos($i['upage'], $tmp['path'].'/stat/') !== false) $_OnlineStatIDs[]=$i['user'];
			}
		}
	}
	if($adduser || $addguest)
	{
		@mysql_query("INSERT INTO ".C_MYSQL_ONLINE_USERS." VALUES (NOW(),'".$user."','".$MyAccess."','".$ip."','".$url."')");
		$cnt[$MyAccess] = (isset($cnt[$MyAccess])) ? $cnt[$MyAccess] + 1 : 1;
	}
	else
	{
		@mysql_query("UPDATE ".C_MYSQL_ONLINE_USERS." SET utime = NOW(), upage = '".$url."' WHERE user = '".$user."' AND usertype = '".$MyAccess."' AND ip = '".$ip."'");
	}
	$k=0;while(isset($wpu[$k]))
	{
		if(isset($cnt[$k]))
		{
			$users = $cnt[$k] + $users;
		}
		$k++;
	}
	if(isset($cnt['-1'])) define('ONLINE_GUESTS',$cnt['-1']);
	else define('ONLINE_GUESTS','0');
	define('ONLINE_USERS',$users);

}

function WhoIsHere($page)
{
	Global $w;
	$ids=$names=array();$cnt=0;
	$tmp=mysql_query("SELECT DISTINCT t1.user, t1.upage, t2.* FROM ".C_MYSQL_ONLINE_USERS." as t1, ".C_MYSQL_MEMBERS_MAIN." as t2 WHERE t1.user = t2.id AND t2.status >= '7' order by t2.id") or die(mysql_error());
	while($i=mysql_fetch_array($tmp))
	{
		if(strpos($i['upage'], $page))
		{
			if($i['hide'] == '1') $cnt++;
			else {$ids[]=$i['id'];$names[] = username($i['id'],$i['username'],$i['fname'],$i['lname']);}
		}
	}
	if($cnt) {$ids[]=0;$names[]=template($w[752],array($cnt));}
	Return array($ids,$names);
}

function ShowPic($Path,$Bigger = Null)
{
	if(C_CRYPT_URL)
	{
		include_once C_PATH.'/classes/crypt.class.php';
		$cr64 = new AzDGCrypt(C_CRYPT_KEY);
		Return ($Bigger == Null) ? C_URL . '/pic.php?c=' . $cr64->crypt($Path) : C_URL . '/pic.php?c=' . $cr64->crypt($Path) . ShowPictureBigger();
	}
	else
	{
		Return C_URL . '/members/uploads/' . $Path;
	}
}

function ShowPicView($Path,$Num,$id)
{
	Return C_URL . '/photos.php?l=' . LANGUAGE . '&id=' . $id . '&picnum=' . $Num;
}

function PhotoSize($var)
{
	if(function_exists('getimagesize') && file_exists($var))
	{
		$val = @getimagesize($var);
		Return array(intval($val[0]),intval($val[1]));
	} else return array(0,0);
}

function MyID()
{
	$MyID = get_info('m');
	Return (empty($MyID) || !is_numeric($MyID)) ? '0' : $MyID;
}

function ShowPictureBigger()
{
	Return (C_CRYPT_URL) ? '&bigger' : '';
}

function IsSecure($var, $p=NULL, $msg=NULL)
{
	unset($s,$m,$o,$g,$n,$u);
	global $stime, $w, $l, $wpu;
	Global $_OnlineIDs,$_OnlineChatIDs,$_OnlineForumIDs,$_OnlineSearchIDs,$_OnlineMainIDs,$_OnlineFAQIDs,$_OnlineMembersIDs,$_OnlineLinksIDs,$_OnlineStatIDs,$_OnlineSubscrIDs;
	if($var >= 0)
	{
		if (
		(MyAccess() < $var) || (!is_md5(get_info('s'))) || (!is_numeric(get_info('m'))) || (!is_md5(get_info('o'))) || (!is_numeric(get_info('m'))) || (((C_SECURITY == '2') || (C_SECURITY == '3')) && (get_info('o') != md5(agent()))) || (((C_SECURITY == '1') || (C_SECURITY == '3')) && get_info('s') != md5(ip())))
		{
		($p == NULL) ? include_once C_PATH.'/header.php' : include_once C_PATH.'/sheader.php';
		if (isset($wpu[$var]))
		{
			if(IsAccess(C_WHO_CAN_SHOW))
			{
				$goto = (GetServerConstant("PHP_SELF") && GetServerConstant("QUERY_STRING")) ? '&goto='.GetServerConstant("PHP_SELF").'?'.htmlentities(urlencode(GetServerConstant("QUERY_STRING"))) : '';
				$url = (($var == '0') || (MyID() == '0')) ? C_URL.'/login.php?l='.$l.$goto : C_URL.'/members/index.php?l='.LANGUAGE.'&a=r';
				$tm = array('<a href="'.$url.'">'.$wpu[$var].'</a>');
			}
			else
			{
				$tm = array($wpu[$var]);
			}
			$str = template($w[369], $tm);
		}
		else
		{
			$str = $w[368];
		}
		$mymes = ($msg == NULL) ? '' : $msg;
		($p == NULL) ? printm($mymes.$str) : sprintm($mymes.$str);
		}
	}
}
function IsAccessToSeeThisPage($access=null)
{
	Global $from,$step,$w,$wsp;
	$steps=explode(',',C_SEARCH_STEPS);
	$bool = ($access != null) ? !IsSearch($step,$access) : True;
	if (!isset($step) || !is_numeric($step) || (!in_array($step,$steps)) || $bool) $step = C_SRC_PAGE;
	if(!ReturnSearchValue('from','num',-1)) $from = 0;
	if(($step != 0) && (ceil($from / $step) >= $wsp[MyAccess()+1]) && ($wsp[MyAccess()+1] != 0))
	{
		printm(template($w[528],array(MyAccessLevel(),$wsp[MyAccess()+1])));
	}
	define('WITH_SELECTED',$w[556]);
}

function IsAccess($param)
{
	return (MyAccess() >= $param) ? True : False;
}

function MyAccessLevel()
{
	Global $w,$wpu;
	if(MyAccess() >= 0) Return $wpu[MyAccess()];
	else Return $w[354];
}

if(!defined("DONT_COUNT_ONLINE"))
{
	@all_online_users();
}

function online_users()
{
	return ONLINE_USERS;
}


function online_quests()
{
	return ONLINE_GUESTS;
}

if((isset($_GET['ChangeTemplate']) || isset($_POST['ChangeTemplate'])) && IsAccess(C_OPTIONS_TEMPLATE)) {
(isset($_GET['ChangeTemplate'])) ? ChangeTemplate(cb($_GET['ChangeTemplate'])) : ChangeTemplate(cb($_POST['ChangeTemplate']),'-1');
}

if(IsAccess(C_TEMPLATE_RANDOM) && (strpos(C_URL.'/index.php',@$_SERVER['REQUEST_URI'])))
{
	$tmp_array=array();
	$handle=opendir(C_PATH.'/templates/');
	while (false!==($TemplateName = readdir($handle)))
	{
		if ($TemplateName != "." && $TemplateName != ".." && is_dir(C_PATH.'/templates/'.$TemplateName))
		{
			$tmp_array[]=$TemplateName;
		}
	}
	closedir($handle);
	$CurTemp = array_rand ($tmp_array);
	ChangeTemplate($tmp_array[$CurTemp]);
	define('C_TEMP',$tmp_array[$CurTemp]);
}
else
{
	if(!defined("C_TEMP"))
	{
		if(isset($_COOKIE['TemplateName']) && file_exists(C_PATH.'/templates/'.$_COOKIE['TemplateName'].'/config.php')  && IsAccess(C_OPTIONS_TEMPLATE)) define('C_TEMP',cb($_COOKIE['TemplateName']));
		else define('C_TEMP',C_TEMP_DEFAULT);
	}
}

function RemoveMessages($ids=null,$toid=null,$custom_sql=null,$archive=null)
{
	Global $w;
	$str='';$adr_r=$adr_t=$main=$main2=array();

	$adr_table = ($archive == null) ? C_MYSQL_ADDRESSBOOK : C_MYSQL_ADDRESSBOOK_ARCHIVE;
	$mes_table = ($archive == null) ? C_MYSQL_MESSAGES : C_MYSQL_MESSAGES_ARCHIVE;

	# Checking for message ID for numeric value - for security reasons:
	$p=0;while(isset($ids[$p]))	{if(!is_numeric($ids[$p])) sprintm($w[1].$w[185]);$p++;}

	# Generating sql query for select and remove messages queries
	if($custom_sql !== null) $msql = $custom_sql;
	else
	{
		$mtoid = ($toid === null) ? '' :  " and toid = ".$toid;
		$msql =  "id in (".cb(implode(',',$ids)).")".$mtoid;
	}

	# Difficult algorithm to remove messages :)
	# Because information about new and total messages locate in the addressbook, we need
	# to find and change this information, and only then remove messages

	# Selecting information from Messages table
	$tmp=mysql_query("Select fromid,toid,count(if(readed>0,readed,null)) as readed,count(id) as total from ".$mes_table." where ".$msql." group by toid") or die(mysql_error());
	$count = mysql_num_rows($tmp);
	if($count == 0) sprintm(template($w[238],array(0)));
	while($i=mysql_fetch_array($tmp))
	{
		$str.="(myid = '".$i['fromid']."' AND user = '".$i['toid']."') OR (user = '".$i['fromid']."' AND myid = '".$i['toid']."') OR ";
		$adr_r[$i['fromid'].'-'.$i['toid']]=$adr2[]=$i['readed'];
		$adr_t[$i['fromid'].'-'.$i['toid']]=$adr2[]=$i['total'];
	}

	# Selecting information from Addressbook tables
	$tmp2=mysql_query("Select * from ".$adr_table." where ".substr($str,0,-4)) or die(mysql_error());

	$count = mysql_num_rows($tmp2);
	if($count == 0) sprintm(template($w[238],array(0)));
	while($i=mysql_fetch_array($tmp2))
	{
		if($archive == null)
		{
			$main[$i['myid'].'-'.$i['user']]=$main2[]= $i['myid'].'|'.$i['user'].'|'.$i['new_mes'].'|'.$i['total_mes'].'|'.$i['lastdate'].'|'.$i['status'];
		}
		else
		{
			$main[$i['myid'].'-'.$i['user']]=$main2[]=$i['myid'].'|'.$i['user'].'|'.$i['new_mes'].'|'.$i['total_mes'].'|'.$i['lastdate'];
		}
	}
	$str='';
	$str_array=array();
	# Counting received data into Addressbook, based on information we received
	$p=$step=0;while(isset($main2[$p]))
	{
		$readed=$total=$readed2=0;
		$s5=explode('|',$main2[$p]);
		$s5_=explode('|',$main[$s5[1].'-'.$s5[0]]);
		$readed=(!isset($adr_r[$s5[0].'-'.$s5[1]])) ? $readed : $readed + $adr_r[$s5[0].'-'.$s5[1]];
		$readed2=(!isset($adr_r[$s5[1].'-'.$s5[0]])) ? $readed2 : $readed2 + $adr_r[$s5[1].'-'.$s5[0]];
		$total =(!isset($adr_t[$s5[0].'-'.$s5[1]])) ? $total : $total + $adr_t[$s5[0].'-'.$s5[1]];
		$total =(!isset($adr_t[$s5[1].'-'.$s5[0]])) ? $total : $total + $adr_t[$s5[1].'-'.$s5[0]];
		if($archive == null)
		{
			$str .= "('".$s5[0]."','".$s5[1]."','".($s5[2]-$readed)."','".($s5[3]-$total)."','".$s5[4]."'),('".$s5_[0]."','".$s5_[1]."','".($s5_[2]-$readed2)."','".($s5[3]-$total)."','".$s5_[4]."'),";
		}
		else
		{
			$str .= "('".$s5[0]."','".$s5[1]."','".($s5[2]-$readed)."','".($s5[3]-$total)."','".$s5[4]."','".$s5[5]."'),('".$s5_[0]."','".$s5_[1]."','".($s5_[2]-$readed2)."','".($s5[3]-$total)."','".$s5_[4]."','".$s5_[5]."'),";
		}

		$p++;$step++;
		if($step == 1000)
		{
			$step = 0;
			$str_array[]=substr($str,0,-1);
			$str='';
		}
	}
	# Replacing received data into Addressbook, based on information we received
	$p=0;while(isset($str_array[$p])) {mysql_query("REPLACE INTO ".$adr_table." VALUES ".$str_array[$p]);$p++;}
	if($str != '') mysql_query("REPLACE INTO ".$adr_table." VALUES ".substr($str,0,-1));

	# Removing messages
	mysql_query("DELETE FROM ".$mes_table." WHERE ".$msql) or die(mysql_error());
	sprintm(template($w[238],array(mysql_affected_rows())));
}



function CreateAddressBook($param=null,$archive=null)
{
	# $param:
	# null - create new addressbook
	# 1 - Update existing addressbook

	# $archive
	# null - for messages
	# true - for archive

	$adr_table = ($archive == null) ? C_MYSQL_ADDRESSBOOK : C_MYSQL_ADDRESSBOOK_ARCHIVE;
	$mes_table = ($archive == null) ? C_MYSQL_MESSAGES : C_MYSQL_MESSAGES_ARCHIVE;

	$trows = mysql_fetch_array(mysql_query("SELECT count(*) as total FROM ".$adr_table));
	$count = $trows['total'];
	if($param == null)
	{
		if($count && $param == null) {
			mysql_query("ALTER TABLE ".$adr_table." DROP INDEX ids");
			@mysql_query("DELETE FROM ".$adr_table);
			mysql_query("ALTER TABLE ".$adr_table." ADD UNIQUE ids (user,myid)");
		}
	}

	# Selecting user with unactive statuses
	$usrst = array();
	$tab = mysql_query("Select id,status from ".C_MYSQL_MEMBERS_MAIN." WHERE status < '7'");
	$count=mysql_num_rows($tab);
	if($count)
	{
		while($k=mysql_fetch_array($tab))
		{
			$usrst[intval($k['id'])]=$k['status'];
		}
	}

	$adrb=array();
	$tab = mysql_query("Select myid,user from ".$adr_table." WHERE lastdate = 0");
	$count=mysql_num_rows($tab);
	if($count)
	{
		while($k=mysql_fetch_array($tab))
		{
			$adrb[$k['myid']][$k['user']]=0;
		}
	}
	$tmp = mysql_query("Select fromid,toid,max(sendtime) as sendtime,readed,count(*) as total_mes from ".$mes_table." where fromid != toid group by CONCAT_WS('-',GREATEST(fromid,toid),LEAST(fromid,toid))");
	$cnt = mysql_num_rows($tmp);$steps=0;$str_array=array();
	if($cnt != 0)
	{
		$str='';
		$tmp2 = mysql_query("Select fromid,toid,count(*) as total_new from ".$mes_table." where fromid != toid and readed > 0 group by CONCAT_WS('-',fromid,toid)");
		$cnt2 = mysql_num_rows($tmp2);
		if($cnt2 != 0)
		{
			$arr_new=array();
			while($j=mysql_fetch_array($tmp2))
			{
				$arr_new[$j['fromid']][$j['toid']]=$j['total_new'];
			}
		}
		while($i=mysql_fetch_array($tmp))
		{
			$r=(isset($arr_new[$i['fromid']][$i['toid']])) ? intval($arr_new[$i['fromid']][$i['toid']]) : 0;
			$r2=(isset($arr_new[$i['toid']][$i['fromid']])) ? intval($arr_new[$i['toid']][$i['fromid']]) : 0;
			$ldate=(isset($adrb[$i['fromid']][$i['toid']])) ? intval($adrb[$i['fromid']][$i['toid']]) : $i['sendtime'];
			$ldate2=(isset($adrb[$i['toid']][$i['fromid']])) ? intval($adrb[$i['toid']][$i['fromid']]) : $i['sendtime'];
			$steps++;
			if($archive == null)
			{
				$st1 = (isset($usrst[intval($i['fromid'])])) ? $usrst[$i['fromid']] : '7';
				$st2 = (isset($usrst[intval($i['toid'])])) ? $usrst[$i['toid']] : '7';
				$str .= "('".$i['fromid']."','".$i['toid']."','".$r."','".$i['total_mes']."','".$ldate."','".$st1."'),('".$i['toid']."','".$i['fromid']."','".$r2."','".$i['total_mes']."','".$ldate2."','".$st2."'),";
			}
			else
			{
				$str .= "('".$i['fromid']."','".$i['toid']."','".$r."','".$i['total_mes']."','".$ldate."'),('".$i['toid']."','".$i['fromid']."','".$r2."','".$i['total_mes']."','".$ldate2."'),";
			}
			if($steps == 1000) {
				$steps = 0;
				mysql_query("REPLACE INTO ".$adr_table." VALUES ".substr($str,0,-1)) or die(mysql_error());
				$str='';
			}
		}
		if($str != '') mysql_query("REPLACE INTO ".$adr_table." VALUES ".substr($str,0,-1)) or die(mysql_error());
	}
}

function SearchInFile($file,$str)
{
	$bool = False;
	$cnt = file($file);$fp = fopen($file,"r");@flock($fp, LOCK_EX);
	for ($i=0;$i<count($cnt);$i++)
	{
		if (strstr ($cnt[$i],$str))
		{
			$bool = True;
			break;
		}
	}
	@flock($fp, LOCK_UN);
	fclose($fp);
	Return $bool;
}

function InsertInFile($file,$find,$str,$times)
{
	$cnt = file($file);$fp = fopen($file,"w");flock($fp, LOCK_EX);
	for ($i=0;$i<count($cnt);$i++)
	{
		if (strstr($cnt[$i],$find) && $times)
		{
			$tmp = $cnt[$i];
			$cnt[$i] = $str.$tmp;
			if($times) $times--;
		}
	}
	fwrite($fp, implode("",$cnt));fflush($fp);flock($fp, LOCK_UN);
	fclose($fp);
}

function ReturnIds($ids,$from,$step)
{
	$str='';
	for($i=$from;$i<($from+$step);$i++)
	{
		if(isset($ids[$i])) $str .= $ids[$i].',';
	}
	if(strlen($str) > 0) $str = substr($str,0,-1);
	return $str;
}

if(!(isset($l))) $l='default';
define('LANGUAGE',cb($l));

function GenQuickForumLinks($OnlyId=null,$Sel=null,$addval=null)
{
	Global $w;
	$tmp=mysql_query("SELECT t1.*,t2.* FROM ".C_MYSQL_FORUM." as t2,".C_MYSQL_FORUMCAT." as t1 WHERE access <= ".MyAccess()." AND t1.id = t2.cid order by t1.catname ASC");
	$Value = '';
	$selected = ($Sel !== null && in_array('',$Sel)) ? ' selected' : '';
	if($addval != null) $Value .= '<option value=""'.$selected.'>'.$addval;
	$selected = ($Sel !== null && in_array('0',$Sel)) ? ' selected' : '';
	$Value .= ($OnlyId == null) ? '<option value="'.C_URL.'/forum/index.php?l='.LANGUAGE.'"'.$selected.'>'.$w[591] : '<option value="0"'.$selected.'>'.$w[591];
	while($i=mysql_fetch_array($tmp))
	{
		$selected = ($Sel !== null && in_array($i['id'],$Sel)) ? ' selected' : '';
		$Value .= ($OnlyId == null) ? '<option value="'.C_URL.'/forum/forum.php?l='.LANGUAGE.'&fid='.$i['id'].'"'.$selected.'>'.$i['catname'].' > '.$i['title'] : '<option value="'.$i['id'].'"'.$selected.'>'.$i['catname'].' > '.$i['title'];
	}
	define('FORUM_VALUE',$Value);
}

function IsGlobalForumMod(){
	$tmp=explode(',',C_FORUM_GLOBAL_MOD_IDS);
	if (in_array (MyID(), $tmp)) return True;
	else return False;
}

function CheckForumBan($ThisForumId) {
	if(C_FORUM_BANS) {
		$tmp=mysql_query("SELECT bans FROM ".C_MYSQL_MEMBERS_FORUM." WHERE id = ".MyID());
		$count = mysql_num_rows($tmp);
		if($count == 0) Return False;
		else {
			while($i=mysql_fetch_array($tmp))
			{
				if($i['bans'] == '') Return False;
				else {
					$tmp=explode(',',$i['bans']);
					if (in_array ($ThisForumId, $tmp)) return True;
					else return False;
				}
			}
		}
	} else return false;
}


function UsersNumberPerCountry($country)
{
	include_once C_PATH.'/classes/cachequery.class.php';
	$tmp = New CacheQuery("SELECT country, count(*) as c FROM ".C_MYSQL_MEMBERS_MAIN." WHERE status >= '7' group by country order by c desc",True);
	$ret = 0;
	while(list($k,$i)=@each($tmp->data)) {
		if($i['country'] == $country)
		{
			$ret = $i['c'];
			break;
		}
	}
	Return $ret;
}

function MUIPic($pic)
{
	$ext = strrchr($pic,".");
	$muipic = str_replace($ext,'_'.LANGUAGE.$ext,$pic);
	return (file_exists(C_PATH.'/'.$muipic)) ? $muipic : $pic;
}

function Date2Phrase($date,$else_ret)
{
	Global $w; // In future will return from language file
	$W_Today = $w[750];
	$W_Yesterday = $w[749];

	$date_ = explode(" ", $date);

	$today = date("Y-m-d");
	$yesterday = date("Y-m-d", strtotime("-1 day"));

	if($date_[0] == $today) Return $W_Today.', '.$date_[1];
	elseif($date_[0] == $yesterday) Return $W_Yesterday.', '.$date_[1];
	else Return $else_ret;
}

function CheckForIgnor($id,$msg=null)
{
	Global $w;
	if(C_BANSH < '256') {
		$sql = mysql_query("SELECT count(id) as total FROM ".C_MYSQL_BANLIST." WHERE myid = '".$id."' AND (user='".MyID()."' or user='0')") or die(mysql_error());
		$trows = mysql_fetch_array($sql);
		$total = $trows['total'];
		if($total != '0')
		{
			if($msg === null) printm($w[324],2);
			else sprintm($w[324],2);
		}
	}
}

function CheckNoKiss($id)
{
	Global $w;
	if(!IsAccess(C_SUPER_KISS))
	{
		$sql = mysql_query("SELECT count(id) as total FROM ".C_MYSQL_MEMBERS_SEC." WHERE id = '".$id."' AND nokiss = '1'") or die(mysql_error());
		$trows = mysql_fetch_array($sql);
		$total = $trows['total'];
		if($total != '0') sprintm($w[768],1);
	}
}

function IsUserAccess($param,$access)
{
	return ($access >= $param) ? True : False;
}

function NewMsgIcon()
{
	return '<img src="'.C_URL.'/templates/'.C_TEMP.'/images/nm.gif" border=0> ';
}

function ShowAV($av)
{

	if(IsAV($av)) { return "
                       <script language=\"JavaScript\">
                        <!--
                        var soundFile = \"".C_URL."/members/uploads/".$av."\";
                        if(navigator.plugins.length>0){
                        	document.write('<embed src=\"'+soundFile+'\" autostart=\"".C_AUDIO_AUTOSTART."\" loop=\"".C_AUDIO_LOOP."\" ".audio_player(C_AUDIO_PLAYER,'0')."></embed>');}
                        	else {
                        		document.write('<embed src=\"'+soundFile+'\" autostart=\"".C_AUDIO_AUTOSTART."\" loop=\"".C_AUDIO_LOOP."\" ".audio_player(C_AUDIO_PLAYER,'1')."></embed>');}
                        		//-->
                  </script>
      <noscript><embed src=\"".C_URL."/members/uploads/".$av."\" autostart=\"".C_AUDIO_AUTOSTART."\" loop=\"".C_AUDIO_LOOP."\"></embed></noscript>
      <noembed><bgsound src=\"".C_URL."/members/uploads/".$av."\" loop=\"".C_AUDIO_LOOP."\"></noembed>";
	} else {
		return "
      <OBJECT id='mediaPlayer' width=\"320\" height=\"285\" 
      classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' 
      codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'
      standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>
      <param name='fileName' value=\"".C_URL."/members/uploads/".$av."\">
      <param name='animationatStart' value='true'>
      <param name='transparentatStart' value='true'>
      <param name='autoStart' value=\"".C_AUDIO_AUTOSTART."\">
      <param name='showControls' value=\"true\">
      <param name='loop' value=\"".C_AUDIO_LOOP."\">
      <EMBED type='application/x-mplayer2'
        pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
        id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' 
        bgcolor='darkblue' showcontrols=\"true\" showtracker='-1' 
        showdisplay='0' showstatusbar='-1' videoborder3d='-1' width=\"320\" height=\"285\"
        src=\"".C_URL."/members/uploads/".$av."\" autostart=\"".C_AUDIO_AUTOSTART."\" designtimesp='5311' loop=\"".C_AUDIO_LOOP."\">
      </EMBED>
      </OBJECT>";
	}
}

function GenLink($type,$prm,$lnk=null)
{
	$pre = C_URL.'/';
	if($lnk != null) $prm = array_merge ($prm, $lnk);
	switch($type)
	{
		case 'UserProfile':
			return (C_SEF) ? $pre.template(C_SEF_VP,array('LANGUAGE'=>$prm[0],'ID'=>intval($prm[1]))) : $pre.'view.php?l='.$prm[0].'&id='.$prm[1];
			break;
		case 'Stat':
			return (C_SEF) ? $pre.template(C_SEF_ST,array('LANGUAGE'=>$prm[0])) : $pre.'stat.php?l='.$prm[0];
			break;
		case 'Last':
			return (C_SEF) ? $pre.template(C_SEF_LAST,array('LANGUAGE'=>$prm[0],'FROM'=>$prm[1],'GENDER'=>$prm[2])) : $pre.'last.php?l='.$prm[0].'&gender='.$prm[2];
			break;
		case 'Top':
			return (C_SEF) ? $pre.template(C_SEF_TOP,array('LANGUAGE'=>$prm[0],'FROM'=>$prm[1],'GENDER'=>$prm[2],'PIC'=>$prm[3])) : $pre.'top.php?l='.$prm[0].'&gender='.$prm[2].'&pic='.$prm[3];
			break;
		case 'HotTop':
			return (C_SEF) ? $pre.template(C_SEF_HOTTOP,array('LANGUAGE'=>$prm[0],'FROM'=>$prm[1],'GENDER'=>$prm[2])) : $pre.'hot_top.php?l='.$prm[0].'&gender='.$prm[2];
			break;
		case 'Blogs':
			return (C_SEF) ? $pre.template(C_SEF_BLOGS,array('LANGUAGE'=>$prm[0],'FROM'=>$prm[1],'CAT'=>$prm[2])) : $pre.'users_blogs.php?l='.$prm[0].'&cat='.$prm[2];
			break;
		case 'Blog':
			return (C_SEF) ? $pre.template(C_SEF_BLOG,array('LANGUAGE'=>$prm[0],'ID'=>$prm[1])) : $pre.'blog_entry.php?l='.$prm[0].'&id='.$prm[1];
			break;
		case 'ForumIndex':
			return (C_SEF) ? $pre.template(C_SEF_FORUM_INDEX,array('LANGUAGE'=>$prm[0])) : $pre.'forum/index.php?l='.$prm[0];
			break;
		case 'Forum':
			return (C_SEF) ? $pre.template(C_SEF_FORUM_FORUM,array('LANGUAGE'=>$prm[0],'FORUM'=>$prm[1],'TITLE'=>EncodeURL(CutSlashes($prm[2])))) : $pre.'forum/forum.php?l='.$prm[0].'&fid='.$prm[1];
			break;
		case 'Thread':
			return (C_SEF) ? $pre.template(C_SEF_FORUM_THREAD,array('LANGUAGE'=>$prm[0],'PARAM'=>$prm[1],'THREAD'=>$prm[2],'TITLE'=>EncodeURL(CutSlashes($prm[3])))) : $pre.'forum/thread.php?l='.$prm[0].'&tid='.$prm[2].'&'.$prm[1];
			break;
		case 'Links':
			return (C_SEF) ? $pre.template(C_SEF_LINKS,array('LANGUAGE'=>$prm[0],'ID'=>$prm[1],'TITLE'=>EncodeURL(CutSlashes($prm[2])))) : $pre.'links.php?l='.$prm[0].'&sid='.$prm[1];
			break;
		case 'LinksCat':
			return (C_SEF) ? $pre.template(C_SEF_LINKS_CAT,array('LANGUAGE'=>$prm[0],'FROM'=>$prm[1],'ID'=>$prm[2],'TITLE'=>EncodeURL(CutSlashes($prm[3])))) : $pre.'links.php?l='.$prm[0].'&cid='.$prm[2];
			break;
	}
}

function EncodeURL($param)
{
	return (C_SEF_ENCODE) ? rawurlencode($param) : $param;
}

function CutSlashes($text)
{
	return str_replace('/','',$text);
}

function ReturnError($file,$line)
{
	$file = str_replace(C_PATH,'',$file);

	return "<br>File: " . $file . "<br>" . "Line: ". $line;
}

function GetTemplates()
{
	$handle=opendir(C_PATH.'/templates/'); $tmparr=array();
	while (false!==($TemplateName = readdir($handle)))
	{
		if ($TemplateName != "." && $TemplateName != ".." && is_dir(C_PATH.'/templates/'.$TemplateName))
		{
			$tmparr[] = $TemplateName;
		}
	}
	closedir($handle);
	return $tmparr;
}

function GetURL($url){$Tmp = parse_url($url);$Arr = explode(".", $Tmp['host']);Return $Arr[count($Arr)-2].'.'.$Arr[count($Arr)-1];}

$color='';
function colors($nochange=NULL) {
	global $color;
	if($nochange == NULL) {
		$color = ($color == COLOR4) ? COLOR3 : COLOR4;
	}
	return $color;
}

function LimitString($value, $length, $postfix = " ...")
{
	$pre_string = substr($value, 0, $length);
	$pos_end = strrpos($pre_string, " ");
	if($pos_end === false) $string = $pre_string.$postfix;
	else $string = substr($pre_string, 0, $pos_end).$postfix;
	return $string;
}

function BBCheck($var)
{
	/*
	0. Can to use smiles
	1. Can to use Bold
	2. Can to use Italic
	3. Can to use Underline
	4. Can to use Strike
	5. Can to use QUOTES
	6. Can to use URL
	7. Can to use IMG
	8. Can to use VIDEO
	*/
	$tmp = explode(',',$var);
	define('USE_SMILES', IsAccess($tmp[0]) ? True : False);
	define('USE_BOLD', IsAccess($tmp[1]) ? True : False);
	define('USE_ITALIC', IsAccess($tmp[2]) ? True : False);
	define('USE_UNDERLINE', IsAccess($tmp[3]) ? True : False);
	define('USE_STRIKE', IsAccess($tmp[4]) ? True : False);
	define('USE_QUOTE', IsAccess($tmp[5]) ? True : False);
	define('USE_URL', IsAccess($tmp[6]) ? True : False);
	define('USE_IMG', IsAccess($tmp[7]) ? True : False);
	define('USE_VIDEO', IsAccess($tmp[8]) ? True : False);

	define('USE_BB', (USE_BOLD || USE_ITALIC || USE_UNDERLINE || USE_STRIKE || USE_QUOTE || USE_URL || USE_IMG || USE_VIDEO) ? True : False);
}

function GetC_URL(){$Tmp = parse_url(C_URL);$Arr = explode(".", $Tmp['host']);Return $Arr[count($Arr)-2].'.'.$Arr[count($Arr)-1];}
?>