<?php
/* WebWall */
include "modules/libmail.php";
class engine
{
	function __construct() 
	{
		if(DB_SERVER!="" && DB_USERNAME!="" && DB_PASSWORD!="" && DB_NAME!="")
		{
			$mysql_connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
			if($mysql_connection)
			{
				$dbCon = mysql_select_db(DB_NAME, $mysql_connection);
			}
			else
			{
				die("Verify settings mysql.");
			}
		}
		else
		{
			die("<a href='http://".$_SERVER["SERVER_NAME"]."/site/install?step=1' style='display:block;margin:150px auto;width:300px;text-align:center;text-decoration:none;background-color:#2b5797;color:#fff;font-size:18px;padding:5px 0'>WebWall<br>Start installation</a>");
		}
	}

	public function headerin($adress)
	{
		header('Location: http://'.SITE_DOMAIN.'/'.$adress.'');
	}
	
	public function resizeimg($filename, $smallimage, $w, $h) 
	{    
		$ratio = $w/$h; 
		$size_img = getimagesize($filename); 
		$src_ratio=$size_img[0]/$size_img[1]; 
		if($ratio<$src_ratio) $h = $w/$src_ratio; 
		else $w = $h*$src_ratio; 
		$dest_img = imagecreatetruecolor($w, $h);   
		$white = imagecolorallocate($dest_img, 255, 255, 255);  
		switch($size_img[2])  
		{
			case 1:
			{
				$src_img = imagecreatefromgif($filename);
				imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $w, $h, $size_img[0], $size_img[1]);                 
				imagegif($dest_img, $smallimage);
			}
			case 2:
			{
				$src_img = imagecreatefromjpeg($filename);                       
				imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $w, $h, $size_img[0], $size_img[1]);                 
				imagejpeg($dest_img, $smallimage);
			}
			case 3:
			{
				$src_img = imagecreatefrompng($filename);
				imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $w, $h, $size_img[0], $size_img[1]);                 
				imagepng($dest_img, $smallimage);
			}
		}    
		imagedestroy($dest_img); 
		imagedestroy($src_img); 
		return true;          
	}   
	
	public function onlineusers($number=0)
	{
		$maxtime = time()-60;
		$query = mysql_query("SELECT username, visit FROM users WHERE visit>'".$maxtime."'");
		$number = mysql_num_rows($query);
		return $number;
	}
	
	public function inboxposts($user, $number=0)
	{
		$query = mysql_query("SELECT * FROM posts WHERE to_user = '$user'");
		$number = mysql_num_rows($query);
		return $number;
	}
	
	public function getinfo($table, $table_val, $mode)
	{
		$configsql = @mysql_query("SELECT * FROM ".$table." LIMIT 1") or die(mysql_error());
		$config = mysql_fetch_assoc($configsql);
		if($mode == 0 && $table_val!="*") return $config[''.$table_val.'']; 
		else if($mode == 0 && $table_val=="*") return $config;
		else if($mode == 1) echo $config[''.$table_val.'']; 
	}
	
	public function crypts($encrypt_val, $mode, $brute_pass)
	{
		if($brute_pass != 0 && strlen($encrypt_val) > 0 || strlen($encrypt_val) < 800)
		{
			switch($mode)
			{
				case 1:		
				case "MD5":		
				{
					return md5($encrypt_val);
					break;
				}
				case 2:
				case "BASE_64":	
				{
					return base64_encode($encrypt_val);
					break;
				}
				case 3:
				case "SHA1":	
				{
					return sha1($encrypt_val);
					break;
				}
				default:		
				{
					return 0;
					break;
				}
			}
		}
		else if($brute_pass != 1)
		{
			return sha1(base64_encode(md5($encrypt_val)));
		}
	}
	
	public function captchaerror() //?
    {
        $_SESSION['msg'] = 3;
        $this->headerin("account/signup");
        exit;
    }

	public function checkcookies($username, $password, $social = 'none', $id = '', $admin = 2, $moderator = 1, $user = 0)
	{
		if($social !="none")
		{
			$result = @mysql_query("SELECT id, username, password, status, rank, lang FROM users WHERE $social = '$id'");
			$user_data = @mysql_fetch_array($result);
			if(@mysql_num_rows($result) != 0)
			{	
				if($user_data['status'] != 1 || $user_data['rank'] != 1 && $user_data['rank'] != 0 && $user_data['rank'] != 2)
				{
					$_SESSION['error'] = 1;
					$_SESSION['logtry'] = $user_data['username']; 
					$this->headerin("account/login");
					exit;
				}
				else
				{
					$_SESSION['login'] = true;
					$_SESSION['id'] = $user_data['id'];
					$_SESSION['rank'] = $user_data['rank'];
					$_SESSION['social'] = $user_data['rank'];
					$_SESSION['account_username'] = $user_data['username']; 
					SetCookie("lang", $user_data['lang'], time()+360*24*3600, "/");
					if($user_data['rank'] == $admin)
					{
						for ($i = 1; $i <= 15; $i++)
						{
							$this->user_rights .= engine::setuserrights($i);
						}
					}
					else if($user_data['rank'] == $moderator)
					{
						for ($i = 16; $i <= 19; $i++)
						{
							$this->user_rights .= engine::setuserrights($i);
						}
					}
					else if($user_data['rank'] == $user)
					{
						$this->user_rights = 'NORMAL';
					}
					$_SESSION['__rights'] = $this->user_rights;
					$this->headerin();
					exit;
				}
			}
			else
			{
				if($social !="")
				{
					$this->headerin("account/signup");
					exit;
				}
				else
				{
					$_SESSION['error'] = 2;
					$this->headerin("account/login");
					exit;
				}
			}
		}
		else
		{
			if(!preg_match('/^[a-za-zA-Z\d_]{1,32}$/i', $username)) 
			{
				$_SESSION['error'] = 3;
				$this->headerin("account/login");
				exit;	
			}
			else
			{
				$pass = engine::crypts(engine::crypts(engine::crypts($password, "MD5", 0), 2, 0), "SHA1", 0);
				$result = @mysql_query("SELECT id, username, password, status, rank, lang FROM users WHERE username = '$username' AND password = '$pass'");
			}
		}
		$user_data = @mysql_fetch_array($result);
		if(@mysql_num_rows($result) != 0)
		{			 
			if($user_data['status'] != 1 || $user_data['rank'] != 1 && $user_data['rank'] != 0 && $user_data['rank'] != 2)
			{
				$_SESSION['error'] = 1;
				$this->headerin("account/login");
				exit;
			}
			else
			{
				$_SESSION['login'] = true;
				$_SESSION['id'] = $user_data['id'];
				$_SESSION['account_username'] = $user_data['username']; 
				SetCookie("lang", $user_data['lang'], time()+360*24*3600, "/");
				if($user_data['rank'] == $admin)
				{
					for ($i = 1; $i <= 15; $i++)
					{
						$this->user_rights .= engine::setuserrights($i);
					}
				}
				else if($user_data['rank'] == $moderator)
				{
					for ($i = 16; $i <= 19; $i++)
					{
						$this->user_rights .= engine::setuserrights($i);
					}
				}
				else if($user_data['rank'] == $user)
				{
					$this->user_rights = 'NORMAL';
				}
				$_SESSION['__rights'] = $this->user_rights;
				$this->headerin();
				exit;
			}
		}
		else
		{
			if($social !="")
			{
				$_SESSION['error'] = 3;
				$this->headerin("account/login");
				exit;
			}
			else
			{
				$_SESSION['error'] = 2;
				$this->headerin("account/login");
				exit;
			}
		}
	}
	
	public function reactive($username)
	{	
		$this->username = text_filter($username, 1);		
		if(mysql_query("UPDATE users SET status = '1' WHERE username = '$this->username'") != 0)
		{	
			$_SESSION['error'] = 10;
			$this->headerin("account/login");
			exit;;
		}
		else
		{
			$_SESSION['error'] = 1;
			$this->headerin("account/login");
			exit;
		} 
	}
	
	public function changelang()
	{		
		$lang = text_filter($_COOKIE['lang'], 1);
		mysql_query("UPDATE users SET lang = '".$lang."' WHERE username = '".USER_USERNAME."'");
	}
	
	public function randomvar($length, $numbers, $upper)
	{
		if(1 > $length) $length = 8;
		$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$numChars = 62;
		if(!$numbers)
		{
			$numChars = 52;
			$chars = substr($chars, 10, $numChars);
		}	
		if(!$upper)
		{
			$numChars -= 26;
			$chars = substr($chars, 0, $numChars);
		}
		$string = '';
		for ($i = 0; $i < $length; $i++)
		{
			$string .= $chars[mt_rand(0, $numChars - 1)];
		}			
		return $string;		
	}
	
	public function serializethemes($myTheme,$user="")
	{
		$arr = array();
		$arr[] = "background";
		$arr[] = "default";
		$arr[] = "agenda";
		$arr[] = "birch";
		$arr[] = "birds";
		$arr[] = "blackcross";
		$arr[] = "blackromb";
		$arr[] = "bluebulles";
		$arr[] = "bluemettal";
		$arr[] = "cyanmettal";
		$arr[] = "greenlines";
		$arr[] = "greenmettal";
		$arr[] = "greymettal";
		$arr[] = "isumrudic";
		$arr[] = "lined_paper";
		$arr[] = "mosaic";
		$arr[] = "noisygrid";
		$arr[] = "notes";
		$arr[] = "orangelines";
		$arr[] = "paper";
		$arr[] = "pink";
		$arr[] = "pinkmettal";
		$arr[] = "pinstripe";
		$arr[] = "redcircle";
		$arr[] = "redmettal";
		$arr[] = "vintage";
		$arr[] = "whitemosaic";
		$arr[] = "whitestripped";
		$arr[] = "wood";
		$arr[] = "yellowmettal";
		if(in_array($myTheme, $arr) != true)	return;
		$this->Message = "";
		for($i=0; $i<30; $i++)
		{
			$this->Message .= '<div id="theme_'.$arr[$i].'" class="';
			if($myTheme != ''.$arr[$i].'') 
			{ 
				$this->Message .= 'theme'; 
			}
			else 
			{ 
				$this->Message .= 'theme selectedTheme'; 
			}
			if($arr[$i]=='background')
			{
				$this->Message .= '" style="background:url(media/images/backgrounds/'.$user.');background-size: 100% 100%;">';
			}
			else
			{
				$this->Message .= '" style="background-image:url(media/images/themes/'.$arr[$i].'.png)">';
			}
			$this->Message .= "<a href=\"#\" onclick=\"selectTheme('$arr[$i]'); return false;\">&nbsp;</a>";
			$this->Message .= '</div>';
		
		}
		return $this->Message;
	}
	
	public function serializegifts($message = "")
	{
		$arr = array();
		$query = mysql_query("SELECT * FROM giftstype");
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$message .= "<a href=\"#\" onclick=\"selectGift('".$ii['id']."'); return false;\" class='gift".$ii['id']."'>";
				$message .= "<img src='".GIFTS_IMG_PATH."".$ii['image']."' width='100' height='100'>";
				$message .= "</a>";
			}
		}
		return $message;
	}
	
	public function updateusertheme($username, $theme)
	{
		$this->username = text_filter($username, 1);
		$this->theme = text_filter($theme, 1);
		if(SESSION_STATUS != false)
		{
			if(in_array($this->theme, array('default', 'agenda', 'background', 'birch', 'birds', 'blackcross', 'blackromb', 'bluebulles', 'bluemettal', 'cyanmettal', 'greenlines', 'greenmettal', 'greymettal', 'isumrudic', 'lined_paper', 'mosaic', 'noisygrid', 'notes', 'orangelines', 'paper', 'pink', 'pinkmettal', 'pinstripe', 'photo', 'redcircle', 'redmettal', 'vintage', 'whitemosaic', 'whitestripped', 'wood','yellowmettal')))
			{
				if(engine::getuserdata(USER_USERNAME, "THEME") == $this->theme)
				{
					$_SESSION['msg'] = 1;
					$this->headerin("account/design");
					exit;
				}
				else if(mysql_query("UPDATE users SET theme = '$this->theme' WHERE username = '$this->username'") != 0)
				{
					$_SESSION['msg'] = 2;
					$this->headerin("account/design");
					exit;
				}   
				else 
				{ 
					die('<center>'.engine::getlangvar(39).'</center>'); 
				}
			}
			else
			{
				$_SESSION['msg'] = 3;
				$this->headerin("account/design");
				exit;
			} 
		}
	}
	
	public function updateuserbackground($username, $photo_file)
	{
		if(SESSION_STATUS != false)
		{
			$this->username = text_filter($username, 1);
			$this->photo = $photo_file = $_FILES["photo"];
			$error = array();
			$file = isset($this->photo) ? $this->photo : FALSE;
			if($file)
			{
				if(!eregi("^image\/(pjpeg|jpeg|jpg|png|gif|bmp)$", $file["type"]))
				{
					$error[] = 1;
					$_SESSION['msg'] = 1;
					header('Location: http://'.SITE_DOMAIN.'/account/design');
					exit;
				}
				else
				{
					if($file["size"] > PHOTO_MAX_SIZE)
					{
						$error[] = 2;
						$_SESSION['msg'] = 2;
						header('Location: http://'.SITE_DOMAIN.'/account/design');
						exit;
					}
					$photo_dimensions = getimagesize($file["tmp_name"]);
					if($photo_dimensions[0] > PHOTO_MAX_WIDTH)
					{
						$error[] = 3;
						$_SESSION['msg'] = 3;
						header('Location: http://'.SITE_DOMAIN.'/account/design');
						exit;
					}
					if($photo_dimensions[1] > PHOTO_MAX_HEIGHT)
					{
						$error[] = 4;
						$_SESSION['msg'] = 4;
						header('Location: http://'.SITE_DOMAIN.'/account/design');
						exit;
					}
				}
				if(sizeof($error))
				{
					$_SESSION['msg'] = 5;
					header('Location: http://'.SITE_DOMAIN.'/account/design');
					exit;
				}
				else
				{
					preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $file["name"], $ext);
					$photo_crypt_name = engine::crypts($username.time().'', 1, 0) . "." . $ext[1];
					$root = realpath($_SERVER["DOCUMENT_ROOT"]);
					$directory = "../../media/images/backgrounds/" . '' . $photo_crypt_name;
					$tdirectory = "../../media/images/backgrounds/" . 't_' . $photo_crypt_name;
					move_uploaded_file($file["tmp_name"], $directory);
					engine::resizeimg($directory, $tdirectory, 1920, 1080); 
					if(SESSION_STATUS != false)
					{
						if(mysql_query("UPDATE users SET background = '$photo_crypt_name', theme = 'background' WHERE username = '$this->username'") != 0)
						{
							$_SESSION['msg'] = 2;
							$this->headerin("account/design");
							exit;
						} 
						else 
						{ 
							die('<center>'.engine::getlangvar(39).'</center>'); 
						}
					}
				}
			}
		}
	}
		
	public function recoverpassword($email, $pass_length = 15)
	{
		$this->email = text_filter($email, 1);
		$new_pass = engine::randomvar($pass_length, true, false);
		$this->password = engine::crypts(engine::crypts(engine::crypts($new_pass, "MD5", 0), 2, 0), "SHA1", 0);
		$this->message = '';
		if(isset($this->email))
		{
			if(SESSION_STATUS != true)
			{
				if($this->email != "" && strlen($this->email) > 0)
				{
					$sql = "SELECT * FROM users WHERE email = '$this->email' LIMIT 1";
					$query = mysql_query($sql);
					if(@mysql_num_rows($query) != 0)
					{
						if(mysql_query("UPDATE users SET password = '$this->password' WHERE email = '$this->email'") != 0)
						{
							$m=new Mail;
							$m->From("no-reply@".SITE_DOMAIN."");
							$m->To($email);
							$m->Subject(engine::getlangvar(800) . SITE_DOMAIN . "!");
							$m->Body(engine::getlangvar(801) . $new_pass . ".<br>" . engine::getlangvar(802) . ".<br>" . engine::getlangvar(803) . SITE_DOMAIN . ".");    
							$m->Priority(3) ;  
							$m->Send();    
							$this->message .= '<p class="popup_success">'.engine::getlangvar(804).'</p>';
						}
						else 
						{
						 	die('<center>'.engine::getlangvar(39).'</center>'); 
						}
					}
					else
					{
						$this->message .= '<p class="error"><b>'.engine::getlangvar(40).' </b>'.engine::getlangvar(41).'</p>';
					}
				}
				else
				{
					$this->message .= '<p class="error"><b>'.engine::getlangvar(40).' </b>'.engine::getlangvar(42).'</p>';
				}
			}
		}
		return $this->message;
	}
	
	public function setuserrights($code, $min = 0, $max = 20) //?
	{
		$mRights .= 'VIEW_USERS';
		$mRights .= 'EDIT_USER_ACCOUNT';
		$mRights .= 'EDIT_USER_PROFILE';
		if($code > $min && $code < $max)
		{
			switch($code)
			{
				case 1: 	return "ADM";
							break;
				case 2:     return "FREE_HM_ACCESS";
							break;
				case 3:	    return "SUPREME_COMMANDS";
							break;
				case 4:	    return "VIEW_QA";
							break;
				case 5:     return "DELETE_QA";
							break;
				case 6:	    return "EDIT_SITE_SETTINGS";
							break;
				case 7:	    return "VIEW_USERS";
							break;
				case 8:	    return "VIEW_SITE_SETTINGS"; 
							break;
				case 9: 	return "EDIT_USER_ACCOUNT"; 
							break;
				case 10:    return "EDIT_USER_PROFILE"; 
							break;
				case 11:    return "DELETE_USER";
							break;
				case 12:	return "SUPPORT_REQUEST";
							break;
				case 13:   	return "VIEW_RANKS"; 
							break;
				case 14:    return "GIVE_RANK"; 
							break;
				case 15:    return "TAKE_RANK";
							break;
				case 16:    return "MOD"; 
							break;
				case 17:    return "FREE_HM_ACCESS"; 
							break;
				case 18:    return $mRights; 
							break;
				case 19:    return "VIEW_qaDELETE_qa"; 
							break;
				default:    return NULL;
							break;
			}
		}
	}
	
	public function updateusersettings($name, $password, $passwords, $email, $protection, $surname)
	{
		$this->username = ''.USER_USERNAME.'';
		$this->name = text_filter($name, 1);
		$this->surname = text_filter($surname, 1);
		$this->password = $password;
		$this->passwords = $passwords;
		$this->email = text_filter($email, 1);
		$this->protection = text_filter($protection, 1);		
		if(SESSION_STATUS != false)
		{	
			if($this->email != engine::getuserdata($this->username, "EMAIL"))
			{
				if(engine::emailalreadyexists($this->email) == "Email Exists")
				{
					$_SESSION['msg'] = 3;
					$this->headerin("account/settings");
					exit;
				}
			 }
			if($this->name == "" || $this->surname == "" || $this->email == "")
			{
				$_SESSION['msg'] = 2;
				header('Location: http://'.SITE_DOMAIN.'/account/profile');
				exit;
			}
			if(strlen($this->passwords) > 4)
			{ 
				$pass = engine::crypts(engine::crypts(engine::crypts($password, "MD5", 0), 2, 0), "SHA1", 0);
				$result = @mysql_query("SELECT id FROM users WHERE username = '$this->username' AND ( password = '$pass' OR password = '' ) ");
				if(@mysql_num_rows($result) != 0)
				{
					$modify_pass = 1; 
				}
				else
				{
					$_SESSION['msg'] = 405;
					header('Location: http://'.SITE_DOMAIN.'/account/profile');
					exit;
				}	
			} 
			if($this->passwords != "" && strlen($this->passwords) < 5)
			{
				$_SESSION['msg'] = 2;
				header('Location: http://'.SITE_DOMAIN.'/account/profile');
				exit;
			} 
			elseif($this->passwords == "") 
			{ 
				$modify_pass = 0; 
			}
			$pass = engine::crypts(engine::crypts(engine::crypts($this->passwords, "MD5", 0), 2, 0), "SHA1", 0);
			$mysqlmessage = "UPDATE users SET ";
			$mysqlmessage .= "real_name = '$this->name', ";
			$mysqlmessage .= "real_surname = '$this->surname', ";
			$mysqlmessage .= "email = '$this->email', ";
			if($modify_pass != 0) 
			{	
				$mysqlmessage .= "password = '$pass', ";	
			}
			$mysqlmessage .= "anonymous_view = '$this->protection' ";
			$mysqlmessage .= "WHERE username = '$this->username'";
			if(mysql_query($mysqlmessage) != 0)
			{
				$_SESSION['msg'] = 1;
				header('Location: http://'.SITE_DOMAIN.'/account/profile');
				exit;
			} 
			else 
			{ 
				die('<center>'.engine::getlangvar(39).'</center>'); 
			}
		}
	}

	public function getuserdata($username, $data)
	{
		$this->username = $username;
		if(strlen($this->username) > 0)
		{
				$sql = @mysql_query("SELECT * FROM users WHERE username = '$this->username'") or die(mysql_error());
				$readdata = @mysql_fetch_assoc($sql);
				switch($data)
				{
					case "ID": 				return $readdata['id']; 
											break; 
					case "USERNAME":	 	return $readdata['username']; 
											break;
					case "PASSWORD": 		return $readdata['password']; 
											break; 
					case "PASS": 			if($readdata['password']=="")
											return 0;
											else return 1;
											break; 
					case "REAL_NAME": 		return $readdata['real_name']; 
											break; 
					case "REAL_SURNAME":	return $readdata['real_surname']; 
											break;
					case "RANK": 			return $readdata['rank']; 
											break; 
					case "EMAIL": 			return $readdata['email']; 
											break; 
					case "WEBSITE": 		return $readdata['website']; 
											break; 
					case "LOCALIZATION": 	return $readdata['localization'];
											break; 
					case "USER_STATUS":		return $readdata['user_status']; 
											break; 
					case "PHOTO": 			return $readdata['photo']; 
											break;
					case "BIO": 			return $readdata['bio']; 
											break;
					case "COVER": 			return $readdata['cover']; 
											break; 
					case "BACKGROUND": 		return $readdata['background']; 
											break; 						
					case "STATUS": 			return $readdata['status']; 
											break; 
					case "IP_ADDRESS": 		return $readdata['ip']; 
											break; 
					case "A_VIEW": 			return $readdata['anonymous_view']; 
											break; 
					case "REG_DATE": 		return $readdata['reg_date']; 
											break; 
					case "VISIT": 			return $readdata['visit']; 
											break; 
					case "LANGUAGE": 		return $readdata['language']; 
											break; 
					case "VERIFIED": 		return $readdata['verified']; 
											break; 
					case "THEME": 			return $readdata['theme']; 
											break;
					case "FACEBOOK": 		return $readdata['facebook']; 
											break;
					case "TWITTER": 		return $readdata['twitter']; 
											break;
					case "GOOGLEPLUS": 		return $readdata['googleplus']; 
											break;
					case "VKONTAKTE": 		return $readdata['vkontakte']; 
											break;
					case "POINTS": 			if($readdata['points']=="") $readdata['points']=0;
											return $readdata['points']; 
											break;
					case "GIFTS": 			$sql = @mysql_query("SELECT COUNT(*) as total FROM gifts WHERE to_user = '$this->username'") or die(mysql_error());
											$readdata = @mysql_fetch_assoc($sql);
											return $readdata['total']; 
											break;
					case "*":				return $readdata;
											break;
			}
		}
	}
	
	public function getuserrelations($username, $data)
	{
		$this->username = text_filter($username, 1);
		if(strlen($this->username) > 0)
		{
			if($data == "FOLLOW") $sql = @mysql_query("SELECT DISTINCT friend FROM users_friends WHERE username = '$this->username'") or die(mysql_error());
			else if($data == "FOLLOWERS") $sql = @mysql_query("SELECT DISTINCT username FROM users_friends WHERE friend = '$this->username'") or die(mysql_error());
			$num_rows = @mysql_num_rows($sql);
			return $num_rows; 
		}
	}
	
	public function clearcookies()
	{
		unset($_SESSION['id']);
		unset($_SESSION['account_username']);
		unset($_SESSION['__rights']);
		unset($_SESSION['login']);
		session_destroy();
		session_start();
		$_SESSION["log_verify"] = true;
		$this->headerin("site/complete");
        exit;
	}
	
	public function getuserrights($received_right)
	{
		if(isset($received_right))
		{
			if(SESSION_STATUS != false)
			{
				if(strpos(USER_RIGHTS, $received_right) === false) $returnvar = 0;
				else $returnvar = 1;
				return $returnvar;
			}
		}
	}

	public function profileuserexists($user)
	{
		$this->username = text_filter($user, 1);
		if(strlen($this->username) > 0)
		{
			$result = @mysql_query("SELECT * FROM users WHERE username = '$this->username'");
			if(@mysql_num_rows($result) > 0) return 1;
			else return 0;
		}
		else return 0;
	}
	
	public function profileaccess($userviewed, $userentered)
	{
		if(strlen($userviewed) > 0)
		{
			$query = "SELECT * FROM users_blocked WHERE username = '".text_filter($userviewed, 1)."' and blocked = '".text_filter($userentered, 1)."'";
			$result = mysql_query($query);
			$done = mysql_num_rows($result);
			if($done>0) return 1;
			else return 0;
		}
		else return 0;
	}
	
	public function profilefriend($userviewed, $userentered)
	{
		if(strlen($userviewed) > 0)
		{
			$query = "SELECT * FROM users_friends WHERE username = '".$userviewed."' and friend = '".$userentered."'";
			$result = mysql_query($query);
			$done = mysql_num_rows($result);
			if($done>0) return 1;
			else return 0;
		}
		else return 0;
	}

	public function updateuserphoto($photo_file)
	{
		$this->username = ''.USER_USERNAME.'';
		$this->photo = $photo_file = $_FILES["photo"];
		$error = array();
		$file = isset($this->photo) ? $this->photo : FALSE;
		if($file)
		{
			if(!eregi("^image\/(pjpeg|jpeg|jpg|png|gif|bmp)$", $file["type"]))
			{
				$error[] = 1;
				$_SESSION['msg'] = 1;
				header('Location: http://'.SITE_DOMAIN.'/account/settings');
				exit;
			}
			else
			{
				if($file["size"] > PHOTO_MAX_SIZE)
				{
					$error[] = 2;
					$_SESSION['msg'] = 2;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
				$photo_dimensions = getimagesize($file["tmp_name"]);
				if($photo_dimensions[0] > PHOTO_MAX_WIDTH)
				{
					$error[] = 3;
					$_SESSION['msg'] = 3;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
				if($photo_dimensions[1] > PHOTO_MAX_HEIGHT)
				{
					$error[] = 4;
					$_SESSION['msg'] = 4;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
			}
			if(sizeof($error))
			{
				$_SESSION['msg'] = 5;
				header('Location: http://'.SITE_DOMAIN.'/account/settings');
				exit;
			}
			else
			{
				preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $file["name"], $ext);
				$photo_crypt_name = engine::crypts(''.USER_USERNAME.''.time().'', 1, 0) . "." . $ext[1];
				$root = realpath($_SERVER["DOCUMENT_ROOT"]);
				$directory = IMG_PATH . 'b_' . $photo_crypt_name;
				$tdirectory = IMG_PATH . '' . $photo_crypt_name;
				$ttdirectory = IMG_PATH . 'tt_' . $photo_crypt_name;
				move_uploaded_file($file["tmp_name"], $directory);
				engine::resizeimg($directory, $tdirectory, 300, 300); 
				engine::resizeimg($directory, $ttdirectory, 100, 100); 
				if(SESSION_STATUS != false)
				{
					if(mysql_query("UPDATE users SET photo = '$photo_crypt_name' WHERE username = '$this->username'") != 0)
					{
						$_SESSION['msg'] = 6;
						header('Location: http://'.SITE_DOMAIN.'/account/settings');
						exit;
					} 
					else 
					{ 
						die('<center>'.engine::getlangvar(39).'</center>'); 
					}
				}
			}
		}
	}

	public function updateusercover($photo_file)
	{
		$this->username = ''.USER_USERNAME.'';
		$this->photo = $photo_file = $_FILES["photo"];
		$error = array();
		$file = isset($this->photo) ? $this->photo : FALSE;
		if($file)
		{
			if(!eregi("^image\/(pjpeg|jpeg|jpg|png|gif|bmp)$", $file["type"]))
			{
				$error[] = 1;
				$_SESSION['msg'] = 1;
				header('Location: http://'.SITE_DOMAIN.'/account/settings');
				exit;
			}
			else
			{
				if($file["size"] > PHOTO_MAX_SIZE)
				{
					$error[] = 2;
					$_SESSION['msg'] = 2;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
				$photo_dimensions = getimagesize($file["tmp_name"]);
				if($photo_dimensions[0] > PHOTO_MAX_WIDTH)
				{
					$error[] = 3;
					$_SESSION['msg'] = 3;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
				if($photo_dimensions[1] > PHOTO_MAX_HEIGHT)
				{
					$error[] = 4;
					$_SESSION['msg'] = 4;
					header('Location: http://'.SITE_DOMAIN.'/account/settings');
					exit;
				}
			}
			if(sizeof($error))
			{
				$_SESSION['msg'] = 5;
				header('Location: http://'.SITE_DOMAIN.'/account/settings');
				exit;
			}
			else
			{
				preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $file["name"], $ext);
				$photo_crypt_name = engine::crypts(''.USER_USERNAME.''.time().'', 1, 0) . "." . $ext[1];
				$root = realpath($_SERVER["DOCUMENT_ROOT"]);
				$directory = IMG_PATH . 'b_' . $photo_crypt_name;
				$tdirectory = IMG_PATH . '' . $photo_crypt_name;
				$ttdirectory = IMG_PATH . 'tt_' . $photo_crypt_name;
				move_uploaded_file($file["tmp_name"], $directory);
				engine::resizeimg($directory, $tdirectory, 300, 300); 
				engine::resizeimg($directory, $ttdirectory, 100, 100); 
				if(SESSION_STATUS != false)
				{
					if(mysql_query("UPDATE users SET cover = '$photo_crypt_name' WHERE username = '$this->username'") != 0)
					{
						$_SESSION['msg'] = 6;
						header('Location: http://'.SITE_DOMAIN.'/account/settings');
						exit;
					} 
					else 
					{ 
						die('<center>'.engine::getlangvar(39).'</center>'); 
					}
				}
			}
		}
	}
  
	public function updateuserprofile($website, $location, $about, $status)
	{
		$this->username = ''.USER_USERNAME.'';
		$this->website = text_filter($website, 1);
		$this->location = text_filter($location, 1);
		$this->about_me = text_filter($about, 1);
		$this->status = text_filter($status, 1);		   
		if(SESSION_STATUS != false)
		{
			if(mysql_query("UPDATE users SET website='$this->website', localization='$this->location', bio='$this->about_me', user_status='$this->status' WHERE username = '$this->username'") != 0)
			{
				$_SESSION['msg'] = 1;
				header('Location: http://'.SITE_DOMAIN.'/account/settings');
				exit;  
			} 
			else 
			{ 
				die("<center>Error deteted! Contact us for support. Error: EngUUP</center>"); 
			}
		}
	}
	
	public function disableaccount()
	{
		$this->username = ''.USER_USERNAME.'';
		$error_msg = '<center>'.engine::getlangvar(39).'</center>';
		if(SESSION_STATUS != false)
		{
			if(is_numeric(engine::getuserdata($this->username, "STATUS")) == true)
			{
				if(mysql_query("UPDATE users SET status = '0' WHERE username = '$this->username'") != 0)
				{
					$this->clearcookies();
					exit;
				} 
				else 
				{ 
					die($error_msg); 
				}
			}
		}
	}
	
	public function serializesearch($typed)
	{
		$workingString = text_filter($typed, 1);
		$this->message = '';
		if(!isset($workingString) || strlen($workingString) < 0 || empty($workingString))
		{
			$this->message .= '<center><p class="error"><b>'.engine::getlangvar(40).'</b> '.engine::getlangvar(60).'</p></center>';
		}	
		else
		{
			$sql = "SELECT * FROM users WHERE username LIKE '%$workingString%' OR real_name LIKE '%$workingString%' OR  real_surname LIKE '%$workingString%' AND status = '1' ORDER BY id DESC LIMIT 0, 200";
			$query = mysql_query($sql);
			$rows = mysql_num_rows($query);
			if($rows != 0)
			{
				while($ii = mysql_fetch_assoc($query))
				{
					$this->message .= "<div class='tcpeople tcsearch'>";
					$username = $ii['username'];
					$name = $ii['real_name'].' '.$ii['real_surname'];
	                $photo = $ii['photo'];
	                $from = $ii['localization'];
					if(file_exists('../../media/images/users/' . $photo . ''))
					{
	                    $image = "<a href='http://" . SITE_DOMAIN . "/" . $username . "'><img src='http://" . SITE_DOMAIN . "/media/images/users/" . $photo . "' class='ppphoto'></a>";
	                } 
					else 
					{
	                    $image = "<a href='http://" . SITE_DOMAIN . "/" . $username . "'><img src='http://" . SITE_DOMAIN . "/media/images/users/photo_default.png' class='ppphoto'></a>";
	                }
					$this->message .= "<div class='tcimage'>".$image."</div>";
					$this->message .= "<div class='tcinfo'><a href=\"http://" . SITE_DOMAIN . "/" . $username . "\"><p class='tcinfoname'>".$name."</p></a><a href=\"http://" . SITE_DOMAIN . "/" . $username . "\"><p>@".$username."</p></a><p>".$from."</p></div>";
					$this->message .= "<div class='tcfoll'>";
					if($username != USER_USERNAME && USER_USERNAME!="") 
					{
	                    $queryfollow = "SELECT * FROM users_friends WHERE username = '" . USER_USERNAME . "' and friend = '" . $username . "'";
	                    $resultfollow = mysql_query($queryfollow);
	                    $follow = mysql_num_rows($resultfollow);
	                    if($follow > 0) {
	                        $end = "<span class='followb$username'><a class='btn btn-danger' name='removefriend' onclick=removefr('$username'); return false;>" . langVar(411) . "</a></span>";
	                    } else {
	                        $end = "<span class='followb$username'><a class='btn btn-success' name='addfriend' onclick=addfr('$username'); return false;>" . langVar(410) . "</a></span>";
	                    }
	                }
	                else $end = "";
					$this->message .= $end."</div><div class='clear'></div></div>";
				}
			}
			else
			{
				$this->message .= '<center><p class="error"><b>'.engine::getlangvar(40).'</b> '.engine::getlangvar(61).'</p></center>';
			}
		}
		return $this->message;
	}
	
	public function getlastusersonline($count)
	{
		$message = '';
		$maxtime = time();
		$maxtime = $maxtime-60;
		$sqlquery = "SELECT username, visit FROM `users` WHERE visit>'".$maxtime."' ORDER BY visit DESC LIMIT 0, $count";
		$query = mysql_query($sqlquery);
		if(mysql_num_rows($query) != 0)
		{	
			while($ii = @mysql_fetch_assoc($query))
			{	
				$loaduser = $ii['username'];
				$loadusersql = "SELECT * FROM users WHERE username='$loaduser'";
				$loaduserquery = mysql_query($loadusersql);
				if(@mysql_num_rows($loaduserquery) != 0)
				{
					while($iii = @mysql_fetch_assoc($loaduserquery))
					{
						$Username = $iii['username'];
						$Name = $iii['real_name'];
						$Surname = $iii['real_surname'];
						$Image = $iii['photo'];
						$message .= '<a href="http://'.SITE_DOMAIN.'/'.$Username.'"><img src="http://'.SITE_DOMAIN.'/media/images/users/'.$Image.'" alt="'.$Username.'" width="40" id="postavatar"/></a>';
					}
				}
			}
		}
		return $message;
	}

	public function getlastfollowingusersonline($count)
	{
		$message = '';
		$maxtime = time();
		$maxtime = $maxtime-60;
		$sqlquery = "SELECT users.username AS username, users.visit AS visit FROM users, users_friends WHERE users_friends.username = '" . USER_USERNAME . "' AND users.username = users_friends.friend AND users.visit>'".$maxtime."' ORDER BY users.visit DESC LIMIT 0, $count";
		$query = mysql_query($sqlquery);
		if(mysql_num_rows($query) != 0)
		{	
			while($ii = @mysql_fetch_assoc($query))
			{	
				$loaduser = $ii['username'];
				$loadusersql = "SELECT * FROM users WHERE username='$loaduser'";
				$loaduserquery = mysql_query($loadusersql);
				if(@mysql_num_rows($loaduserquery) != 0)
				{
					while($iii = @mysql_fetch_assoc($loaduserquery))
					{
						$Username = $iii['username'];
						$Name = $iii['real_name'];
						$Surname = $iii['real_surname'];
						$Image = $iii['photo'];
						$message .= '<a href="http://'.SITE_DOMAIN.'/'.$Username.'"><img src="http://'.SITE_DOMAIN.'/media/images/users/'.$Image.'" alt="'.$Username.'" width="40" id="postavatar"/></a>';
					}
				}
			}
		}
		return $message;
	}
	
	public function notify($user,$type)
	{
		$json = array ('response'=>'success');	
		header('Content-type: application/json'); 
		if($type==0)
		{
			$likessql = "SELECT COUNT(*) FROM likes WHERE post_user='$user' AND viewed != '1' AND user !='$user'";
			$querylikessql = mysql_query($likessql);
			$i = mysql_fetch_assoc($querylikessql);
			$likes = $i['COUNT(*)'];
			$postssql = "SELECT COUNT(*) FROM posts WHERE to_user='$user' AND from_user!='$user' AND viewed != '1'";
			$querypostssql = mysql_query($postssql);
			$ii = mysql_fetch_assoc($querypostssql);
			$posts = $ii['COUNT(*)'];
			$commentsql = "SELECT COUNT(*) FROM comments WHERE post_user='$user' AND from_user!='$user' AND viewed != '1'";
			$querycommentsql  = mysql_query($commentsql);
			$iii = mysql_fetch_assoc($querycommentsql);
			$answers = $iii['COUNT(*)'];
			$json = array("likes" => "$likes","posts" => "$posts","answers" => "$answers");
			echo json_encode($json);
		}
		if($type==1) //Get likes
		{	
			$message = "";
			$sql = "UPDATE likes SET viewed = '1' WHERE post_user='$user' AND viewed != '1'";
			$query = mysql_query($sql);
			$sql = "SELECT * FROM likes WHERE post_user='$user' AND user !='$user' ORDER BY time DESC LIMIT 0, 6";
			$query = mysql_query($sql);
			if(@mysql_num_rows($query) != 0)
			{
				while($ii = mysql_fetch_assoc($query))
				{
					$id = $ii['post_id'];
					$touser = $ii['post_user'];
					$fromuser = $ii['user'];
					$sqlgetphoto = mysql_query("SELECT photo FROM users WHERE username = '$fromuser'");
					$iii = mysql_fetch_assoc($sqlgetphoto);
					$sqlgetpost = mysql_query("SELECT post, image FROM posts WHERE id = $id");
					$post = mysql_fetch_assoc($sqlgetpost);
					if($post['image']!='') $img = ' <i class="fa fa-paperclip"></i>';
					else $img = '';
					if(file_exists('../../media/images/users/tt_'.$iii['photo'].''))
					{
						$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/tt_".$iii['photo']."' id='postavatar'></a>";
					} 
					else
					{
						if(file_exists('../../media/images/users/'.$Image.''))
						{
							$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/".$iii['photo']."' id='postavatar'></a>";
						}
						else
						{
							$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/photo_default.png' id='postavatar'></a>";
						}
					}
					$message .= '<a href="http://'.SITE_DOMAIN.'/'.$touser.'/post/'.$id.'" class="notificationtext">'.engine::getlangvar(806).' <b>'.$fromuser.'</b> '.engine::getlangvar(807).': '.$post['post'].''.$img.'</a><div class="clear"></div></div>';
				}
				$message .= "<div class='notificationitem'><center><a href='http://".SITE_DOMAIN."/account/notifications' class='loadposts' style='width:100%'>".engine::getlangvar(852)."</a></center></div>";
			}
			else
			{
				$message .= engine::getlangvar(370);
			}
			$json = array("response" => "$message");
			echo json_encode($json);		
		}
		if($type==2) //Get new posts
		{	
			$message = "";
			$sql = "UPDATE posts SET viewed = '1' WHERE to_user='$user' AND from_user!='$user' AND viewed = '0'";
			$query = mysql_query($sql);
			$sql = "SELECT id, from_user, post, image, anonymous FROM posts WHERE to_user='$user' AND from_user!='$user' ORDER BY time DESC LIMIT 0, 6";
			$query = mysql_query($sql);
			if(@mysql_num_rows($query) != 0)
			{
				while($ii = mysql_fetch_assoc($query))
				{
					$id = $ii['id'];
					$fromuser = $ii['from_user'];
					$text = $ii['post']; 
					$qa_anonymous = $ii['anonymous']; 
					if($ii['image']!='') $img = ' <i class="fa fa-paperclip"></i>';
					else $img = '';
					$sqlgetphoto = mysql_query("SELECT photo FROM users WHERE username = '$fromuser'");
					$iii = mysql_fetch_assoc($sqlgetphoto);
					if($qa_anonymous=='1') 
					{
						$fromuser = engine::getlangvar(300);
						$message .= "<div class='notificationitem'><p class='notificationimage'><img src='media/images/users/photo_anonymous.png' id='postavatar'></p>";
					}
					else
					{
						if(file_exists('../../media/images/users/tt_'.$iii['photo'].''))
						{
							$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/tt_".$iii['photo']."' id='postavatar'></a>";
						} 
						else
						{
							if(file_exists('../../media/images/users/'.$Image.''))
							{
								$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/".$iii['photo']."' id='postavatar'></a>";
							}
							else
							{
								$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/photo_default.png' id='postavatar'></a>";
							}
						}
					}
					$message .= '<a href="http://'.SITE_DOMAIN.'/'.$user.'/post/'.$id.'" class="notificationtext"><b>'.$fromuser.'</b> '.engine::getlangvar(808).': '.$text.''.$img.'</a><div class="clear"></div></div>';
				}
				$message .= "<div class='notificationitem'><center><a href='http://".SITE_DOMAIN."/account/notifications' class='loadposts' style='width:100%'>".engine::getlangvar(852)."</a></center></div>";
			}
			else
			{
				$message .= engine::getlangvar(370);
			}
			$json = array("response" => "$message");
			echo json_encode($json);		
		}
		if($type==3) //Get comments
		{	
			$message = "";
			$sql = "UPDATE comments SET viewed = '1' WHERE post_user='$user' AND viewed != '1'";
			$query = mysql_query($sql);
			$sql = "SELECT * FROM comments WHERE post_user='$user' AND from_user!='$user' ORDER BY time DESC LIMIT 0, 6";
			$query = mysql_query($sql);
			if(@mysql_num_rows($query) != 0)
			{
				while($ii = mysql_fetch_assoc($query))
				{
					$id = $ii['post_id'];
					$comment = $ii['comment'];
					$fromuser = $ii['from_user'];

					$sqlgetpost = mysql_query("SELECT post, image FROM posts WHERE id = $id");
					$post = mysql_fetch_assoc($sqlgetpost);
					if($post['image']!='') $img = ' <i class="fa fa-paperclip"></i>';
					else $img = '';

					if($fromuser!="")
					{
						$sqlgetphoto = mysql_query("SELECT photo FROM users WHERE username = '$fromuser'");
						$iii = mysql_fetch_assoc($sqlgetphoto);
						if(file_exists('../../media/images/users/tt_'.$iii['photo'].''))
						{
							$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/tt_".$iii['photo']."' id='postavatar'></a>";
						} 
						else
						{
							if(file_exists('../../media/images/users/'.$Image.''))
							{
								$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/".$iii['photo']."' id='postavatar'></a>";
							}
							else
							{
								$message .= "<div class='notificationitem'><a href='http://".SITE_DOMAIN."/".$fromuser."' class='notificationimage'><img src='media/images/users/photo_default.png' id='postavatar'></a>";
							}
						}
						$message .= '<a href="http://'.SITE_DOMAIN.'/'.$user.'/post/'.$id.'" class="notificationtext">'.engine::getlangvar(806).' <b>'.$fromuser.'</b> '.engine::getlangvar(420).': '.$comment.' '.engine::getlangvar(170).': '.$post['post'].''.$img.'</a><div class="clear"></div></div>';
					
					}
					else
					{
						$message .= "<div class='notificationitem'><a class='notificationimage'><img src='media/images/users/photo_anonymous.png' id='postavatar'></a>";
						$message .= '<a href="http://'.SITE_DOMAIN.'/'.$user.'/post/'.$id.'" class="notificationtext"><b>'.engine::getlangvar(837).'</b> '.engine::getlangvar(420).': '.$comment.' '.engine::getlangvar(170).': '.$post['post'].''.$img.'</a><div class="clear"></div></div>';
					}
				}
				$message .= "<div class='notificationitem'><center><a href='http://".SITE_DOMAIN."/account/notifications' class='loadposts' style='width:100%'>".engine::getlangvar(852)."</a></center></div>";
			}
			else
			{
				$message .= engine::getlangvar(370);
			}
			$json = array("response" => "$message");
			echo json_encode($json);		
		}
	}
	
	public function getallnotifications($user)
	{
		$array = array();
		$i = 0;
		$sql = "SELECT * FROM comments WHERE post_user='$user' AND from_user!='$user' ORDER BY time DESC LIMIT 0, 30";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$id = $ii['post_id'];
				$comment = $ii['comment'];
				$fromuser = $ii['from_user'];
				$array[$i]['type'] = '<img src="media/images/qrespondb.png" width="15px" height="15px">';
				$array[$i]['time'] = $ii['time'];
				$array[$i]['data'] = '<a href="http://'.SITE_DOMAIN.'/'.$user.'/post/'.$id.'">'.txt2link(getsmiles($comment)).'</a>';
				if($fromuser=="")
				{
					$array[$i]['info'] = ucfirst(engine::getlangvar(420)).' '.engine::getlangvar(66).' '.engine::getlangvar(837);
				}
				else
				{
					$array[$i]['info'] = ucfirst(engine::getlangvar(420)).' '.engine::getlangvar(66).' <a href="http://'.SITE_DOMAIN.'/'.$fromuser.'">'.$fromuser.'</a>';
				}
				$i++;
			}		
		}
		$sql = "SELECT * FROM users_friends WHERE friend='$user' ORDER BY time DESC LIMIT 0, 25";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$id = $ii['friend'];
				$comment = $ii['comment'];
				$fromuser = $ii['username'];
				$sqli = "SELECT photo FROM users WHERE username='".$ii['username']."'";
				$queryi = mysql_query($sqli);
				if(@mysql_num_rows($queryi) != 0)
				{
					while($iii = mysql_fetch_assoc($queryi))
					{
						$image = $iii['photo'];
						if($image!="")
						{
							if(file_exists('../../media/images/users/'.$image.''))
							{
								$image = '<br><div class="img imgLiquid" style="width:100px; height:100px;margin:0 auto"><img src="media/images/users/'.$image.'" class="notifyimg"/></div><br>';
							} 
							else 
							{
								$image = '<br><div class="img imgLiquid" style="width:100px; height:100px;margin:0 auto"><img src="media/images/users/photo_default.png" class="notifyimg"/></div><br>';
							}
						}
					}
				}
				$array[$i]['type'] = '<img src="media/images/qfollowb.png" width="15px" height="15px">';
				$array[$i]['time'] = $ii['time'];
				$array[$i]['data'] = '<a href="http://'.SITE_DOMAIN.'/'.$fromuser.'">'.$image.engine::getlangvar(875).': '.$fromuser.'</a>';
				$array[$i]['info'] = '<a href="http://'.SITE_DOMAIN.'/'.$fromuser.'">'.$fromuser.'</a> '.engine::getlangvar(876);
				$i++;
			}		
		}
		$sql = "SELECT * FROM gifts WHERE to_user='$user' ORDER BY time DESC LIMIT 0, 20";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$id = $ii['from_user'];
				$sqli = "SELECT image FROM giftstype WHERE id=".$ii['gift_id'];
				$queryi = mysql_query($sqli);
				if(@mysql_num_rows($queryi) != 0)
				{
					while($iii = mysql_fetch_assoc($queryi))
					{
						$imageg = $iii['image'];
						if(file_exists('../../media/images/gifts/'.$imageg.''))
						{
							$gimage = '<br><img src="media/images/gifts/'.$imageg.'" class="notifyimg"/><br>';
						} 
						else 
						{
							$gimage = '<br><img src="media/images/qgiftb.png" class="notifyimg"/><br>';
						}
					}
				}
				if($ii['type']==0) 
				{
					$fromuser = engine::getlangvar(878).' ';
					$data = $gimage.engine::getlangvar(877).' '.lcfirst(engine::getlangvar(830));
				}
				elseif($ii['type']==1)
				{
					$fromuser = '<a href="http://'.SITE_DOMAIN.'/'.$ii['from_user'].'">'.$ii['from_user'].'</a> ';
					$data = $gimage.engine::getlangvar(877).' '.lcfirst(engine::getlangvar(831));
				}
				elseif($ii['type']==2) 
				{
					$fromuser = '<a href="http://'.SITE_DOMAIN.'/'.$ii['from_user'].'">'.$ii['from_user'].'</a> ';
					$data = $gimage.engine::getlangvar(877).' '.lcfirst(engine::getlangvar(832));
				}
				$array[$i]['type'] = '<img src="media/images/qgiftb.png" width="15px" height="15px">';
				$array[$i]['time'] = $ii['time'];
				$array[$i]['data'] = '<a href="http://'.SITE_DOMAIN.'/'.$user.'/gifts/0">'.$data.'</a>';
				$array[$i]['info'] = $fromuser.engine::getlangvar(879);
				$i++;
			}		
		}
		$sql = "SELECT * FROM posts WHERE to_user='$user' AND from_user!='$user' ORDER BY time DESC LIMIT 0, 20";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$id = $ii['id'];
				$touser = $ii['to_user'];
				$fromuser = $ii['from_user'];
				$post = getsmiles($ii['post']);
				$array[$i]['type'] = '<img src="media/images/qcommentb.png" width="15px" height="15px">';
				$array[$i]['time'] = $ii['time'];
				$qa_image = $ii['image'];
				if($qa_image!="")
				{
					if(file_exists('../../media/images/answers/t_'.$qa_image.''))
					{
						$image = '<br><img src="media/images/answers/t_'.$qa_image.'" width="200px"/><br>';
					} 
					else 
					{
						$image = '<br><img src="media/images/answers/'.$qa_image.'" width="200px"/><br>';
					}
				}
				else $image="";
				$array[$i]['data'] = '<a href="http://'.SITE_DOMAIN.'/'.$touser.'/post/'.$id.'">'.$image.txt2link(getsmiles($post)).'</a>';
				$array[$i]['info'] = ucfirst(engine::getlangvar(874)).' '.engine::getlangvar(66).' <a href="http://'.SITE_DOMAIN.'/'.$touser.'">'.$touser.'</a>';
				$i++;
			}		
		}
		$sql = "SELECT * FROM likes WHERE post_user='$user' AND user !='$user' ORDER BY time DESC LIMIT 0, 30";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$id = $ii['post_id'];
				$sql = "SELECT post, image FROM posts WHERE id='$id'";
				$queryi = mysql_query($sql);
				while($iii = mysql_fetch_assoc($queryi))
				{
					$post = $iii['post'];
					$qa_image = $iii['image'];
					if($qa_image!="")
					{
						if(file_exists('../../media/images/answers/t_'.$qa_image.''))
						{
							$image = '<br><img src="media/images/answers/t_'.$qa_image.'" width="200px"/><br>';
						} 
						else 
						{
							$image = '<br><img src="media/images/answers/'.$qa_image.'" width="200px"/><br>';
						}
					}
					else $image="";
				}
				$touser = $ii['to_user'];
				$fromuser = $ii['user'];
				$array[$i]['type'] = '<img src="media/images/qlikeb.png" width="15px" height="15px">';
				$array[$i]['time'] = $ii['time'];
				$array[$i]['data'] = '<a href="http://'.SITE_DOMAIN.'/'.$touser.'/post/'.$id.'">'.$image.txt2link(getsmiles($post)).'</a>';
				$array[$i]['info'] = '<a href="http://'.SITE_DOMAIN.'/'.$fromuser.'">'.$fromuser.'</a>  '.engine::getlangvar(807);
				$i++;
			}	
		}	
		return $array;
	}
	
	public function stream($stream_type)
	{
		$message = "";
		$json = array ('response'=>'success');	
		header('Content-type: application/json'); 
		if($stream_type=="all") $sql = "SELECT * FROM posts ORDER BY time desc LIMIT 0, 30";
		if($stream_type=="friends") $sql = "SELECT posts.id, posts.to_user, posts.post, posts.from_user, posts.image, posts.status, posts.anonymous, posts.ip, posts.time FROM posts, users_friends WHERE users_friends.username = '" . USER_USERNAME . "' AND posts.from_user = users_friends.friend ORDER BY posts.time desc LIMIT 0, 30";
		$query = mysql_query($sql);
		$i=1;
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$qa_id = $ii['id']; 
				$qa_to_user = $ii['to_user']; 
				$post = txt2link(getsmiles($ii['post'])); 
				$qa_from_user = $ii['from_user'];  
				$qa_image = $ii['image'];
				$qa_status = $ii['status']; 
				$qa_anonymous = $ii['anonymous']; 
				$qa_ip = $ii['ip']; 
				$qa_time = $ii['time']; 
				$sqlgetphoto = mysql_query("SELECT photo FROM users WHERE username = '$qa_from_user'");
					$iii = mysql_fetch_assoc($sqlgetphoto);
					if(!$iii['photo']) $iii['photo'] = "photo_anonymous.png";
				$message .= '<div class="post';
				if($i%2==0) $message .= ' postbg';
				$i++;
				$message .= '" id="post'.$qa_id.'"><div id="postimage">';
				if(file_exists('../../media/images/users/tt_'.$iii['photo'].''))
				{
					$message .= "<a href=\"http://".SITE_DOMAIN."/".$qa_from_user."\"><div class='img imgLiquid' style='width:60px; height:60px'><img src=\"media/images/users/tt_".$iii['photo']."\" id=\"postavatar\"/></div></a></div>";
				}
				else 
				{
					$message .= "<a href=\"http://".SITE_DOMAIN."/".$qa_from_user."\"><div class='img imgLiquid' style='width:60px; height:60px'><img src=\"media/images/users/".$iii['photo']."\" id=\"postavatar\"/></div></a></div>";
				}
				$message .= '<div id="postbody"><h4>'.$post.'</h4>'; 
				if($qa_image!="")
				{
					$message .= '<a href="http://'.SITE_DOMAIN.'/image/'.$qa_from_user.'/'.$qa_id.'"><img src="media/images/answers/'.$qa_image.'" width="300px"/></a>';
				}
				$message .= '</div>';
				$message .= "<div id=\"postInfo\"><p>";
				$message .= ''.getlikes($qa_id,8,$qa_to_user,$qa_id).'';
				$message .= counttime(usertime($qa_time));
				switch($qa_anonymous)
				{	case 0:	$message .= ' '.langVar(66).' <a href="http://'.SITE_DOMAIN.'/'.$qa_from_user.'">'.$qa_from_user.'</a> '.langVar(90).' <a href="http://'.SITE_DOMAIN.'/'.$qa_to_user.'">'.$qa_to_user.'</a>';
							break;
					case 1:	$message .= ' '.langVar(82).' '.langVar(90).' <a href="http://'.SITE_DOMAIN.'/'.$qa_to_user.'">'.$qa_to_user.'</a>';
							break;
				}
				$message .= '</p></div></div>';
				$message .= '<div class="clear"></div>';
			}
		}
		$json = array("response" => "$message","id" => "post".$qa_id);
		echo json_encode($json);	
	}

	public function streamverifynew($time)
    {
        $message = "";
        $json = array('response' => 'success');
        header('Content-type: application/json');
        $sql = "SELECT COUNT(*) AS total FROM posts WHERE status='1' AND time>'$time'";
        $query = mysql_query($sql);
        if(mysql_num_rows($query) != 0) 
        {
            while ($ii = mysql_fetch_assoc($query)) 
            {
                $total = $ii['total'];
                if($total != 0) 
                {
                    $message = $total;
                } 
                else 
                {
                    $message = 0;
                }
            }
            $json = array("response" => "$message");
        } 
        else 
        {
            $json = array("response" => 0);
        }
        echo json_encode($json);
    }
	
	public function add($post, $to_user, $anonymous, $photo_file, $sqlTable = "posts")
	{
		$this->photo = $photo_file = $_FILES["photo"];
		$this->post = text_filter($post, 1); 
		$this->to_user = text_filter($to_user, 1);
		$this->anonymous = text_filter($anonymous, 1); 
		$this->status = 0; 
		$photo_db = '';
		$this->time = time();

		$this->photo = $photo_file = $_FILES["photo"];
		$file = isset($this->photo) ? $this->photo : FALSE;
		
		if($_FILES['photo']['size']>0 && eregi("^image\/(pjpeg|jpeg|jpg|png|gif|bmp)$", $file["type"]))
		{
			preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $file["name"], $ext);
			$photo_crypt_name = engine::crypts($username.time().'', 1, 0) . "." . $ext[1];
			$root = realpath($_SERVER["DOCUMENT_ROOT"]);
			$directory = "../../media/images/answers/" . '' . $photo_crypt_name;
			$tdirectory = "../../media/images/answers/t_" . $photo_crypt_name;
			move_uploaded_file($file["tmp_name"], $directory);
			engine::resizeimg($directory, $tdirectory, 300, 200); 
			$photo_db = $photo_crypt_name;
		}

		if(($this->post!='' || $photo_db!='') && strlen($this->post) <= O_LENGTH)
		{
			if($this->anonymous == 0)
			{
				if(SESSION_STATUS != false)
				{
					$this->from_user = ''.USER_USERNAME.'';
					$this->anonymous == 0;
					/*Get point */
					if(GET_FREE_POINTS==1)
					{
						$numb = rand(1, 1); 
						if($numb==1) 
						{
							$query = mysql_query("UPDATE users SET points=points+1 WHERE username='$this->from_user'");
						}
					}
				}
			}			
			else if($this->anonymous == 1)
			{
				$this->from_user = "";
				$this->anonymous == 1;
			}
			if(engine::profileuserexists($this->to_user) != 0)
			{
				if(engine::getuserdata($this->to_user, "STATUS") == 1)
				{
					$mysqlmessage =  "INSERT INTO $sqlTable ";
					$mysqlmessage .= "(to_user, post, image, from_user, status, viewed, anonymous, ip, time) ";
					$mysqlmessage .= "VALUES ";
					$mysqlmessage .= "('$this->to_user', '$this->post', '$photo_db', '$this->from_user', '0', '0', '$this->anonymous', '$this->ip', '$this->time')";
					if(mysql_query($mysqlmessage) != 0)
					{
						header('Location: http://'.SITE_DOMAIN.'/'.$to_user);
						exit;
					}
					else 
					{ 
						die(''.engine::getlangvar(39).''); 
					}
				}
			}
		}
		header('Location: http://'.SITE_DOMAIN.'/'.$to_user);
		exit;
	}
	
	public function like($id, $user, $sqlTable = "likes")
	{
		$id = text_filter($id, 1);
		$user = text_filter($user, 1);
		$json = array ('response'=>'success');
		if(SESSION_STATUS != false)
		{
			$sql = "SELECT * FROM $sqlTable WHERE post_id = '$id' AND user = '$user'";
			$query = mysql_query($sql);
			if(@mysql_num_rows($query) != 0)
			{
				$mysqlmessage = "DELETE FROM $sqlTable WHERE post_id = '$id' AND user = '$user'";
				if(mysql_query($mysqlmessage) != 0)
				{
					header('Content-type: application/json'); 
					$json = array("type" => "delete");
					echo json_encode($json);
				}
				else 
				{ 
					die(''.engine::getlangvar(39).''); 
				}
			}
			else
			{
				$touser = "SELECT to_user, from_user FROM posts WHERE id = '$id' ";
				$querytouser = mysql_query($touser);
				$tousers = mysql_fetch_assoc($querytouser);
				$touser = $tousers['to_user'];
				$fromuser = $tousers['from_user'];
				$time = time();
				$mysqlmessage =  "INSERT INTO $sqlTable ";
				$mysqlmessage .= "(post_id, user, to_user, post_user, time) ";
				$mysqlmessage .= "VALUES ";
				$mysqlmessage .= "('$id', '$user', '$touser', '$fromuser', '$time')";
				if(mysql_query($mysqlmessage) != 0)
				{
					header('Content-type: application/json'); 
					$json = array("type" => "add");
					echo(json_encode($json)); 
				}
				else 
				{ 
					die(''.engine::getlangvar(39).''); 
				}
			}
		}	
	}
	
	public function getlangvar($id)
	{
		global $template_session;
		if(isset($id) && is_int($id))
		{
			return $template_session->getlangval($id);
		}
	}
	
	public function delete($id)
	{
		$this->username = ''.USER_USERNAME.'';
		$this->qa_id = base64_decode($id);
		$back_user = $this->username;
		if(isset($this->qa_id) && SESSION_STATUS != false)
		{
			$sql = mysql_query("SELECT to_user FROM posts WHERE id = '$this->qa_id'");
			$to_user = mysql_fetch_array($sql);
			$back_user = $to_user['to_user'];
			$sql = mysql_query("SELECT * FROM posts WHERE id = '$this->qa_id' AND (from_user = '$this->username' OR to_user = '$this->username')");
			if(@mysql_num_rows($sql) != 0)
			{
				if(mysql_query("DELETE FROM posts WHERE id = '$this->qa_id'") != 0)
				{
					if(mysql_query("DELETE FROM comments WHERE post_id = '$this->qa_id'") != 0)
					{
						if(mysql_query("DELETE FROM likes WHERE post_id = '$this->qa_id'") != 0)
						{
							header('Location: http://'.SITE_DOMAIN.'/'.$back_user);
							exit;
						}
						else 
						{ 
							die(''.engine::getlangvar(39).' Delete function error. Contact admin!'); 
						}
					}
				}
			}
		}
		header('Location: http://'.SITE_DOMAIN.'/'.$back_user);
		exit;
	}
	
	public function checkname($name)
	{
		$this->username = text_filter($name, 1);
		$max_lenght = 20;
		$min_lenght = 4;
		if(strlen($this->username) < $min_lenght)
		{
			$json['error'] = ''.engine::getlangvar(69).'';
		}
		else if(strlen($this->username) > $max_lenght)
		{
			$json['error'] = ''.engine::getlangvar(70).'';
		}
		else if($this->username == "install" || 
				$this->username == "config" || 
				$this->username == "help" || 
				$this->username == "privacy" || 
				$this->username == "uploads" || 
				$this->username == "core" || 
				$this->username == "images" || 
				$this->username == "exit" || 
				$this->username == "login" || 
				$this->username == SITE_NAME ||
				$this->username == "recovery" ||
				$this->username == "settings" ||
				$this->username == "search" ||
				$this->username == "options" ||
				$this->username == "friends" ||
				$this->username == "followers" ||
				$this->username == "remove" ||
				$this->username == "admin" ||
				$this->username == "administration" ||
				$this->username == "delete" ||
				$this->username == "people" ||
				$this->username == "change" ||
				$this->username == "disable" ||
				$this->username == "enable" ||
				$this->username == "register")
		{
			$json['error'] = ''.engine::getlangvar(71).'';
		}
		else if(engine::profileuserexists($this->username) != 0)
		{
			$json['error'] = ''.engine::getlangvar(72).'';
		}
		else if(strstr($this->username, ' ')!= false || strstr($this->username, ',')!= false || strstr($this->username, '.')!= false || strstr($this->username, '@')!= false)
		{
			$json['error'] = ''.engine::getlangvar(73).'';
		}
		else
		{
			$json['success'] = NULL;
		}
		$encoded = json_encode($json);
		die($encoded);
	}

	public function createuseraccount($username, $password, $name, $surname, $email)
	{
		if(!empty($username) && !empty($password) && !empty($name) && !empty($email))
		{
			$this->username = text_filter($username, 1); 
			$this->password = engine::crypts(engine::crypts(engine::crypts($password, "MD5", 0), 2, 0), "SHA1", 0); 
			$this->name = text_filter($name, 1);
			$this->surname = text_filter($surname, 1); 
			$this->rank = 0; 
			$this->email = text_filter($email, 1); 
			$this->website = 'http://'.SITE_DOMAIN.'/'.$this->username.''; 
			$this->location = ''.engine::getlangvar(78).''; 
			$this->about_me = ''.engine::getlangvar(79).'';
			$this->user_status = ''.engine::getlangvar(80).''; 
			$this->photo = "photo_default.png";
			$this->status = 1; 
			$this->ip = ''.USER_IP.''; 
			$this->protection = 1; 
			$this->reg_date = time();
			if(!empty($this->username) && strlen($this->username) > 3)
			{
				if(engine::usernameexists($this->username) == "Username Exists")
				{
					$_SESSION['msg'] = 2;
					$this->headerin("account/signup");
					exit;
				}
			}
			if(!empty($this->email) && strlen($this->email) > 5)
			{
				if(engine::emailalreadyexists($this->email) == "Email Exists")
				{
					$_SESSION['msg'] = 1;
					$this->headerin("account/signup");
					exit;
				}
			}
			if(!empty($password) && strlen($password) < 4)
			{
				$_SESSION['msg'] = 1;
				$this->headerin("account/signup");
				exit;
			}
			$mysqlmessage["user"] = "INSERT INTO users ";
			$mysqlmessage["user"] .= "(username, password, real_name, real_surname, points, rank, verified, email, website, localization, bio, user_status, photo, cover, status, ip, anonymous_view, reg_date) ";
			$mysqlmessage["user"] .= "VALUES ";
			$mysqlmessage["user"] .= "('$this->username', '$this->password', '$this->name', '$this->surname', '1', '0', '$this->rank', '$this->email', ";
			$mysqlmessage["user"] .= "'$this->website', '$this->location', '$this->about_me', '$this->user_status', '$this->photo', '', ";
			$mysqlmessage["user"] .= "'$this->status', '$this->ip', '$this->protection', '$this->reg_date')";
			if(mysql_query($mysqlmessage["user"]) != 0)
			{
				if(SESSION_STATUS != true)
				{
					$this->checkcookies($this->username, $password);
					exit;
				}
			}
		}
	}
	
	public function createuseraccountsocial($username, $email, $network, $id, $fname, $lname, $photo, $country, $city)
	{
		if(!empty($username))
		{
			$this->username = text_filter($username, 1);  
			$this->name = text_filter($fname, 1);
			$this->surname = text_filter($lname, 1); 
			$this->rank = 0; 
			$this->email = text_filter($email, 1); 
			$this->website = 'http://'.SITE_DOMAIN.'/'.$this->username.''; 
			$this->location = ''.$country.' '.$city.''; 
			$this->about_me = ''.engine::getlangvar(79).'';
			$this->user_status = ''.engine::getlangvar(80).''; 
			$this->photo = "photo_default.png";
			$this->status = 1; 
			$this->ip = ''.USER_IP.''; 
			$this->protection = 1; 
			$this->reg_date = time();
			
			if(!empty($this->username) && strlen($this->username) > 3)
			{
				if(engine::usernameexists($this->username) == "Username Exists")
				{
					$_SESSION['msg'] = 2;
					$this->headerin("account/signup");
					exit;
				}
			}
			if(!empty($this->email) && strlen($this->email) > 5)
			{
				if(engine::emailalreadyexists($this->email) == "Email Exists")
				{
					$_SESSION['msg'] = 1;
					$this->headerin("account/signup");
					exit;
				}
			}
			
			if($photo!="https://ulogin.ru/img/photo_big.png" || $photo!="")
			{
				if(substr($photo,0,8)=='https://') 
				{
					$photo = substr($photo,8);
					$photo = "http://" . $photo;
				}
				preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $photo, $ext);
				$photo_crypt_name = engine::crypts(''.$username.''.time().'', 1, 0) . "." . $ext[1];
				$root = realpath($_SERVER["DOCUMENT_ROOT"]);
				$directory = IMG_PATH . '' . $photo_crypt_name;				
				$image = file_get_contents($photo);
				file_put_contents($directory, $image);
				$this->photo = $photo_crypt_name;
			}
			
			$mysqlmessage["user"] = "INSERT INTO users ";
			$mysqlmessage["user"] .= "(username, password, real_name, real_surname, points, rank, verified, email, website, localization, bio, user_status, photo, cover, status, ip, anonymous_view, reg_date, $network) ";
			$mysqlmessage["user"] .= "VALUES ";
			$mysqlmessage["user"] .= "('$this->username', '', '$this->name', '$this->surname', '1', '0', '$this->rank', '$this->email', ";
			$mysqlmessage["user"] .= "'$this->website', '$this->location', '$this->about_me', '$this->user_status', '$this->photo', '', ";
			$mysqlmessage["user"] .= "'$this->status', '$this->ip', '$this->protection', '$this->reg_date', '$id')";
			if(mysql_query($mysqlmessage["user"]) != 0)
			{
				if(SESSION_STATUS != true)
				{
					$this->checkcookies("", "", $network, $id);
					unset($_SESSION['regnetwork']);
					unset($_SESSION['regid']);
					unset($_SESSION['regfirst_name']);
					unset($_SESSION['reglast_name']);
					unset($_SESSION['regbdate']);
					unset($_SESSION['regphoto_big']);
					unset($_SESSION['regcountry']);
					unset($_SESSION['regcity']);
					exit;
				}
			}
		}
	}	
	
	public function getusernamebyid($uID)
	{
		if(isset($uID) && is_numeric($uID))
		{
			$sql = @mysql_query("SELECT * FROM users WHERE id = '$uID'") or die(mysql_error());
			$readdata = @mysql_fetch_assoc($sql);
			return $readdata["username"];
		}
	}
	
	public function getallgifts()
	{
		$sql = "SELECT * FROM giftstype ORDER BY name";
		$query = mysql_query($sql);
		$message = '';
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$message .= '<option value="'.$ii['id'].'">'.$ii["name"].'</option>';
			}
		}
		return $message;
	}
	
	public function getlastusergifts($user)
	{
		$this->message = '';
		$maxtime = mktime(date("h"), date("i"), date("s"), date("m"), date("d")-7, date("Y"));
		$sql = "SELECT id, gift_id, position_x, position_y FROM gifts WHERE to_user='$user' AND time>'$maxtime' ORDER BY time DESC";
		$query = mysql_query($sql);
		if(@mysql_num_rows($query) != 0)
		{
			while($ii = mysql_fetch_assoc($query))
			{
				$sqlimage = @mysql_query("SELECT image FROM giftstype WHERE id = '".$ii['gift_id']."'") or die(mysql_error());
				$readimage = @mysql_fetch_assoc($sqlimage);
				$image = $readimage["image"];
				if($image)
				{
					if($user==USER_USERNAME)
					{
						$this->message .= '<img src="'.GIFTS_IMG_PATH.''.$image.'" class="gift" id="udraggable" title="'.$ii['id'].'" style="position:absolute;top:'.$ii['position_x'].'px; left:'.$ii['position_y'].'px;transition:none;-moz-transition:none;-webkit-transition:none"/>';
					}
					else
					{
						$this->message .= '<img src="'.GIFTS_IMG_PATH.''.$image.'" class="gift" id="draggable" style="position:absolute;top:'.$ii['position_x'].'px; left:'.$ii['position_y'].'px;transition:none;-moz-transition:none;-webkit-transition:none"/>';
					}
				}
			}
		}
		return $this->message;
	}
	
	public function giftposition($giftid, $posx, $posy)
	{
		if(SESSION_STATUS)
		{
			$sql = @mysql_query("SELECT to_user FROM gifts WHERE id=$giftid");
			$readdata = @mysql_fetch_assoc($sql);
			if($readdata["to_user"]==USER_USERNAME)
			{
				$sql = "UPDATE gifts SET position_x=$posx, position_y=$posy WHERE id=$giftid";
				$query = mysql_query($sql);
				header('Content-type: application/json'); 
				$json = array("done" => "yes");
				echo json_encode($json);
			}
			else
			{
				header('Content-type: application/json'); 
				$json = array("done" => "$giftid");
				echo json_encode($json);
			}
		}
	}

	public function removeusergift($id, $userid)
	{
		$this->id = text_filter($id, 1);
		if(SESSION_STATUS != false)
		{
			if(engine::getuserrights("TAKE_RANK") != false || engine::getuserrights("SUPREME_COMMANDS"))
			{
				if(is_numeric($this->id))
				{
					$query = "DELETE FROM gifts WHERE id = '$id'";
					if(mysql_query($query) != 0)
					{
						$_SESSION['msg'] = 2;
						$this->headerin("administration/edit_user_gifts.php?id=$userid");
						exit;
					}
					else
					{
						$_SESSION['msg'] = 4;
						$this->headerin("administration/edit_user_gifts.php?id=$userid");
						exit;
					}
				}
			}
		}
	}
	
	public function sendgift($id, $type, $fromuser, $touser)
	{
		if(SESSION_STATUS != false && is_numeric($id))
		{
			if($type==0 || $type==1 || $type==2) 
			{
				if(engine::profileuserexists($fromuser) != 0 && engine::getuserdata($this->username, "POINTS") >= GIFT_PRICE)
				{
					$query = "INSERT INTO gifts (to_user, from_user, gift_id, type, text, time, position_x, position_y) VALUES ('$touser', '$fromuser', $id, '$type', '', '".time()."', 60, 670)";
					if(mysql_query($query) != 0)
					{
						$querytwo = "UPDATE users SET points=points-".GIFT_PRICE." WHERE username='$fromuser'";
						if(mysql_query($querytwo) != 0)
						{
							$this->headerin("$touser");
							exit;
						}
						else
						{
							$this->headerin("$touser");
							exit;
						}
					}
					else
					{
						$_SESSION['msg'] = 4;
						$this->headerin("$touser/gift");
						exit;
					}
				}
			}
		}
	}
	
	public function emailalreadyexists($email)
	{
		$this->email = text_filter($email, 1);
		if(isset($this->email) === true)
		{
			$result = @mysql_query("SELECT * FROM users WHERE email = '$this->email'");
			if(@mysql_num_rows($result) != 0)
			{
				return "Email Exists";
			}
			else
			{
				return "Email Avaliable";
			}
		}
	}
	
	public function usernameexists($username)
	{
		$this->username = text_filter($username, 1);
		if(isset($this->username) === true)
		{
			$result = @mysql_query("SELECT * FROM users WHERE username = '$this->username'");
			if(@mysql_num_rows($result) != 0)
			{
				return "Username Exists";
			}
			else
			{
				return "Username Avaliable";
			}
		}
	}
	
	public function savevisit()
	{
		$sqlquery = mysql_query("UPDATE users SET visit='".time()."' where username='".USER_USERNAME."'");
	}

	public function toppeople($type)
    {
        $message = "";
        $nr = 20;
		$i = 1;
        $json = array('response' => 'success');
        header('Content-type: application/json');
        switch($type)
        {
            case '1': $sql = "SELECT username AS user, points AS count FROM `users` WHERE status='1' ORDER BY points DESC LIMIT 0, $nr"; $text = '' . langVar(867) . ''; break;
            case '2': $sql = "SELECT to_user AS user, COUNT(*) AS count FROM `posts` GROUP BY to_user ORDER BY COUNT(*) DESC LIMIT 0, $nr"; $text = '' . langVar(868) . ''; break;
            case '3': $sql = "SELECT friend AS user, COUNT(*) AS count FROM `users_friends` WHERE status!=0 GROUP BY friend ORDER BY COUNT(*) DESC LIMIT 0, $nr"; $text = '' . langVar(869) . ''; break;

        }
        $query = mysql_query($sql);
        if(@mysql_num_rows($query) != 0) 
        {
            while ($ii = mysql_fetch_assoc($query)) 
            {
				$message .= "<div class='tcpeople'><div class='tccounter'><h1>#".$i."</h1></div>";
				$username = $ii['user'];
				$count = $ii['count'];
                $photo = engine::getuserdata($username, "PHOTO");
				if(file_exists('../../media/images/users/' . $photo . ''))
				{
                    $image = "<a href='http://" . SITE_DOMAIN . "/" . $username . "'><div class='img imgLiquid' style='width:75px; height:75px'><img src='http://" . SITE_DOMAIN . "/media/images/users/" . $photo . "' class='ppphoto'></div></a>";
                } 
				else 
				{
                    $image = "<a href='http://" . SITE_DOMAIN . "/" . $username . "'><div class='img imgLiquid' style='width:75px; height:75px'><img src='http://" . SITE_DOMAIN . "/media/images/users/photo_default.png' class='ppphoto'></div></a>";
                }
				$status = engine::getuserdata($username, "USER_STATUS");
				$bio = engine::getuserdata($username, "BIO");
				$message .= "<div class='tcimage'>".$image."</div>";
				$message .= "<div class='tcinfo'><a href='http://".SITE_DOMAIN."/".$username."'>@".$username."</a></p><p>".$text.": ".$count."</p><p>".$status."</p></div>";
				$message .= "<div class='tcfoll'>";
				if($username != USER_USERNAME && USER_USERNAME!="") 
				{
                    $queryfollow = "SELECT * FROM users_friends WHERE username = '" . USER_USERNAME . "' and friend = '" . $username . "'";
                    $resultfollow = mysql_query($queryfollow);
                    $follow = mysql_num_rows($resultfollow);
                    if($follow > 0) {
                        $end = "<span class='followb$username'><a class='btn btn-danger' name='removefriend' onclick=removefr('$username'); return false;>" . langVar(411) . "</a></span>";
                    } else {
                        $end = "<span class='followb$username'><a class='btn btn-success' name='addfriend' onclick=addfr('$username'); return false;>" . langVar(410) . "</a></span>";
                    }
                }
                else $end = "";
				$message .= $end."</div><div class='clear'></div></div>";
				$i++;
			}
        }
        $json = array("response" => "$message");
        echo json_encode($json);
    }

    public function verified($user,$type)
	{
		$user = text_filter($user, 1);
		$type = text_filter($type, 1);
		$json = array ('response'=>'success');
		if(engine::getuserrights("SUPREME_COMMANDS"))
		{	
			if($type==0 || $type==1)
			{
				$sql = "UPDATE users SET verified = '$type' where username = '$user'";
				$query = mysql_query($sql);
				header('Content-type: application/json'); 
				$json = array("done" => "yes, verified done");
				echo json_encode($json);
			}
			else
			{
				header('Content-type: application/json'); 
				$json = array("done" => "Value 0 or 1!");
				echo json_encode($json);
			}
		}
		else
		{
			header('Content-type: application/json'); 
			$json = array("done" => "no");
			echo json_encode($json);
		}
	}

	public function addpoints($type, $id, $buyerEmail, $ItemQty)
	{
		$query = "UPDATE users SET points=points+".$ItemQty." WHERE username='".USER_USERNAME."'";
		if(mysql_query($query) != 0) 
		{
			$query = "INSERT INTO payments (type, transaction_id, payer_email, user, quantity, date) VALUES ('$type', '$id', '$buyerEmail', '".USER_USERNAME."', $ItemQty, '".time()."')";
			if(mysql_query($query) != 0) 
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
		else 
		{
			return 0;
		}
	}
	
	public function getalllikes($id)
    {
        $message = "<div class='popuptop'><a class='popupclose' onclick='closelikes();'>x</a></div><div class='popupcontent'>";
        $json = array('response' => 'success');
        header('Content-type: application/json');
        $sql = "SELECT * FROM likes WHERE post_id = " . $id . " ORDER BY id DESC LIMIT 0, 100"; // 100 MAX
        $query = mysql_query($sql);
        if(@mysql_num_rows($query) != 0) {
            while ($ii = mysql_fetch_assoc($query)) {
                $message .= "<div class='popuppeople'>";
                $c_user = $ii['user'];
                $querystatus = mysql_query("SELECT user_status FROM users WHERE username = '$c_user'");
                $status = mysql_fetch_array($querystatus);
                $sqlgetphoto = mysql_query("SELECT photo FROM users WHERE username = '$c_user'");
                $iii = mysql_fetch_assoc($sqlgetphoto);
                if(file_exists('../../media/images/users/' . $iii['photo'] . '')) {
                    $message .= "<div class='popupimage'><a href='http://" . SITE_DOMAIN . "/" . $c_user . "'><img src='media/images/users/" . $iii['photo'] . "'></a></div>";
                } else {
                    $message .= "<div class='popupimage'><a href='http://" . SITE_DOMAIN . "/" . $c_user . "'><img src='media/images/users/photo_default.png'></a></div>";
                }
                $message .= "<div class='popupinfo'><a href='http://" . SITE_DOMAIN . "/" . $c_user . "'><span class='popuphashtag'>@" . $c_user . "</span><br>" . $status['user_status'] . "</a></div>";
                if($c_user != USER_USERNAME) {
                    $queryfollow = "SELECT * FROM users_friends WHERE username = '" . USER_USERNAME . "' and friend = '" . $c_user . "'";
                    $resultfollow = mysql_query($queryfollow);
                    $follow = mysql_num_rows($resultfollow);
                    if($follow > 0) {
                        $message .= "<div class='popupfollow'><span class='followb$c_user'><a class='largebtn btn btn-danger' name='removefriend' onclick=removefr('$c_user'); return false;>" . langVar(411) . "</a></span></div>";
                    } else {
                        $message .= "<div class='popupfollow'><span class='followb$c_user'><a class='largebtn btn btn-success' name='addfriend' onclick=addfr('$c_user'); return false;>" . langVar(410) . "</a></span></div>";
                    }
                }
                $message .= "<div class='clear'></div></div>";
            }
        }
        $message .= "</div>";
        $json = array("response" => "$message");
        echo json_encode($json);
    }
}
?>