Просмотр файла function.php

Размер файла: 68.14Kb
<?php

function check($str)
{
    $str = htmlentities($str, ENT_QUOTES, 'UTF-8');
    $str = str_replace("\'", "&#39;", $str);
    $str = str_replace("\r\n", "<br/>", $str);
    $str = strtr
		(
			$str, 
			array
			(
				chr("0") => "", 
				chr("1") => "", 
				chr("2") => "", 
				chr("3") => "", 
				chr("4") => "", 
				chr("5") => "", 
				chr("6") => "", 
				chr("7") => "", 
				chr("8") => "", 
				chr("9") => "", 
				chr("10") => "", 
				chr("11") => "", 
				chr("12") => "", 
				chr("13") => "", 
				chr("14") => "", 
				chr("15") => "", 
				chr("16") => "", 
				chr("17") => "", 
				chr("18") => "", 
				chr("19") => "", 
				chr("20") => "", 
				chr("21") => "", 
				chr("22") => "", 
				chr("23") => "", 
				chr("24") => "", 
				chr("25") => "", 
				chr("26") => "", 
				chr("27") => "", 
				chr("28") => "", 
				chr("29") => "", 
				chr("30") => "", 
				chr("31") => ""
			)
		);
	$str = str_replace('\\', "&#92;", $str);
	$str = str_replace("|", "I", $str);
	$str = str_replace("||", "I", $str);
	$str = str_replace("/\\\$/", "&#36;", $str);
	$str = str_replace("[l]http://", "[l]", $str);
	$str = str_replace("[l] http://", "[l]", $str);
	$str = mysql_real_escape_string($str);
	return $str;
}

function smail($to,$sender,$name,$subject,$message)
{
	//$message = check($message);
	$headers = 'MIME-Version: 1.0' . '';
	$headers .= 'Content-type: text/plain; charset=UTF-8';
	$headers .= '' . 'To: '.check($to). '<' . check($to) . '>' . '';
	$headers .= '' . 'From: '.check($name).'<'.check($sender).'>'.'';
	return mail ($to, $subject, $message, $headers);
}

function timemsg($sec)
{
	$ds = floor($sec/60/60/24);
	if($ds=="1")
	{
		return "$ds day";
	}
	else if($ds > 1)
	{
		return "$ds days";
	}
	$hs = floor($sec/60/60);
	if($hs=="1")
	{
		return "$hs hour";
	}
	else if($hs > 1)
	{
		return "$hs hours";
	}
	$ms = floor($sec/60);
	if($ms=="1")
	{
		return "$ms minute";
	}
	else if($ms > 1)
	{
		return "$ms minutes";
	}
	return "$sec seconds";
}

function bbcode($text)
{
	global $_prefs, $ses;
	
	$res = mysql_query('SELECT * FROM _users');
	while($row = mysql_fetch_array($res))
	{
		if(CheckFriend($row['id']) == 3)
		{
			$user = $row['username'];
			$id = $row['id'];
		$text = str_replace("@".$user,"<a href=\"".$_prefs['selfurl']."?ac=prf&amp;id=$id&amp;sid=".$ses['id']."\">$user</a>", $text);
		}
  	}
	//$text = ereg_replace("http://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $text);
	//$text = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $text);
	$text = preg_replace("/\[b\](.*?)\[\/b\]/i","<b>\\1</b>", $text);
	$text = preg_replace("/\[i\](.*?)\[\/i\]/i","<i>\\1</i>", $text);
	$text = preg_replace("/\[u\](.*?)\[\/u\]/i","<u>\\1</u>", $text);
	$text = preg_replace("/\[st\](.*?)\[\/st\]/i","<strike>\\1</strike>", $text);
	$text = preg_replace("/\[big\](.*?)\[\/big\]/i","<big>\\1</big>", $text);
	$text = preg_replace("/\[s\](.*?)\[\/s\]/i","<small>\\1</small>", $text);
	$text = preg_replace("/\[color\=(.*?)\](.*?)\[\/color\]/is","<font color=\"$1\">$2</font>", $text);
	$text = str_replace("[br/]","<br />", $text);
	if(substr_count($text,"[br/]")<=3)
	{
		$text = str_replace("[br/]","<br />", $text);
	}
	return $text;
}
function GenerateRandomKey($str)
{
	return(md5(microtime().(function_exists('posix_getpid') ? posix_getpid() : mt_rand(0, 1000)).uniqid($str)));
}

function timedate($sec)
{
	$sec = $sec + (-5 * 60 * 60);
	$ds = floor($sec/60/60/24);
	if($ds>="1")
	{
		return date("D h:i a", $sec);
	}
	else if($ds > 1)
	{
		return date("D h:i a", $sec);
	}
	$hs = floor($sec/60/60);
	if($hs=="1")
	{
		return date("h:i a", $sec);
	}
	else if($hs > 1)
	{
		return date("h:i a", $sec);
	}
	$ms = floor($sec/60);
	if($ms=="1")
	{
		return date("h:i a", $sec);
	}
	else if($ms > 1)
	{
		return date("h:i a", $sec);
	}
	return date("h:i a", $sec);
}

function getage($dob)
{
	$dob = explode("-",$dob);
	$m = $dob[0];
	$d = $dob[1];
	$y = $dob[2];
	$age = date("Y") - $y;
	if(date("m")<$m)
	{
		$age-=1;
	}else if((date("m")==$m)&&(date("d")<$d))
    {
      $age-=1;
    }
	return $age;
}

function getip()
{
	if(getenv('HTTP_X_FORWARDED_FOR'))
	{
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	if(strstr($ip, ','))
	{
		$ips = explode(',', $ip);
		$ip = $ips[0];
	}
	return $ip;
}

function cutbrws()
{
	$b = explode('/', $_SERVER['HTTP_USER_AGENT']);
	return $b[0];
}

function extformat($name)
{
    $f1 = strrpos($name, ".");
    $f2 = substr($name, $f1 + 1, 999);
    $fname = strtolower($f2);
    return $fname;
}

function PageNav($params, $smarty)
{
	$tpl_on = $params['on'];
	$tpl_off = $params['off'];
	$current_side = $params['page'];
	$number_of_sides = $params['pages'];
	$ret = '';

	$sides = array($current_side-3,
		$current_side-2,
		$current_side-1,
		$current_side,
		$current_side+1,
		$current_side+2,
		$current_side+3);

	if($current_side > 1)
	{
		$ret .= str_replace('.t', '&#171;', str_replace('.s', ($current_side-1), $tpl_off));
	}

	while(list($key,$val) = each($sides))
	{
		if($val >= 1 && $val <= $number_of_sides)
		{
			if($current_side == $val)
			{
				$ret .= str_replace(array('.s', '.t'), $val, $tpl_on);
			}else{
				$ret .= str_replace(array('.s', '.t'), $val, $tpl_off);
			}
		}
	}

	if($current_side < $number_of_sides)
	{
		$ret .= str_replace('.t', '&#187;', str_replace('.s', ($current_side+1), $tpl_off));
	}

	return($ret);
}

function Lang($params, $smarty)
{
	global $lang;
	
	$phrase = $params['p'];
	
	if(isset($lang[$phrase]))
	{
		return($lang[$phrase]);
	}
	return('#UNKNOWN_PHRASE(' . $phrase . ')#');
}

function scharin($word)
{
  	$chars = "-=@!?~_()[].*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
  	for($i=0;$i<strlen($word);$i++)
  	{
 		$ch = substr($word,$i,1);
		$nol = substr_count($chars,$ch);
		if($nol==0)
		{
			return true;
		}
	}
  		return false;
}

function schar($word)
{
  	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
  	for($i=0;$i<strlen($word);$i++)
  	{
 		$ch = substr($word,$i,1);
		$nol = substr_count($chars,$ch);
		if($nol==0)
		{
			return true;
		}
	}
  		return false;
}

function spacesin($word)
{
	$pos = strpos($word," ");
	if($pos === false)
	{
		return false;
	}else{
		return true;
	}
}
function chkuserid($id)
{
	$chk = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM _users WHERE id='".check($id)."'"));
	if($chk[0])
	{
		return true;
	}else{
		return false;
	}
}

function chkuser($user)
{
	$chk = mysql_fetch_array(mysql_query("SELECT username FROM _users WHERE username='".check($user)."'"));
	if($chk[0])
	{
		return true;
	}else{
		return false;
	}
}

function chkgroup($grp)
{
	$chk = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM _groups WHERE grp='".check($grp)."'"));
	if($chk[0])
	{
		return true;
	}else{
		return false;
	}
}

function getusername($id)
{
	$chk = mysql_fetch_array(mysql_query("SELECT username FROM _users WHERE id='".check($id)."'"));
	return ucfirst($chk[0]);
}
function getuser($user)
{
	$get = mysql_fetch_array(mysql_query("SELECT * FROM _users WHERE email='".check($user)."' OR username='".check($user)."'"));
	return $get;
}

function getuserinfo($id)
{
	$get = mysql_fetch_array(mysql_query("SELECT * FROM _users WHERE id='".check($id)."'"));
	return $get;
}

function getgroupinfo($id)
{
	$get = mysql_fetch_array(mysql_query("SELECT * FROM _groups WHERE id='".check($id)."'"));
	return $get;
}

function getdetail($id)
{
	$get = mysql_query("SELECT * FROM _detail WHERE userid='".check($id)."'");
	if(mysql_num_rows($get) == 0)
	{
		$result = 0;
	}
	else
	{
		$result = mysql_fetch_array($get);
	}
	return $result;
}

function getsetphoto($id)
{
	$get = getdetail($id);
	$info = getuserses($id);
	$photo = getphoto($info['photo']);
	if($info['photo'] > 0)
	{
		$set = 'photo/'.$photo['url'];
	}else if($get['sex'] == 1)
	{
		$set = 'photo/male.gif';
	}
	else if($get['sex'] == 2)
	{
		$set = 'photo/female.gif';
	}else{
		$set = 'photo/nophoto.png';
	}
	return $set;
}

function ForgotPassword($info)
{
	global $_prefs;
	
	$user = getuser($info);
	$char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,_-&$";
	if($user['id'] > 0)
	{
		if($user['email'] == $info || $user['username'] == $info)
		{
			for($i = 0; $i < 8; $i++)
			{
				$pwResetNew .= substr($char, mt_rand(0, strlen($char)-1), 1);
			}
			$pwResetKey = GenerateRandomKey('pwResetKey');
			$upd = mysql_query('UPDATE _users SET pw_reset_new="'.md5($pwResetNew).'", pw_reset_key="'.$pwResetKey.'" WHERE id="'.$user['id'].'"');
			$subject = 'Forgot Password';
			$link = sprintf('%sreset/%d/%s', $_prefs['selfurl'], $user['id'], $pwResetKey);
			$message = 'Dear '.$user['username'].',' . "\n\n" 
					.	'a password request has been requested for your account. ' . "\n\n"
					. 	'Your new password is: '.$pwResetNew.''."\n\n"
					.	'Please click the following link to activate your new password: '."\n\n"
					. 	$link."\n\n"
					.	' After clicking the link you can login using the password given above.' . "\n\n"
					.	'(This message has been generated automatically)';
			if(smail($user['email'], $_prefs['email'], $_prefs['title'], $subject, $message))
			{
				return true;
			}
		}
	}
}

function ResetPassword($id, $rkey)
{
	if(strlen($rkey) == 32 && $id > 0)
	{
		$result = mysql_query('UPDATE _users SET password=pw_reset_new, pw_reset_new="", pw_reset_key="" WHERE id="'.check($id).'" AND
		LENGTH(pw_reset_new)="32" AND LENGTH(pw_reset_key)="32" AND pw_reset_key="'.check($rkey).'"');
		if($result)
		{
			return true;
		}
	}
}

function getphoto($id)
{
	$photo = mysql_fetch_array(mysql_query('SELECT * FROM _photo WHERE id="'.check($id).'"'));
	return $photo;
}

function getuserses($id)
{
	$get = mysql_fetch_array(mysql_query("SELECT * FROM _users WHERE id='".check($id)."'"));
	return $get;
}

function getses($ses)
{
	$get = mysql_fetch_array(mysql_query("SELECT * FROM _session WHERE id='".check($ses)."'"));
	return $get;
}

function chkmail($mail)
{
	$chk = mysql_fetch_array(mysql_query("SELECT email FROM _users WHERE email='".check($mail)."'"));
	if($chk[0])
	{
		return true;
	}else{
		return false;
	}
}

function chkeus($user)
{
	$chk = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM _users WHERE email='".check($user)."' OR username='".check($user)."'"));
	if($chk[0])
	{
		return true;
	}else{
		return false;
	}
}

function chkemail($email)
{
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function upgroup($id, $group, $description, $privacy)
{
	global $ses, $_prefs;
	$reg = mysql_query('UPDATE _groups SET grp="'.check($group).'", description="'.check($description).'", dtm="'.time().'", level="'.check($privacy).'"
			WHERE id="'.check($id).'"');
	if($reg)
	{
		$info = mysql_fetch_array(mysql_query('SELECT id FROM _groups WHERE grp="'.check($group).'"'));
		$in = mysql_query('INSERT INTO _members SET userid="'.check($ses['userid']).'", grp="'.check($info[0]).'",  dtm="'.time().'", level=1');
		if($in)
		{
			header('location: '.$_prefs['selfurl'].'?ac=gop&id='.$info[0].'&sid='.$ses['id']);
			exit();
		}
	}else{
		return false;
	}
}

function addgroup($group, $description, $privacy)
{
	global $ses, $_prefs;
	$reg = mysql_query('INSERT INTO _groups SET userid="'.check($ses['userid']).'", grp="'.check($group).'", 
				description="'.check($description).'", dtm="'.time().'", level="'.check($privacy).'"');
	if($reg)
	{
		$info = mysql_fetch_array(mysql_query('SELECT id FROM _groups WHERE grp="'.check($group).'"'));
		$in = mysql_query('INSERT INTO _members SET userid="'.check($ses['userid']).'", grp="'.check($info[0]).'",  dtm="'.time().'", level=1');
		if($in)
		{
			header('location: '.$_prefs['selfurl'].'?ac=gop&id='.$info[0].'&sid='.$ses['id']);
			exit();
		}
	}else{
		return false;
	}
}

function adduser($username, $password, $email, $language)
{
	$reg = mysql_query('INSERT INTO _users SET username="'.check($username).'", password="'.check(md5($password)).'", 
				email="'.check($email).'", reg_ip="'.ip2long($_SERVER['REMOTE_ADDR']).'", reg_browser="'.$_SERVER['HTTP_USER_AGENT'].'", 
				reg_date="'.time().'", language="'.check($language).'"');
	if($reg == true)
	{
		return true;
	}else{
		return false;
	}
}

function addses($id, $rem)
{
	global $_prefs;
	$tm = time();
	$var1 = $_SERVER['HTTP_USER_AGENT'];
	$var2 = $_SERVER['REMOTE_ADDR'];
	$var3 = rand(1,1000); 
	$var4 = mt_rand(0, 1000);
	$var5 = microtime();
	$var = $tm.$var1.$var2.$var3.$var4.$var5;
	$did = md5($var);
	$did = substr($did,0,-22);
	$did = base64_encode($did);
	$did = substr($did,0,-12);
	$xtm = time() + $_prefs['ses_limit'];
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _session WHERE userid="'.check($id).'"'));
	if($chk[0] > 0)
	{
		$del = mysql_num_rows(mysql_query('DELETE FROM _session WHERE userid="'.check($id).'"'));
	}
	$_SESSION['sid'] = $did;
	$add =	mysql_query('INSERT INTO _session SET id="'.$did.'", userid="'.check($id).'", log="'.$xtm.'", browser="'.$_SERVER['HTTP_USER_AGENT'].'",
			remember="'.check($rem).'"');
	$update =	mysql_query('UPDATE _users SET lastlogin="'.time().'" WHERE id="'.check($id).'"');
	return $did;
}

function chkses($sid)
{
	global	$_prefs;
	$chk =	mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _session WHERE (log<"'.time().'" AND id="'.check($sid).'") AND remember="0"'));
	$xtm =	time() + $_prefs['ses_limit'];
	$chkd =	mysql_query('DELETE FROM _session WHERE log<"'.time().'" AND remember="0"');
	$re	=	str_replace('&sid='.$sid, '', $_SERVER['QUERY_STRING']);
	if($chk[0] > 0)
	{
		session_destroy();
		header('Location: index.php?ac=lgn&err=1&return='.urlencode($re));
		exit();
	}
	$chk =	mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _session WHERE id="'.check($sid).'"'));
	if(isset($sid) && $chk[0] == 0)
	{
		session_destroy();
		header('Location: index.php?ac=lgn&err=1&return='.urlencode($re));
		exit();
	}
	$chk = mysql_query('UPDATE _session SET log="'.$xtm.'" WHERE id="'.check($sid).'"');
	return $chk;
}

function chklog()
{
	global $_prefs;
	if(isset($_REQUEST['sid']))
	{
		$sid = $_REQUEST['sid'];
	}
	if(isset($_SESSION['sid']))
	{
		$sid = $_SESSION['sid'];
	}
	chkses($sid);
	if(isset($sid) && ($_REQUEST['ac'] == 'lgn' || $_REQUEST['ac'] == 'rgs' || $_REQUEST['ac'] == 'fgp'))
	{
		header('Location: '.$_prefs['selfurl'].'?ac=hme&sid='.$sid);
		exit();
	}
	return $sid;
}

function uphoto($album, $name, $photo)
{
	global $lang, $_prefs, $ses;
	$res = mysql_query('SELECT * FROM _photo WHERE album="'.check($album).'"');
	$alid = mysql_fetch_array($res);
	if(mysql_num_rows($res) == 0)
	{
		$res = mysql_query('SELECT * FROM _photo WHERE userid="'.check($ses['userid']).'" ORDER BY albumid DESC');
		$alid = mysql_fetch_array($res);
		$alid['albumid'] = $alid['albumid']+1;
	}
	if($album == '')
	{
		$msg = $lang['album_required'];
	}
	else if($name == '')
	{
		$msg = $lang['photo_required'];
	}
	else if($photo['name'] == '')
	{
		$msg = $lang['select_photo'];
	}else{
		$var1 = rand(1,99999);
		$var2 = rand(1,99999999999999);
		$var3 = rand(1,999999);
		$var4 = rand(1,9999999);
		$ext = array("gif", "jpg", "jpeg", "png");
		$tff = implode(", ", $ext);
		$tm = time();
		$nfile = $var1.'_'.$var2.'_'.$var3.'_'.$var4.'.'.extformat($photo['name']);
		$lfi  = strtolower($photo['name']);
		if ((preg_match("/php/i", $lfi)) or (preg_match("/.pl/i", $photo['name'])) or ($photo['name'] == ".htaccess"))
		{
			$msg = $lang['error_occur'];
		}
		else if(!in_array(extformat($photo['name']), $ext))
		{
			$msg = sprintf($lang['not_support'], $tff);
		}
		else if($photo['size'] > $_prefs['photo_size'])
		{
			$msg = $lang['file_large'];
		}else{
			if((move_uploaded_file($photo['tmp_name'], "photo/$nfile")) == true)
			{
				$add =	mysql_query('INSERT INTO _photo SET albumid="'.check($alid['albumid']).'", album="'.check($album).'", photo="'.check($name).'", 
						url="'.check($nfile).'", uptm="'.$tm.'", userid="'.check($ses['userid']).'"');
				if($add)
				{
					$msg = $nfile;
				}
			}
		}
	}
	return $msg;
}

function cphoto($album, $name, $photo)
{
	global $lang, $_prefs, $ses;
	if($album == '')
	{
		$msg = $lang['album_required'];
	}
	else if($name == '')
	{
		$msg = $lang['photo_required'];
	}
	else if($photo['name'] == '')
	{
		$msg = $lang['select_photo'];
	}else{
		$var1 = rand(1,99999);
		$var2 = rand(1,99999999999999);
		$var3 = rand(1,999999);
		$var4 = rand(1,9999999);
		$ext = array("gif", "jpg", "jpeg", "png");
		$tff = implode(", ", $ext);
		$tm = time();
		$nfile = $var1.'_'.$var2.'_'.$var3.'_'.$var4.'.'.extformat($photo['name']);
		$lfi  = strtolower($photo['name']);
		if ((preg_match("/php/i", $lfi)) or (preg_match("/.pl/i", $photo['name'])) or ($photo['name'] == ".htaccess"))
		{
			$msg = $lang['error_occur'];
		}
		else if(!in_array(extformat($photo['name']), $ext))
		{
			$msg = sprintf($lang['not_support'], $tff);
		}
		else if($photo['size'] > $_prefs['photo_size'])
		{
			$msg = $lang['file_large'];
		}else{
			if((move_uploaded_file($photo['tmp_name'], "photo/$nfile")) == true)
			{
				$add =	mysql_query('INSERT INTO _photo SET album="'.check($album).'", photo="'.check($name).'", 
						url="'.check($nfile).'", uptm="'.$tm.'", userid="'.check($ses['userid']).'"');
				if($add)
				{
					if($chk[0] < 1)
					{
						$pic 	=	mysql_fetch_array(mysql_query('SELECT id FROM _photo WHERE uptm="'.$tm.'" AND userid="'.check($ses['userid']).'"'));
						$update =	mysql_query('UPDATE _users SET photo="'.$pic[0].'" WHERE id="'.check($ses['userid']).'"');
					}
					$msg = $nfile;
				}
			}
		}
	}
	return $msg;
}

function GetMessageUser($mid)
{
	global $ses;
	$res = mysql_query('SELECT DISTINCT toid FROM _messages WHERE mid="'.check($mid).'"');
	if(mysql_num_rows($res) == 0)
	{
		$result = $mid;
		$users = explode(urldecode(','), $result);
		$resul[$users[0]]['amount'] = count($users);
		$resul[$users[0]]['name'] = getusername($users[0]);
		$resul[$users[1]]['amount'] = count($users) - 2;
		$resul[$users[1]]['name'] = getusername($users[1]);
		if($resul[$users[0]]['amount'] > 0 && count($users) == 1)
		{
			$resul[$users[0]]['amount'] = 0;
		}
		else if($resul[$users[0]]['amount'] > 0 && count($users) == 2)
		{
			$resul[$users[0]]['amount'] = 1;
		}else if($resul[$users[0]]['amount'] > 0 && count($users) > 2)
		{
			$resul[$users[0]]['amount'] = 2;
		}
		if($resul[$users[1]]['amount'] > 0 && count($users) == 3)
		{
			$resul[$users[2]]['name'] = getusername($users[2]);
			$resul[$users[1]]['amount'] = 1;
		}else if($resul[$users[1]]['amount'] > 0 && count($users) > 3)
		{
			$resul[$users[1]]['amount'] = 3;
			$resul[$users[1]]['amoun'] = count($users) - 2;
		}
	}
	else
	{
		$chk = mysql_fetch_array(mysql_query('SELECT DISTINCT fromid FROM _messages WHERE mid="'.check($mid).'"'));
		$ch = mysql_fetch_array(mysql_query('SELECT DISTINCT toid FROM _messages WHERE mid="'.check($mid).'" AND toid="'.$chk[0].'"'));
		if($chk[0] != $ses['userid'] && $ch[0] == 0)
		{
			$result[] = $chk[0];
		}
		while($info = mysql_fetch_array($res))
		{
			if($info['toid'] != $ses['userid'])
			{
				$result[] = $info['toid'];
			}
		}
		$resul[0]['amount'] = count($result);
		$resul[0]['name'] = getusername($result[0]);
		$resul[1]['amount'] = count($result) - 2;
		$resul[1]['name'] = getusername($result[1]);
		if($resul[0]['amount'] > 0 && count($result) == 1)
		{
			$resul[0]['amount'] = 0;
		}
		else if($resul[0]['amount'] > 0 && count($result) == 2)
		{
			$resul[0]['amount'] = 1;
		}else if($resul[0]['amount'] > 0 && count($result) > 2)
		{
			$resul[0]['amount'] = 2;
		}
		if($resul[1]['amount'] > 0 && count($result) == 3)
		{
			$resul[2]['name'] = getusername($result[2]);
			$resul[2]['amount'] = 0;
		}else if($resul[1]['amount'] > 0 && count($result) > 3)
		{
			$resul[1]['amount'] = 3;
			$resul[1]['amoun'] = count($result) - 2;
		}
	}
	return $resul;
}

function GetMessageCount($id, $type = '0')
{
	global $ses;
	$res =	mysql_query('SELECT COUNT(*) FROM _messages WHERE (mid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") OR 
			(toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'")');
	$row =	mysql_fetch_array($res);
	return	$row[0];
}

function GetMessageIDCount($id, $type = '0')
{
	global $ses;
	$res =  mysql_query('SELECT DISTINCT mid FROM _messages WHERE ((toid="'.check($id).'" AND fromuser="'.check($type).'" AND 
			fromid="'.check($ses['userid']).'") OR (toid="'.check($ses['userid']).'" AND fromid="'.check($id).'" AND touser="'.check($type).'")) AND type="0"');
	$row =	mysql_num_rows($res);
	return	$row;
}

function GetMessageID($id, $type = '0')
{
	global $ses;
	$res =  mysql_query('SELECT mid FROM _messages WHERE ((toid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") OR 
			(toid="'.check($ses['userid']).'" AND fromid="'.check($id).'" AND touser="'.check($type).'"))  AND type="0"');
	$row =	mysql_fetch_array($res);
	return	$row[0];
}

function GetMessageList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC', $type = '0')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _messages WHERE (mid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") 
			OR (toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'") GROUP BY sentm ORDER BY sentm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$result[$row['id']] = array(
			'from_name'	=> getusername($row['fromid']),
			'message'		=> bbcode($row['message']),
			'from'		=> $row['fromid'],
			'to'			=> $row['toid'],
			'time'		=> timemsg(time()-$row['sentm']),
			'seen'	=> seenmsg($row['id'])
		);
	}
	return $result;
}

function seenmsg($id)
{
	global $ses;
	$chk =	mysql_fetch_array(mysql_query('SELECT * FROM _messages WHERE id="'.check($id).'" ORDER BY sentm DESC'));
	$inf =	mysql_fetch_array(mysql_query('SELECT DISTINCT uptm FROM _messages WHERE (fromid="'.$chk['fromid'].'" AND toid="'.$chk['toid'].'" OR 
			fromid="'.$chk['toid'].'" AND toid="'.$chk['fromid'].'") ORDER BY uptm DESC'));
	$in =	mysql_fetch_array(mysql_query('SELECT DISTINCT sentm FROM _messages WHERE (fromid="'.$chk['fromid'].'" AND toid="'.$chk['toid'].'" OR 
			fromid="'.$chk['toid'].'" AND toid="'.$chk['fromid'].'") ORDER BY sentm DESC'));
	if($in['sentm'] == $chk['sentm'] && ($chk['toid'] != $ses['userid'] && $chk['sentm'] == $chk['sentm'] && $chk['uptm'] == $inf['uptm']) && $chk['uptm'] != 0)
	return timedate($chk['uptm']);
}

function ComposeMessage($id, $message, $type = '0')
{
	global $ses, $lang;
	$res =  mysql_query('SELECT * FROM _messages WHERE mid="'.check($id).'" AND (fromid="'.check($ses['userid']).'" OR toid="'.check($ses['userid']).'") 
			ORDER BY sentm DESC');
	if(mysql_num_rows($res) < 1)
	{
		$to = $id;
		$usr = explode(urldecode(','), $to);
		for($i=0;$i<count($usr);$i++)
		{
			$usr = $usr[$i];
			if(chkuserid($usr) == false || $id == $ses['userid'])
			{
				$msg = $lang['user_not_found'];
			}
		}
	}else{
		while($chk =  mysql_fetch_array($res))
		{
			if($ses['userid'] != $chk['fromid'])
			{
				$to = $chk['fromid'];
			}else if($ses['userid'] != $chk['toid'])
			{
				$to = $chk['toid'];
			}
			if(chkuserid($to) == false || $to == $ses['userid'])
			{
				$msg = $lang['user_not_found'];
			}
		}
	}
	$min = time()-60;
	$key = GenerateRandomKey('message');
	if($message == '')
	{
		$msg = $lang['message_empty'];
	}else{
		if(mysql_num_rows($res) == 0)
		{
			$to = explode(urldecode(','), $to);
			if(count($to) > 1)
			{
				$amo = 1;
			}
			for($i=0;$i<count($to);$i++)
			{
				$res =  mysql_query('INSERT INTO _messages SET mid="'.$key.'", fromid="'.check($ses['userid']).'", toid="'.check($to[$i]).'", sentm="'.time().'", message="'.check($message).'", type="'.$amo.'"');
			}
			if($res)
			{
				header('Location: index.php?ac=msg&sid='.$ses['id']);
				exit();
			}
		}
		else
		{
			$res =  mysql_query('SELECT DISTINCT mid FROM _messages WHERE mid="'.check($id).'" ORDER BY sentm DESC');
			while($chk =  mysql_fetch_array($res))
			{
				$chk = minfo($chk['mid']);
				if($ses['userid'] != $chk['fromid'])
				{
					$to =  mysql_query('INSERT INTO _messages SET mid="'.$chk['mid'].'", fromid="'.check($ses['userid']).'", toid="'.$chk['fromid'].'", sentm="'.time().'", message="'.check($message).'", type="'.$chk['type'].'"');
				}
				if($ses['userid'] != $chk['toid'])
				{
					$to =  mysql_query('INSERT INTO _messages SET mid="'.$chk['mid'].'", fromid="'.check($ses['userid']).'", toid="'.$chk['toid'].'", sentm="'.time().'", message="'.check($message).'", type="'.$chk['type'].'"');
				}
			}
				$msg = 1;
		}
	}
	return $msg;
}

function viewmessage($mid)
{
	global $ses, $_prefs;
	$chk =	mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _messages WHERE mid="'.check($mid).'" AND toid="'.check($ses['userid']).'" AND uptm=0'));
	if($chk[0] > 0)
	{
		$res = mysql_query('UPDATE _messages SET uptm="'.time().'" WHERE mid="'.check($mid).'" AND toid="'.check($ses['userid']).'"');
		if($res)
		{
			header('location: '.$_prefs['selfurl'].'?ac=msg&mid='.$mid.'&sid='.$ses['id']);
			exit();
		}
	}
}

function viewnotification()
{
	global $ses;
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _notify WHERE userid="'.check($ses['userid']).'" AND uptm=0'));
	if($chk[0] > 0)
	{
		$res = mysql_query('UPDATE _notify SET uptm="'.time().'" WHERE userid="'.check($ses['userid']).'" AND uptm=0');
		if($res)
		{
			header('location: '.$_prefs['selfurl'].'?ac=nfc&sid='.$ses['id']);
			exit();
		}
	}
}

function GetLastMessage($id, $type = '0')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _messages WHERE (toid="'.check($ses['userid']).'" AND touser="'.check($type).'" AND mid="'.check($id).'") OR 
			(fromid="'.check($ses['userid']).'" AND fromuser="'.check($type).'" AND mid="'.check($id).'") ORDER BY sentm DESC');
	$re = mysql_fetch_array($res);
	return $re;
}

function GetLastMess($id, $type = '0')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _messages WHERE toid="'.check($ses['userid']).'" AND touser="'.check($type).'" AND mid="'.check($id).'" ORDER BY 
			sentm DESC');
	$re = mysql_fetch_array($res);
	if(!isset($re['uptm']))
	{
		$re['uptm'] = 1;
	}
	return $re;
}

function GetUnreadCount($type = '0')
{
	global $ses;
	$res =  mysql_query('SELECT COUNT(DISTINCT mid) FROM _messages WHERE toid="'.check($ses['userid']).'" AND touser="'.check($type).'" AND uptm=0 ORDER BY sentm DESC');
	$row =  mysql_fetch_array($res);
	return $row[0];
}

function GetInboxCount($type = '0')
{
	global $ses;
	$res =  mysql_query('SELECT COUNT(DISTINCT mid) FROM _messages WHERE (toid="'.check($ses['userid']).'" AND touser="'.check($type).'" 
			OR fromid="'.check($ses['userid']).'" AND fromuser="'.check($type).'")');
	$row =  mysql_fetch_array($res);
	return $row[0];
}

function minfo($mid)
{
	global $ses;
	$result =	mysql_fetch_array(mysql_query('SELECT * FROM _messages  WHERE mid="'.$mid.'" ORDER BY id DESC'));
	return $result;
}

function GetInboxList($page = 1, $PerPage = -1, $sortBy = 'DESC', $type = '0')
{
	global $ses;
	$res =  mysql_query('SELECT DISTINCT mid FROM _messages WHERE (toid="'.check($ses['userid']).'" AND touser="'.check($type).'" OR 
			fromid="'.check($ses['userid']).'" AND fromuser="'.check($type).'") ORDER BY id 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$row = minfo($row['mid']);
		$inf = GetMessageUser($row['mid']);
		if($inf[1]['name'])
		{
			$inf[1]['name'] = ', '.$inf[1]['name'];
		}
		if($inf[2]['name'])
		{
			$inf[2]['name'] = ', '.$inf[2]['name'];
		}
		$group = GetLastMessage($row['mid'], $type);
		$gru = GetLastMess($row['mid'], $type);
		$result[$row['id']] = array(
			'from_name'	=> $inf[0]['name'].$inf[1]['name'].$inf[2]['name'],
			'message'		=> bbcode($group['message']),
			'from'		=> $row['toid'],
			'to'			=> $row['fromid'],
			'mid'			=> $row['mid'],
			'time'		=> timemsg(time()-$group['sentm']),
			'uptm' => $gru['uptm']
		);
	}
	return $result;
}

function UpdateProfilePhoto($id)
{
	global $ses;
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _photo WHERE id="'.check($id).'" AND userid="'.check($ses['userid']).'"'));
	if($chk[0] > 0)
	{
		$res = mysql_query('UPDATE _users SET photo="'.check($id).'" WHERE id="'.check($ses['userid']).'"');
		if($res)
		{
			header('Location: index.php?ac=prf&id='.$ses['userid'].'&sid='.$ses['id']);
			exit();
		}
	}
}

function UpdateAlbumPhoto($id)
{
	global $ses;
	$chk = mysql_fetch_array(mysql_query('SELECT * FROM _photo WHERE id="'.check($id).'" AND userid="'.check($ses['userid']).'"'));
	if($chk[0] > 0)
	{
		$res = mysql_query('UPDATE _photo SET cover="'.check($id).'" WHERE albumid="'.$chk['albumid'].'" AND userid="'.check($ses['userid']).'"');
		if($res)
		{
			header('Location: index.php?ac=pho&id='.$ses['userid'].'&sid='.$ses['id']);
			exit();
		}
	}
}

function GetNotifyUser($nid)
{
	global $ses;
	$res = mysql_query('SELECT DISTINCT fid FROM _notify WHERE nid="'.check($nid).'" AND userid="'.check($ses['userid']).'" ORDER BY dtm DESC');
	while($info = mysql_fetch_array($res))
	{
		$result[] = $info['fid'];
	}
	$resul[0]['amount'] = count($result);
	$resul[0]['name'] = getusername($result[0]);
	$resul[0]['id'] = $result[0];
	$resul[1]['amount'] = count($result) - 2;
	$resul[1]['name'] = getusername($result[1]);
	$resul[1]['id'] = $result[1];
	if($resul[0]['amount'] > 0 && count($result) == 1)
	{
		$resul[0]['amount'] = 0;
	}
	else if($resul[0]['amount'] > 0 && count($result) == 2)
	{
		$resul[0]['amount'] = 1;
	}else if($resul[0]['amount'] > 0 && count($result) > 2)
	{
		$resul[0]['amount'] = 2;
	}
	if($resul[1]['amount'] > 0 && count($result) == 3)
	{
		$resul[2]['name'] = getusername($result[2]);
		$resul[2]['id'] = $result[2];
		$resul[2]['amount'] = 0;
	}else if($resul[1]['amount'] > 0 && count($result) > 3)
	{
		$resul[1]['amount'] = 3;
		$resul[1]['amoun'] = count($result) - 2;
	}
	return $resul;
}

function whonotify($id)
{
	$chk = mysql_fetch_array(mysql_query('SELECT * FROM _notify WHERE id="'.check($id).'"'));
	if($chk['wid'] > 0)
	{
		$result = mysql_fetch_array(mysql_query('SELECT userid FROM _story WHERE id="'.check($chk['wid']).'"'));
	}
	if($chk['pid'] > 0)
	{
		$result = mysql_fetch_array(mysql_query('SELECT userid FROM _photo WHERE id="'.check($chk['pid']).'"'));
	}
	if($chk['alid'] > 0)
	{
		$result = mysql_fetch_array(mysql_query('SELECT userid FROM _photo WHERE albumid="'.check($chk['alid']).'"'));
	}
	return $result[0];
}

function notify($userid = 0, $wid = 0, $cid = 0, $pid = 0, $alid = 0, $do = 0)
{
	global $ses;
	$key = GenerateRandomKey('notify');
	$nid = mysql_fetch_array(mysql_query('SELECT nid FROM _notify WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND pid="'.check($pid).'" AND 
			alid="'.check($alid).'" AND ac="'.check($do).'"'));
	if(strlen($nid[0]) > 0)
	{
		$res = mysql_query('INSERT INTO _notify SET userid="'.check($userid).'", nid="'.$nid[0].'", fid="'.check($ses['userid']).'", wid="'.check($wid).'", 
				cid="'.check($cid).'", pid="'.check($pid).'", alid="'.check($alid).'", ac="'.check($do).'", dtm="'.time().'"');
	}
	else
	{
		$res = mysql_query('INSERT INTO _notify SET userid="'.check($userid).'", nid="'.$key.'", fid="'.check($ses['userid']).'", wid="'.check($wid).'", 
				cid="'.check($cid).'", pid="'.check($pid).'", alid="'.check($alid).'", ac="'.check($do).'", dtm="'.time().'"');
	}
	return $res;
}

function NotificationCount()
{
	global $ses;
	$result =	mysql_fetch_array(mysql_query('SELECT COUNT(DISTINCT nid) FROM _notify WHERE userid="'.check($ses['userid']).'"'));
	return $result[0];
}

function ninfo($nid)
{
	global $ses;
	$result =	mysql_fetch_array(mysql_query('SELECT * FROM _notify  WHERE userid="'.check($ses['userid']).'" AND nid="'.$nid.'" ORDER BY id DESC'));
	return $result;
}

function GetNotificationList($page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res = mysql_query('SELECT DISTINCT nid FROM _notify WHERE userid="'.check($ses['userid']).'" ORDER BY id 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$row = ninfo($row['nid']);
		$inf = GetNotifyUser($row['nid']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'fromname' => $inf[0]['name'],
			'fromname1' => $inf[1]['name'],
			'fromname2' => $inf[2]['name'],
			'who' => whonotify($row['id']),
			'whoname' => getusername(whonotify($row['id'])),
			'amount' => $inf[0]['amount'],
			'amoun' => $inf[1]['amoun'],
			'from' => $inf[0]['id'],
			'from1' => $inf[1]['id'],
			'from2' => $inf[2]['id'],
			'wid' => $row['wid'],
			'cid' => $row['cid'],
			'pid' => $row['pid'],
			'alid' => $row['alid'],
			'do' => $row['ac'],
			'uptm' => $row['uptm'],
			'photo' => getsetphoto($row['userid']),
			'dtm' => timemsg(time()-$row['dtm'])
		);
	}
	return $result;
}

function GoNotifyID($id)
{
	global $ses, $_prefs;
	$res = mysql_query('SELECT * FROM _notify WHERE id="'.check($id).'" AND userid="'.check($ses['userid']).'"');
	$r = mysql_fetch_array($res);
	if(mysql_num_rows($res) > 0)
	{
		$re = mysql_query('UPDATE _notify SET uptm="'.time().'" WHERE userid="'.check($ses['userid']).'" AND nid="'.check($r['nid']).'"');
		if($re)
		{
			if($r['ac'] == 4 || $r['ac'] == 3)
			{
				$ac = 'prf';
				if($r['ac'] == 3)
				{
					$wh = '&id='.$r['userid'];
				}
				else
				{
					$wh = '&id='.$r['fid']; 
				}
			}
			if($r['wid'] > 0)
			{
				$ac = 'cmt';
				$wh = '&stid='.$r['wid'];
			}
			if($r['pid'] > 0 || $r['alid'] > 0)
			{
				$ac = 'pho';
				if($r['pid'] > 0)
				{
					$wh = '&pid='.$r['pid'];
				}
				else if($r['alid'] > 0)
				{
					$wh = '&alid='.$r['alid'];
				}
				else if($r['pid'] > 0 && $r['alid'] > 0)
				{
					$wh = '&alid='.$r['alid'].'&pid='.$r['pid'];
				}
			}
			header('location: '.$_prefs['selfurl'].'?ac='.$ac.$wh.'&sid='.$ses['id']);
			exit();
		}
	}
}

function GetNotifyList($sortBy = 'DESC')
{
	global $ses;
	$res = mysql_query('SELECT DISTINCT nid FROM _notify WHERE userid="'.check($ses['userid']).'" AND uptm=0 ORDER BY id 
			'.$sortBy.' LIMIT 2');
	while($row = mysql_fetch_array($res))
	{
		$row = ninfo($row['nid']);
		$inf = GetNotifyUser($row['nid']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'fromname' => $inf[0]['name'],
			'fromname1' => $inf[1]['name'],
			'fromname2' => $inf[2]['name'],
			'who' => whonotify($row['id']),
			'whoname' => getusername(whonotify($row['id'])),
			'amount' => $inf[0]['amount'],
			'amoun' => $inf[1]['amoun'],
			'from' => $inf[0]['id'],
			'from1' => $inf[1]['id'],
			'from2' => $inf[2]['id'],
			'wid' => $row['wid'],
			'cid' => $row['cid'],
			'pid' => $row['pid'],
			'alid' => $row['alid'],
			'do' => $row['ac'],
			'uptm' => $row['uptm'],
			'photo' => getsetphoto($row['userid']),
			'dtm' => timemsg(time()-$row['dtm'])
		);
	}
	return $result;
}

function FriendRequestCount()
{
	global $ses;
	$chk =	mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _friends WHERE toid="'.check($ses['userid']).'" AND accdate=0'));
	return $chk[0];
}

function FriendRequestList($sortBy = 'DESC')
{
	global $ses;
	$res =  mysql_query('SELECT * FROM _friends WHERE toid="'.check($ses['userid']).'" AND accdate=0 ORDER BY reqdate '.$sortBy.' LIMIT 2');
	while($row = mysql_fetch_array($res))
	{
		if($row['fromid'] != $ses['userid'])
		{
			$from = $row['fromid'];
		}
		$result[$row['id']] = array(
			'user'	=> getusername($from),
			'userid'=> $from
		);
	}
	return $result;
}

function SendFriend($id)
{
	global $ses;
	if(chkuserid($id)==FALSE || $ses['userid'] == $id)
	{
		return false;
	}
	else
	{
		$chk =	mysql_fetch_array(mysql_query('SELECT * FROM _friends WHERE (toid="'.check($id).'" AND fromid="'.check($ses['userid']).'") 
				OR (toid="'.check($ses['userid']).'" AND fromid="'.check($id).'")'));
		if($chk['accdate'] == 0 && $chk['toid'] == $ses['userid'])
		{
			$update = mysql_query('UPDATE _friends SET accdate="'.time().'" WHERE id="'.$chk[0].'"');
			notify($chk['fromid'], 0, 0, 0, 0, 4);
			if($update)
			{
				header('Location: index.php?ac=prf&id='.$id.'&sid='.$ses['id']);
				exit();
			}
		}
		else if($chk['accdate'] > 0)
		{
			$del = mysql_query('DELETE FROM _friends WHERE id="'.$chk[0].'"');
			if($del)
			{
				header('Location: index.php?ac=prf&id='.$id.'&sid='.$ses['id']);
				exit();
			}
		}
		else if($chk['accdate'] == 0 && $chk['fromid'] == $ses['userid'])
		{
			$del = mysql_query('DELETE FROM _friends WHERE id="'.$chk[0].'"');
			if($del)
			{
				header('Location: index.php?ac=prf&id='.$id.'&sid='.$ses['id']);
				exit();
			}
		}
		else
		{
			$res = mysql_query('INSERT INTO _friends SET toid="'.check($id).'", fromid="'.check($ses['userid']).'", reqdate="'.time().'"');
			if($res)
			{
				header('Location: index.php?ac=prf&id='.$id.'&sid='.$ses['id']);
				exit();
			}
		}
	}
}

function AddToWall($id, $msg, $shrid = 0, $grid = 0)
{
	global $ses;
	$uid = $id;
	if(!isset($id))
	{
		$id = $ses['userid'];
	}
	$ins = 	mysql_query('INSERT INTO _story SET userid="'.check($ses['userid']).'", toid="'.check($id).'", shrid="'.check($shrid).'", 
			grid="'.check($grid).'", message="'.check($msg).'", dtm="'.time().'", brws="'.cutbrws().'", ip="'.ip2long(getip()).'"');
	if($uid > 0 && $uid != $ses['userid'])
	{
		notify($id, 0, 0, 0, 0, 3);
	}
	if($ins)
	{
		return true;
	}
}

function AddToLike($wid = 0, $cid = 0, $alid = 0, $pid = 0)
{
	global $ses;
	$chk =  mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _like WHERE userid="'.check($ses['userid']).'" AND wid="'.check($wid).'" AND 
			cid="'.check($cid).'" AND alid="'.check($alid).'" AND pid="'.check($pid).'"'));
	if($chk[0] > 0)
	{
		$ins = mysql_query('DELETE FROM _like WHERE userid="'.check($ses['userid']).'" AND wid="'.check($wid).'" AND 
				cid="'.check($cid).'" AND alid="'.check($alid).'" AND pid="'.check($pid).'"');
	}
	else
	{
		$ins = 	mysql_query('INSERT INTO _like SET userid="'.check($ses['userid']).'", wid="'.check($wid).'", cid="'.check($cid).'", alid="'.check($alid).'", 
				pid="'.check($pid).'", dtm="'.time().'"');
		if($wid > 0)
		{
			$res = mysql_query('SELECT userid FROM _story WHERE id="'.check($wid).'"');
		}
		if($alid > 0)
		{
			$res = mysql_query('SELECT userid FROM _photo WHERE albumid="'.check($alid).'"');
		}
		if($pid > 0)
		{
			$res = mysql_query('SELECT userid FROM _photo WHERE id="'.check($pid).'"');
		}
		if($cid > 0)
		{
			 $res = mysql_query('SELECT userid FROM _comment WHERE id="'.check($cid).'"'); 
		}
		$user = mysql_fetch_array($res);
		if($user[0] != $ses['userid'])
		{
			notify($user[0], $wid, $cid, $pid, $alid, 0);
		}
	}
	if($ins)
	{
		return true;
	}
}

function AddComment($stid = 0, $alid = 0, $pid = 0, $msg)
{
	global $ses;
	$ins = 	mysql_query('INSERT INTO _comment SET userid="'.check($ses['userid']).'", stid="'.check($stid).'", alid="'.check($alid).'", pid="'.check($pid).'", 
			message="'.check($msg).'", dtm="'.time().'", brws="'.cutbrws().'", ip="'.ip2long(getip()).'"');
	if($ins)
	{
		return true;
	}
}

function GetLikeUser($wid = 0, $cid = 0, $alid = 0, $pid = 0)
{
	global $ses;
	$res = mysql_query('SELECT a.id, a.userid, a.wid, a.cid, a.alid, a.pid FROM _like a INNER JOIN _friends b ON (a.userid=b.toid) OR (a.userid=b.fromid) 
	 		WHERE (a.wid="'.check($wid).'" AND a.cid="'.check($cid).'" AND a.alid="'.check($alid).'" AND a.pid="'.check($pid).'" AND b.accdate>0) 
			AND (b.toid="'.check($ses['userid']).'" OR b.fromid="'.check($ses['userid']).'") GROUP BY 1,2');
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(DISTINCT userid) FROM _like WHERE userid="'.check($ses['userid']).'" AND (wid="'.check($wid).'" 
			AND cid="'.check($cid).'" AND alid="'.check($alid).'" AND pid="'.check($pid).'")'));
	if($chk[0] > 0)
	{
		$result[] = $ses['userid'];
	}
	while($info = mysql_fetch_array($res))
	{
		if($info['userid'] != $ses['userid'])
		{
			$result[] = $info['userid'];
		}
	}
	$cou = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _like WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND alid="'.check($alid).'" 
				AND pid="'.check($pid).'"'));
	if(count($result) == 0 && $cou[0] > 0)
	{
		$res = mysql_query('SELECT * FROM _like WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND alid="'.check($alid).'" 
				AND pid="'.check($pid).'"');
		while($row = mysql_fetch_array($res))
		{
			$result[] = $row['userid'];
		}
	}
	else if(count($result) > 0 && $cou[0] > 1)
	{
		$res = mysql_query('SELECT * FROM _like WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND alid="'.check($alid).'" 
				AND pid="'.check($pid).'" GROUP BY userid');
		while($row = mysql_fetch_array($res))
		{
			if($result[0] != $row['userid'] && $result[1] != $row['userid'] && $result[2] != $row['userid'])
			{
				$result[] = $row['userid'];
			}
		}
	}
	$resul[0]['amount'] = count($result);
	$resul[0]['name'] = getusername($result[0]);
	$resul[0]['userid'] = $result[0];
	$resul[1]['amount'] = count($result) - 2;
	$resul[1]['name'] = getusername($result[1]);
	$resul[1]['userid'] = $result[1];
	if($resul[0]['amount'] > 0 && count($result) == 1)
	{
		$resul[0]['amount'] = 0;
	}
	else if($resul[0]['amount'] > 0 && count($result) == 2)
	{
		$resul[0]['amount'] = 1;
	}else if($resul[0]['amount'] > 0 && count($result) > 2)
	{
		$resul[0]['amount'] = 2;
	}
	if($resul[1]['amount'] > 0 && count($result) == 3)
	{
		$resul[2]['name'] = getusername($result[2]);
		$resul[2]['userid'] = $result[2];
		$resul[2]['amount'] = 0;
	}else if($resul[1]['amount'] > 0 && count($result) > 3)
	{
		$resul[1]['amount'] = 3;
		$resul[1]['amoun'] = count($result) - 2;
	}
	return $resul;
}

function GetLikeCount($wid = 0, $cid = 0, $alid = 0, $pid = 0)
{
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _like WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND alid="'.check($alid).'" 
			AND pid="'.check($pid).'"'));
	$res = $chk[0];
	return $res;
}

function GetLikeList($wid = 0, $cid = 0, $alid = 0, $pid = 0, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	$res = mysql_query('SELECT * FROM _like WHERE wid="'.check($wid).'" AND cid="'.check($cid).'" AND alid="'.check($alid).'"
			AND pid="'.check($pid).'" ORDER BY id '.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'photo' => getsetphoto($row['userid']),
			'dtm' => timemsg(time()-$row['dtm'])
		);
	}
	return $result;
}

function GetULikeCount($wid = 0, $cid = 0, $alid = 0, $pid = 0)
{
	global $ses;
	$chk = 	mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _like WHERE userid="'.check($ses['userid']).'" AND wid="'.check($wid).'" 
			AND cid="'.check($cid).'" AND alid="'.check($alid).'" AND pid="'.check($pid).'"'));
	$res = $chk[0];
	return $res;
}

function GetCommentCount($stid = 0, $alid = 0, $pid = 0)
{
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _comment WHERE stid="'.check($stid).'" AND alid="'.check($alid).'" 
			AND pid="'.check($pid).'"'));
	$res = $chk[0];
	return $res;
}

function GetCommentList($stid = 0, $alid = 0, $pid = 0, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _comment WHERE stid="'.check($stid).'" AND alid="'.check($alid).'" AND pid="'.check($pid).'" ORDER BY id 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		if($stid > 0)
		{
			$x = $stid;
			$xx = $row['id'];
			$xxx = 0;
			$xxxx = 0;
		}
		if($alid > 0)
		{
			$x = 0;
			$xx = $row['id'];
			$xxx = $alid;
			$xxxx = 0;
		}
		if($pid > 0)
		{
			$x = 0;
			$xx = $row['id'];
			$xxx = 0;
			$xxxx = $pid;
		}
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'toid' => $row['toid'],
			'message' => bbcode($row['message']),
			'toname'	=> getusername($row['toid']),
			'like' => GetLikeCount($x, $xx, $xxx),
			'ulike' => GetULikeCount($x, $xx, $xxx, $xxxx),
			'dtm' => timemsg(time()-$row['dtm']),
			'browser' => $row['brws'],
			'ip' => $row['ip']
		);
	}
	return $result;
}

function GetGroupWallCount($id)
{
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _story WHERE grid="'.check($id).'"'));
	return $chk[0];
}

function GetGroupWallList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _story WHERE grid="'.check($id).'" ORDER BY dtm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$share = GetWallShare($row['shrid']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'toid' => $row['toid'],
			'message' => bbcode($row['message']),
			'toname'	=> getusername($row['toid']),
			'shrid'	=> $row['shrid'],
			'suser' => getusername($share['userid']),
			'suserid' => $share['userid'],
			'like' => GetLikeCount($row['id']),
			'ulike' => GetULikeCount($row['id']),
			'smessage' => bbcode($share['message']),
			'comment' => GetCommentCount($row['id']),
			'dtm' => timemsg(time()-$row['dtm']),
			'browser' => $row['brws'],
			'ip' => $row['ip']
		);
	}
	return $result;
}

function GetWallCount($id)
{
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _story WHERE toid="'.check($id).'"'));
	return $chk[0];
}

function GetWallList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _story WHERE toid="'.check($id).'" ORDER BY dtm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$share = GetWallShare($row['shrid']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['userid']),
			'userid' => $row['userid'],
			'toid' => $row['toid'],
			'message' => bbcode($row['message']),
			'toname'	=> getusername($row['toid']),
			'shrid'	=> $row['shrid'],
			'suser' => getusername($share['userid']),
			'suserid' => $share['userid'],
			'like' => GetLikeCount($row['id']),
			'ulike' => GetULikeCount($row['id']),
			'smessage' => bbcode($share['message']),
			'comment' => GetCommentCount($row['id']),
			'dtm' => timemsg(time()-$row['dtm']),
			'browser' => $row['brws'],
			'ip' => $row['ip']
		);
	}
	return $result;
}

function GetFeedCount()
{
	global $ses;
	 $sql = mysql_query('SELECT a.id, a.userid, a.toid, a.dtm, a.message FROM _story a INNER JOIN _friends b ON (a.userid=b.toid) OR (a.userid=b.fromid) 
	 		WHERE (b.toid="'.check($ses['userid']).'" OR b.fromid="'.check($ses['userid']).'") AND b.accdate>0 GROUP BY 1,2');
	$chk = mysql_num_rows($sql);
	if($chk == 0)
	{
		$chk = GetWallCount($ses['userid']);
	}
	return $chk;
}

function GetFeedList($page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$sql = mysql_query('SELECT a.id, a.userid, a.toid, a.dtm, a.message FROM _story a INNER JOIN _friends b ON (a.userid=b.toid) OR (a.userid=b.fromid) 
	 		WHERE (b.toid="'.check($ses['userid']).'" OR b.fromid="'.check($ses['userid']).'") AND b.accdate>0 GROUP BY 1,2');
	$chk = mysql_num_rows($sql);
	if($chk > 0)
	{
		$res =  mysql_query('SELECT a.id, a.userid, a.toid, a.shrid, a.grid, a.dtm, a.message, a.brws, a.ip FROM _story a INNER JOIN _friends b ON 
				(a.userid=b.toid) OR (a.userid=b.fromid) WHERE (b.toid="'.check($ses['userid']).'" OR b.fromid="'.check($ses['userid']).'") AND b.accdate>0 
				GROUP BY 1,2 ORDER BY a.dtm '.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
		while($row = mysql_fetch_array($res))
		{
			$share = GetWallShare($row['shrid']);
			$group = getgroupinfo($row['grid']);
			$result[$row['id']] = array(
				'username'	=> getusername($row['userid']),
				'userid' => $row['userid'],
				'toid' => $row['toid'],
				'grid' => $row['grid'],
				'grname' => $group['grp'],
				'message' => bbcode($row['message']),
				'toname'	=> getusername($row['toid']),
				'shrid'	=> $row['shrid'],
				'suser' => getusername($share['userid']),
				'suserid' => $share['userid'],
				'like' => GetLikeCount($row['id']),
				'ulike' => GetULikeCount($row['id']),
				'smessage' => bbcode($share['message']),
				'comment' => GetCommentCount($row['id']),
				'dtm' => timemsg(time()-$row['dtm']),
				'browser' => $row['brws'],
				'ip' => $row['ip']
			);
		}
	}
	else
	{
		$result = GetWallList($ses['userid'], $page, $PerPage, $sortBy);
	}
	return $result;
}

function GetStoryInfo($id)
{
	$row = mysql_fetch_array(mysql_query('SELECT * FROM _story WHERE id="'.check($id).'"'));
	$share = GetWallShare($row['shrid']);
	$group = getgroupinfo($row['grid']);
	$result = array(
		'username' => getusername($row['userid']),
		'userid' => $row['userid'],
		'toid' => $row['toid'],
		'grid' => $row['grid'],
		'grname' => $group['grp'],
			'message' => bbcode($row['message']),
			'toname'	=> getusername($row['toid']),
			'shrid'	=> $row['shrid'],
			'suser' => getusername($share['userid']),
			'suserid' => $share['userid'],
			'smessage' => bbcode($share['message']),
			'comment' => GetCommentCount($row['id']),
			'like' => GetLikeCount($row['id']),
			'ulike' => GetULikeCount($row['id']),
			'dtm' => timemsg(time()-$row['dtm']),
			'browser' => $row['brws'],
			'ip' => $row['ip']
		);
	return $result;
}

function GetWallShare($id)
{
	$res = mysql_fetch_array(mysql_query('SELECT * FROM _story WHERE id="'.check($id).'"'));
	return $res;
}

function FriendCount($fid, $q)
{
	global $ses;
	$chk = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _friends a INNER JOIN _users b ON (b.id=a.toid) OR (b.id=a.fromid) 
			WHERE ((a.toid="'.check($fid).'" AND a.fromid=b.id OR a.fromid="'.check($fid).'" AND a.toid=b.id) AND a.accdate>0) AND 
			b.id!="'.check($ses['userid']).'" AND b.username LIKE "%'.check($q).'%"'));
	return $chk[0];
}

function GetFriendList($fid, $q,  $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT a.toid, a.fromid FROM _friends a INNER JOIN _users b ON (b.id=a.toid) OR (b.id=a.fromid) 
			WHERE ((a.toid="'.check($fid).'" AND a.fromid=b.id OR a.fromid="'.check($fid).'" AND a.toid=b.id) AND a.accdate>0) AND 
			b.id!="'.check($ses['userid']).'" AND b.username LIKE "%'.check($q).'%" ORDER BY b.lastlogin 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		if($row['toid'] != $ses['userid'])
		{
			$inf = $row['toid'];
		}
		if($row['fromid'] != $ses['userid'])
		{
			$inf = $row['fromid'];
		}
		$in = getuserinfo($inf);
		$result[$inf] = array(				
			'username'	=> getusername($inf),
			'photo' => $in['photo'],
			'url' => getsetphoto($inf),
			'friend' => CheckFriend($inf)
		);
	}
	return $result;
}

function CheckFriend($id)
{
	global $ses;
	$chk =	mysql_fetch_array(mysql_query('SELECT * FROM _friends WHERE (toid="'.check($id).'" 
			AND fromid="'.check($ses['userid']).'") OR (toid="'.check($ses['userid']).'" AND fromid="'.check($id).'")'));
	$result = 0;
	if($chk['toid']==$ses['userid'] && $chk['accdate'] == 0)
	{
		$result = 1;
	}
	else if($chk['fromid']==$ses['userid'] && $chk['accdate'] == 0)
	{
		$result = 2;
	}
	else if($chk[0] > 0 && $chk['accdate'] > 0)
	{
		$result = 3;
	}
	return $result;
}

function GetComposeCount($q)
{
	global $ses;
	$res = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _friends a INNER JOIN _users b ON (b.id=a.toid) OR (b.id=a.fromid) 
			WHERE ((a.toid="'.check($ses['userid']).'" AND a.fromid=b.id OR a.fromid="'.check($ses['userid']).'" AND a.toid=b.id) AND a.accdate>0) 
			AND b.username LIKE "%'.check($q).'%"'));
	return $res[0];
}

function GetComposeList($q,  $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res = mysql_query('SELECT b.id FROM _friends a INNER JOIN _users b ON (b.id=a.toid) OR (b.id=a.fromid) 
			WHERE ((a.toid="'.check($ses['userid']).'" AND a.fromid=b.id OR a.fromid="'.check($ses['userid']).'" AND a.toid=b.id) AND a.accdate>0) 
			AND b.username LIKE "%'.check($q).'%" ORDER BY RAND() 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$info = getuserinfo($row['id']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['id']),
			'url' => getsetphoto($row['id']),
			'photo' => $info['photo'],
			'friend' => CheckFriend($row['id'])
		);
	}
	return $result;
}

function GetOnlineCount($q, $typ = 2)
{
	global $ses;
	$tme = time();
	$res = mysql_query('SELECT a.userid, a.log FROM _session a INNER JOIN _users b ON (a.userid=b.id) 
	 		WHERE b.username LIKE "%'.check($q).'%" AND a.userid!="'.check($ses['userid']).'" AND a.log>"'.$tme.'" GROUP BY 1,2');
	if($typ == 2)
	{
		while($row = mysql_fetch_array($res))
		{
			if(CheckFriend($row[0]) == 3)
			{
				$ro[] = $row[0];
			}
		}
		$row = count($ro);
	}
	else if($typ == 1)
	{
		$row = mysql_num_rows($res);
	}
	return $row;
}

function GetOnlineList($q, $typ = 2,  $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT a.userid, a.log FROM _session a INNER JOIN _users b ON (a.userid=b.id) 
	 		WHERE b.username LIKE "%'.check($q).'%" AND a.userid!="'.check($ses['userid']).'" AND a.log>"'.$tme.'" GROUP BY 1,2 ORDER BY a.log 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		if($typ == 2 && CheckFriend($row['userid']) == 3)
		{
		
			$result[$row['userid']] = array(
				'username'	=> getusername($row['userid']),
				'photo' => getsetphoto($row['userid']),
				'friend' => CheckFriend($row['userid'])
			);
		}
		else if($typ == 1)
		{
			$result[$row['userid']] = array(
				'username'	=> getusername($row['userid']),
				'photo' => getsetphoto($row['userid']),
				'friend' => CheckFriend($row['userid'])
			);
		}
	}
	return $result;
}

function GetInboxSearchCount($q, $type)
{
	global $ses;
	$res =	mysql_query('SELECT COUNT(DISTINCT mid) FROM _messages WHERE (toid="'.check($ses['userid']).'" AND touser="'.check($type).'" 
			OR fromid="'.check($ses['userid']).'" AND fromuser="'.check($type).'") AND message LIKE "%'.check($q).'%"');
	$row = mysql_fetch_array($res);
	return $row[0];
}

function GetInboxSearchList($q, $page = 1, $PerPage = -1, $sortBy = 'DESC', $type)
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _messages WHERE (toid="'.check($ses['userid']).'" AND touser="'.check($type).'" OR fromid="'.check($ses['userid']).'" 
			AND fromuser="'.check($type).'") AND message LIKE "%'.check($q).'%" GROUP BY mid ORDER BY sentm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$inf = GetMessageUser($row['mid']);
		if($inf[1]['name'])
		{
			$inf[1]['name'] = ', '.$inf[1]['name'];
		}
		if($inf[2]['name'])
		{
			$inf[2]['name'] = ', '.$inf[2]['name'];
		}
		$group = GetLastMessage($row['mid'], $type);
		$gru = GetLastMess($row['mid'], $type);
		$result[$row['id']] = array(
			'from_name'	=> $inf[0]['name'].$inf[1]['name'].$inf[2]['name'],
			'message'		=> bbcode($row['message']),
			'from'		=> $row['toid'],
			'to'			=> $row['fromid'],
			'mid'			=> $row['mid'],
			'time'		=> timemsg(time()-$group['sentm']),
			'uptm' => $gru['uptm']
		);
	}
	return $result;
}

function AlbumInfo($id)
{
	$row = mysql_fetch_array(mysql_query('SELECT * FROM _photo WHERE albumid="'.check($id).'"'));
	$result = array(
			'username' => getusername($row['userid']),
			'userid' => $row['userid'],
			'photo' => $row['photo'],
			'url' => $row['url'],
			'cover' => $row['cover'],
			'album' => $row['album'],
			'like' => GetLikeCount(0, 0, $row['albumid']),
			'ulike' => GetULikeCount(0, 0, $row['albumid']),
			'uptm' => timemsg(time()-$row['uptm'])
		);
	return $result;
}

function GetAlbumPhotoCount($id)
{
	$res = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _photo WHERE albumid="'.check($id).'"'));
	return $res[0];
}

function GetAlbumPhotoList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _photo WHERE albumid="'.check($id).'" ORDER BY uptm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$result[$row['id']] = array(
				'cover'		=> $url['url'],
				'photo'		=> $row['photo'],
				'url'			=> $row['url'],
				'uptm'		=> timemsg(time()-$row['uptm'])
			);
	}
	return $result;
}

function GetAlbumCover($alb)
{
	$chk = mysql_fetch_array(mysql_query('SELECT cover FROM _photo WHERE albumid="'.check($alb).'"'));
	if($chk[0] > 0)
	{
		return $chk[0];
	}
	else
	{
		$row = mysql_fetch_array(mysql_query('SELECT id FROM _photo WHERE albumid="'.check($alb).'" ORDER BY RAND()'));
		return $row[0];
	}
}

function GetPhotoCount($id)
{
	global $ses;
	$res = mysql_query('SELECT albumid FROM _photo WHERE id="'.check($id).'"');
	$row = mysql_fetch_array($res);
	$res = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM _photo WHERE albumid="'.check($row[0]).'"'));
	return $res[0];
}

function GetPhotoList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$chk = mysql_fetch_array(mysql_query('SELECT albumid FROM _photo WHERE id="'.check($id).'"'));
	$res =	mysql_query('SELECT * FROM _photo WHERE albumid="'.check($chk[0]).'" ORDER BY id="'.check($id).'"
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$url = getphoto(GetAlbumCover($row['albumid']));
		$profile = getuserinfo($row['userid']);
		$result[$row['id']] = array(
				'userid'	=> $row['userid'],
				'username'	=> getusername($row['userid']),
				'cover'		=> GetAlbumCover($row['albumid']),
				'profile'	=> $profile['photo'],
				'album'		=> $row['album'],
				'albumid'	=> $row['albumid'],
				'amount'	=> GetAlbumPhotoCount($row['albumid']),
				'photo'		=> $row['photo'],
				'ulike'		=> GetULikeCount(0, 0, 0, $row['id']),
				'url'		=> $row['url'],
				'uptm'		=> timemsg(time()-$row['uptm'])
			);
	}
	return $result;
}

function GetAlbumCount($id)
{
	global $ses;
	$res = mysql_query('SELECT COUNT(DISTINCT albumid) FROM _photo WHERE userid="'.check($id).'"');
	$row = mysql_fetch_array($res);
	return $row[0];
}

function GetAlbumList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _photo WHERE userid="'.check($id).'" GROUP BY albumid ORDER BY uptm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$url = getphoto(GetAlbumCover($row['albumid']));
		$result[$row['id']] = array(
				'username'	=> getusername($row['userid']),
				'cover'		=> $url['url'],
				'album'		=> $row['album'],
				'albumid'		=> $row['albumid'],
				'amount'	=> GetAlbumPhotoCount($row['albumid']),
				'photo'		=> $row['photo'],
				'url'			=> $row['url'],
				'uptm'		=> timemsg(time()-$row['uptm'])
			);
	}
	return $result;
}

function GetSearchCount($q)
{
	global $ses;
	$res = mysql_query('SELECT COUNT(*) FROM _users WHERE username LIKE "%'.check($q).'%"');
	$row = mysql_fetch_array($res);
	return $row[0];
}

function GetAddMemberCount($id, $friend)
{
	global $ses;
	$res = mysql_query('SELECT id FROM _users WHERE username LIKE "%'.check($friend).'%" AND id!="'.check($ses['userid']).'"');
	while($row = mysql_fetch_array($res))
	{
		if(CheckFriend($row[0]) == 3 && GetGroupMember($id, $row[0]) == 0)
		{
			$ro[] = $row[0];
		}
	}
	$row = count($ro);
	return $row;
}

function GetAddMemberList($id, $friend, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res = mysql_query('SELECT id, photo FROM _users WHERE username LIKE "%'.check($friend).'%" AND id!="'.check($ses['userid']).'" ORDER BY lastlogin 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		if(CheckFriend($row[0]) == 3 && GetGroupMember($id, $row[0]) == 0)
		{
			$result[$row['id']] = array(
				'username'	=> getusername($row['id']),
				'url' => getsetphoto($row['id']),
				'photo' => $row['photo'],
				'friend' => CheckFriend($row['id'])
			);
		}
	}
	return $result;
}

function GetGroupMember($id, $user)
{
	global $ses;
	$res =  mysql_query('SELECT COUNT(*) FROM _members WHERE grp="'.check($id).'" AND userid="'.check($user).'" AND dtm>0');
	$row =	mysql_fetch_array($res);
	return	$row[0];
}

function GetGroupMemberCount($id)
{
	global $ses;
	$res =  mysql_query('SELECT COUNT(*) FROM _members WHERE grp="'.check($id).'" AND dtm>0');
	$row =	mysql_fetch_array($res);
	return	$row[0];
}

function GetGroupMemberList($id, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	$res =	mysql_query('SELECT * FROM _members WHERE grp="'.check($id).'" AND dtm>0 ORDER BY dtm 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$info = getuserinfo($row['userid']);
		$result[$row['userid']] = array(
			'username'	=> getusername($row['userid']),
			'url' => getsetphoto($row['userid']),
			'photo' => $info['photo'],
			'friend' => CheckFriend($row['userid'])
		);
	}
	return $result;
}

function GetGroupCount()
{
	global $ses;
	$res =  mysql_query('SELECT COUNT(*) FROM _members WHERE userid="'.check($ses['userid']).'"');
	$row =	mysql_fetch_array($res);
	return	$row[0];
}

function GetGroupList($page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _members WHERE userid="'.check($ses['userid']).'" AND dtm>0 ORDER BY lastact 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$info = getgroupinfo($row['grp']);
		$result[$info['id']] = array(
			'group'	=> $info['grp'],
			'description'		=> $info['description'],
			'time'		=> timemsg(time()-$info['dtm'])
		);
	}
	return $result;
}

function GetRecGroupList()
{
	global $ses;
	$res =	mysql_query('SELECT id, grp, userid, lastact FROM _members WHERE dtm>0 AND userid!="'.check($ses['userid']).'" GROUP BY grp 
			ORDER BY lastact DESC LIMIT 2');
	while($row = mysql_fetch_array($res))
	{
		$info = getgroupinfo($row['grp']);
		if(CheckFriend($row['userid']) == 3 && GetGroupMember($row['grp'], $ses['userid']) == 0)
		{
			$result[$info['id']] = array(
				'group'	=> $info['grp'],
				'description'		=> $info['description'],
				'time'		=> timemsg(time()-$info['dtm'])
			);
		}
	}
	return $result;
}

function GetMessageDo($id, $do, $sel, $type = '0')
{
	global $ses;
	$chk =	mysql_fetch_array(mysql_query('SELECT * FROM _messages WHERE (mid="'.check($id).'" AND fromid="'.check($ses['userid']).'" AND
			fromuser="'.check($type).'") OR (toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'") ORDER BY 
			uptm DESC LIMIT 1'));
	if($chk[0] > 0)
	{
		if($do == 1)
		{
			$up = mysql_query('UPDATE _messages SET uptm=0 WHERE toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'"');
			if($up)
			{
				header('Location: index.php?ac=msg&sid='.$ses['id']);
			}
		}
		else if($do == 2)
		{
			$res =	mysql_query('SELECT * FROM _messages WHERE (mid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") 
					OR (toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'")');
			while($row = mysql_fetch_array($res))
			{
				if($ses['userid'] == $row['toid'])
				{
					$up = mysql_query('UPDATE _messages SET touser=1 WHERE id="'.$row[0].'"');
				}
				if($ses['userid'] == $row['fromid'])
				{
					$up = mysql_query('UPDATE _messages SET fromuser=1 WHERE id="'.$row[0].'"');
				}
			}
			if($up)
			{
				header('Location: index.php?ac=msg&sid='.$ses['id']);
			}
		}
		else if($do == 3)
		{
			if(isset($sel))
			{
				for($i=0;$i<count($sel);$i++)
				{
					$res = mysql_query('SELECT * FROM _messages WHERE id="'.check($sel[$i]).'"');
					$row = mysql_fetch_array($res);
					if($ses['userid'] == $row['toid'])
					{
						$up = mysql_query('UPDATE _messages SET touser=1 WHERE id="'.$row[0].'"');
					}
					if($ses['userid'] == $row['fromid'])
					{
						$up = mysql_query('UPDATE _messages SET fromuser=1 WHERE id="'.$row[0].'"');
					}
					if($up)
					{
						header('Location: index.php?ac=msg&sid='.$ses['id']);
					}
				}
			}
		}
		else if($do == 4)
		{
			$res =	mysql_query('SELECT * FROM _messages WHERE (mid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") 
					OR (toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'")');
			while($row = mysql_fetch_array($res))
			{
				if($ses['userid'] == $row['toid'] && $row['touser'] == 2)
				{
					$up = mysql_query('UPDATE _messages SET touser=0 WHERE id="'.$row[0].'"');
				}
				if($ses['userid'] == $row['toid'] && ($row['touser'] == 0 || $row['touser'] == 3))
				{
					$up = mysql_query('UPDATE _messages SET touser=2 WHERE id="'.$row[0].'"');
				}
				
				if($ses['userid'] == $row['fromid'] && $row['fromuser'] == 2)
				{
					$up = mysql_query('UPDATE _messages SET fromuser=0 WHERE id="'.$row[0].'"');
				}
				if($ses['userid'] == $row['fromid'] && ($row['fromuser'] == 0 || $row['fromuser'] == 3))
				{
					$up = mysql_query('UPDATE _messages SET fromuser=2 WHERE id="'.$row[0].'"');
				}
			}
			if($up)
			{
				header('Location: index.php?ac=msg&sid='.$ses['id']);
			}
		}
		else if($do == 5)
		{
			$res =	mysql_query('SELECT * FROM _messages WHERE (mid="'.check($id).'" AND fromuser="'.check($type).'" AND fromid="'.check($ses['userid']).'") 
					OR (toid="'.check($ses['userid']).'" AND mid="'.check($id).'" AND touser="'.check($type).'")');
			while($row = mysql_fetch_array($res))
			{
				if($ses['userid'] == $row['toid'] && $row['touser'] == 3)
				{
					$up = mysql_query('UPDATE _messages SET touser=0 WHERE id="'.$row[0].'"');
				}
				if($ses['userid'] == $row['toid'] && ($row['touser'] == 0 || $row['touser'] == 2))
				{
					$up = mysql_query('UPDATE _messages SET touser=3 WHERE id="'.$row[0].'"');
				}
				
				if($ses['userid'] == $row['fromid'] && $row['fromuser'] == 3)
				{
					$up = mysql_query('UPDATE _messages SET fromuser=0 WHERE id="'.$row[0].'"');
				}
				if($ses['userid'] == $row['fromid'] && ($row['fromuser'] == 0 || $row['fromuser'] == 2))
				{
					$up = mysql_query('UPDATE _messages SET fromuser=3 WHERE id="'.$row[0].'"');
				}
			}
			if($up)
			{
				header('Location: index.php?ac=msg&sid='.$ses['id']);
			}
		}
		else if($do == 6)
		{
		}
		else if($do == 7)
		{
		}
	}
}

function GetSearchList($q, $page = 1, $PerPage = -1, $sortBy = 'DESC')
{
	global $ses;
	$res =	mysql_query('SELECT * FROM _users WHERE username LIKE "%'.check($q).'%" ORDER BY lastlogin 
			'.$sortBy.($PerPage != -1 ? ' LIMIT '.(($page-1)*$PerPage).' ,'.$PerPage : ''));
	while($row = mysql_fetch_array($res))
	{
		$info = getuserinfo($row['id']);
		$result[$row['id']] = array(
			'username'	=> getusername($row['id']),
			'url' => getsetphoto($row['id']),
			'photo' => $info['photo'],
			'friend' => CheckFriend($row['id'])
		);
	}
	return $result;
}
?>