<?php
/*
fiemeCP - BETA.
Written by, and managed by xDario.

The script may be altered at wish, but redistributing any part of it, even with credets, is prohibited. Currently, only myself and my website (http://www.dario-ml.com/) along with kryptodev are aloud to host my script.

©2011 xDario (created for Ohai Online)

You must provide a thanks on the page from which this is called, unless you have donated. If I find my class used without copyright, or a mention of appreciation, I will pursude you. Fiesta servers aren't thousands, so you're not hard to spot out.

Page: class.fiemecp_functions.php
Last Change: 30 June 2011
*/

if (!defined('IN_FIEME'))
{
	die("canno't directly access this page");
}

class fiemecp_class
{
	//define the variables that we need to talk to the server
	var $server_name;
	var $dbacc;
	var $dbchar;
	var $install_dir;
	
	/*
	This defines our class, and how it's called from the php funtion
	For it to work, you need to have a working SQL database.
	
	$controlpanel = new user_cp_class();
	*/
	function __construct()
	{	
		global $lang;
		global $cfg;
		
		$this->lang = $lang;
		
		$serverName = $cfg['database_host'];
		
		//connect to tha account database
		$dbacc = sqlsrv_connect( $serverName, array("Database"=>"$cfg[database_account]"));
		if( $dbacc === false ) die( print_r(sqlsrv_errors()) );
		
		//connect to the character database
		$dbchar = sqlsrv_connect( $serverName, array("Database"=>"$cfg[database_characters]"));
		if( $dbchar === false ) die( print_r(sqlsrv_errors()) );
		
		$this->server_name = $cfg['srv_name'];
		$this->install_dir = $cfg['script_root'];
		
		$this->dbacc =& $dbacc;
		$this->dbchar =& $dbchar;
		
		//functions for details on script. MUST BE LEFT INTACT, UNLESS PRIOR CONSENT!!! Required for debugging, and updates:
		if (@$_GET['class_'] == 'version')
		{
			echo FIEME_REV;
		}
	}
		
	/*
	Did our sql return any errors?
	*/
	function check_query_success($result)
	{
		if (!$result)
		{
			return 0;
		}
		else
		{
			return 1; 
		}
	}
	
	/*
	Dump login data to database, to make sure logins are valid and such.
	*/
	function track_login($username, $password, $ip, $success, $cookie_login=0, $admin=0, $time=0)
	{
		global $settings;
		
		if ( ( $settings->logging_logins == 1 && $admin==1 ) || ( $settings->logging_logins == 2 ) )
		{
			if ($time == 0)
			{
				$time = time();
			}
			
			if ((($settings->logging_logins_passwords == 0) || ( ($settings->logging_logins_passwords == 1) && $admin == 0)) || ( ($settings->logging_logins_passwords_conditions == 0) && ($success == 1) ) )
			{
				$password = "";
			}
			
			$sql = "INSERT INTO [Account].[dbo].[fLoginLog] ([username],[password],[ip],[time],[is_admin_login],[success],[login_cookie]) VALUES (?,?,?,?,?,?,?)";
			$results = sqlsrv_query($this->dbacc, $sql, array($username, $password, $ip, $time, $admin, $success,$cookie_login), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		}
	}
	
	/*
	Shall we search the database for the string? This looks in both the account, the user and the guild tables, to make sure that we find what the user is looking for.
	*/
	
	function search_database($string)
	{
		global $lang;
		
		$return = $lang->search_database_yousearched_begin . "<span style=\"color: orange\">$string</span>" . $lang->search_database_yousearched_end . "<br /><br />" . $lang->search_database_yousearched_wefound . "<br />";
		$sql = "SELECT * FROM dbo.tUser WHERE sUserID LIKE ?";
		$results = sqlsrv_query($this->dbacc, $sql, array("%$string%"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		while ($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC))
		{
			$return .=  $lang->search_database_restuls_account . "<a href=\"?acc=$row[nUserNo]\">$row[sUserID]</a><br />";
			$i = 1;
		}
		$sql = "SELECT * FROM dbo.tCharacter WHERE sID LIKE ?";
		$results = sqlsrv_query($this->dbchar, $sql, array("%$string%"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		while ($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC))
		{
			$return .= $lang->search_database_results_character . "<a href=\"?acc=$row[nUserNo]\">$row[sID]</a><br />";
			$i = 1;
		}
		$sql = "SELECT * FROM dbo.tGuild WHERE sName LIKE ?";
		$results = sqlsrv_query($this->dbchar, $sql, array("%$string%"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		while ($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC))
		{
			$return .= $lang->search_database_results_guild . "<a href=\"?guild=$row[sName]\">$row[sName]</a><br />";
			$i = 1;
		}
		
		if (@$i != 1)
		{
			$return .= $lang->search_database_no_results;
		}
		
		return $return;
	}
	
	/*
	Reverses the gender
	*/
	function change_gender($user_id)
	{
		$sql = "SELECT * FROM dbo.tCharacterShape WHERE nCharNo = ?";
		$results = sqlsrv_query($this->dbchar, $sql, array("$user_id"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
		if ($row['nGender'] === 1)
		{
			$sql = "UPDATE dbo.tCharacterShape SET nGender = 0 WHERE nCharNo = ?";
			$results = sqlsrv_query($this->dbchar, $sql, array("$user_id"));
			return 1;
		}
		elseif ($row['nGender'] === 0)
		{
			$sql = "UPDATE dbo.tCharacterShape SET nGender = 1 WHERE nCharNo = ?";
			$results = sqlsrv_query($this->dbchar, $sql, array("$user_id"));
			return 1;
		}
		else
		{
			return 0; //char not found
		}
	}
	
	/*
	Adds a user account
	duplicates : if 0, every name must be unique.
	*/
	
	function make_game_acc($accountname, $password, $username, $email = "", $nAuthID = 1, $ip = "NULL", $duplicates = 0)
	{
		$sUserID = substr($accountname, 0, 30);
		$sUserPW = substr($password, 0, 20);
		$sUserName = substr($username, 0, 10);
		$sUserIP = substr($ip, 0, 15);
		
		//check if username exists, if requeires
		if ($duplicates == 0)
		{
			$sql = "SELECT * FROM Account.dbo.tUser WHERE sUserID = ?";
			$results = sqlsrv_query($this->dbacc, $sql, array("$sUserID"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			if (sqlsrv_num_rows($results) != 0)
			{
				return 2; //Name already used
			}
		}
		
		$sql = "INSERT INTO Account.dbo.tUser ([sUserID], [sUserPW], [sUserName], [nAuthID], [sUserIP]) VALUES (?, ?, ?, ?, ?)";
		$results = sqlsrv_query($this->dbacc, $sql, array("$sUserID", "$sUserPW", "$sUserName", "$nAuthID", "$sUserIP"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		
		if ($email != "")
		{
			$results1 = sqlsrv_query($this->dbacc, "SELECT TOP 1 * FROM Account.dbo.tUser WHERE sUserID = ? AND sUserPW = ? ORDER BY [nUserNo] desc", array("$sUserID", "$sUserPW"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			$row = sqlsrv_fetch_array($results1);
			sqlsrv_query($this->dbacc, "INSERT INTO dbo.tUserOption ([nUserNo], [sEmail]) VALUES (?, ?)", array($row['nUserNo'], $email), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		}
		
		return $this->check_query_success($results); // 1 = Account Created and is ready to be used in game; 0 = failed
	}
	
	/*
	Checks that the user belongs to a specific account - used to make sure that a user is editing only his own shit. Accepts only numerical values for both
	*/
	
	function char_belong_acc($char_id, $acc_id)
	{
		if (!is_numeric($char_id) || !is_numeric($acc_id))
		{
			return 0;
		}
		$sql = "SELECT * FROM dbo.tCharacter WHERE nCharNo = ?";
		$results = sqlsrv_query($this->dbchar, $sql, array($char_id), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		if (sqlsrv_num_rows($results) > 0)
		{
			$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
			if ($row['nUserNo'] == $acc_id)
			{
				return 1;
			}
		}
		return 0;
	}
	
	/*
	Turns the numerical array found in the database to a user-friendly name, such as is found in game (Master, Admin, Council, Guard, ect)
	
	If $guild_grade is larger than 6, returns the whole array
	*/
	
	function guildgrade_array($guild_grade)
	{
		$grades = array('0' => "Master", '1' => "Admin", '2'=> "Commander", '3'=> "Council", '4'=> "Guard", '6'=> "Member");
		
		if ($guild_grade < 7)
		{
			return $grades["$guild_grade"];
		}
		else
		{
			return $grades;
		}
	}
	
	/*
	Returns an array of the guild name, the grade in language, and the raw grade.
	[guild] = Guild name
	[grade] = Grade in langauge
	[raw_grade] = Grade in numerical form
	*/
	
	function get_guild_of_char($char_id)
	{
		$sql = "SELECT * FROM dbo.tGuildMember WHERE nCharNo = ?";
		$results = sqlsrv_query($this->dbchar, $sql, array($char_id), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
		
		if (sqlsrv_num_rows($results) == 0)
		{
			return false; //invalid ID, or char is not in guild
		}
		
		$return['grade'] = $this->guildgrade_array($row['nGrade']);
		$return['raw_grade'] = $row['nGrade'];
		
		$sql = "SELECT * FROM dbo.tGuild WHERE nNo = ?";
		$results = sqlsrv_query($this->dbchar, $sql, array($row['nNo']), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
		$return['guild'] = $row['sName'];
		
		return $return;
	}
	
	/*
	Moves the location of the character to the specified location.
	*/
	
	function char_change_location($char_id, $location, $xcoords, $ycoords)
	{
		$sql = "UPDATE dbo.tCharacter SET sLoginZone = ?, nLoginZoneX = ?, nLoginZoneY = ? WHERE nCharNo = ?";
		$results = sqlsrv_query($this->dbchar, $sql, array("$location", "$xcoords", "$ycoords", "$char_id"));
		return $this->check_query_result($results); //"Reset location success if 1";
	}
	
	/*
	Bans / unbans a character - the database is checked, and it's value reversed
	*/
	
	function ban_or_unban($acc)
	{
		$sql = "SELECT * FROM dbo.tUser WHERE nUserNo = ?";
		$results = sqlsrv_query($this->dbacc, $sql, array("$acc"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
		if ($row['bIsBlock'] === 1)
		{
			$sql = "UPDATE dbo.tUser SET bIsBlock = 0 WHERE nUserNo = ?";
			$results = sqlsrv_query($this->dbacc, $sql, array("$acc"));
			return 1;
		}
		elseif ($row['bIsBlock'] === 0)
		{
			$sql = "UPDATE dbo.tUser SET bIsBlock = 1 WHERE nUserNo = ?";
			$results = sqlsrv_query($this->dbacc, $sql, array("$acc"));
			return 1;
		}
		else
		{
			return 0; //char not found
		}
	}
	
	/*
	Changed a users password
	*/
	
	function edit_user_password($acc, $new_pass)
	{
		$sql = "UPDATE dbo.tUser SET sUserPW = ? WHERE nUserNo = ?";
		$results = sqlsrv_query($this->dbacc, $sql, array("$new_pass", "$acc"));
		
		return $this->check_query_success($results);
		
	}
	
	
	/*
	Turned a raw money value into a nice readable value.
	Change "images/Money_Jem" to the appropriate location.
	*/
	function money_to_readable($money)
	{
		if (!is_numeric($money))
		{
			return 0; //money ain't numerical
		}
			
		$mon = "";
		if (strlen($money) > 8) //we have gems
		{
			$length=strlen($money)-8;
			$mon .= substr($money, 0, $length) . "<img src=\"images/Money_Jem.png\" /> ";
		}
		if (strlen($money) > 6) //we have golds
		{
			if (strlen($money) <= 8)
			{
				$length = strlen($money) - 6;
			}
			else
			{
				$length = 2;
			}
			$mon .= substr($money, -8, $length) . "<img src=\"images/Money_Gold.png\" /> ";
		}
		if (strlen($money) > 3)
		{
			if (strlen($money) < 6)
			{
				$length = strlen($money) - 3;
			}
			else
			{
				$length = 3;
			}
			$mon .= substr($money, -6, $length) . "<img src=\"images/Money_Silver.png\" /> ";
		}
		$mon .= substr($money, -3, 3) . "<img src=\"images/Money_Copper.png\" /> ";
		
		return $mon;
	}
	
	
	/*
	Changes the character's name.
	*/
	function edit_char_name($old_char_id, $new_char_name)
	{
		$sql = "UPDATE dbo.tCharacter SET sID = ? WHERE nCharNo = ?";
		$results = sqlsrv_query($this->dbacc, $sql, array("$new_char_name", "$old_char_id"));
		return $this->check_query_success($results);
	}
	
	/*
	Changes a character or account id with name (or vice versa). Has both auto checker, and a manual switch, in case there are errors, or the function needs to be used in a specific way.
	
	$type = Are we dealing with accounts or characters?
		ACCOUNT : $type = 0
		CHARACTERS : $type = 1
		
	$value = What are we swapping? if you give string when method is 0, it will automatically swap to method 1.
	
	$method = How are we swapping it?
		0 = ID (The given data is and ID, and we want a string)
		1 = STRING (The given data is a name (char or add) and we want an ID)
	
	*/
	function id_name_switch($type, $value, $method)
	{
		global $lang;
		
		if ($type == 0) //CONVERTING ACCOUNT
		{
			$sql = "SELECT * FROM Account.dbo.tUser WHERE ";
			if ($method == 0 and is_numeric($value))
			{
				$sql .= "nUserNo";
			}
			else
			{
				$sql .= "sUserID";
			}
			$sql .= " = ?";
			
			$results = sqlsrv_query($this->dbacc, $sql, array("$value"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
			
			if (sqlsrv_num_rows($results) == 0)
			{
				return $lang->no_results;
			}
			elseif ($method == 0 and is_numeric($value))
			{
				return $row['sUserID'];
			}
			else
			{
				return $row['nUserNo'];
			}
		}
		else //CONVERTING CHARACTER DATA
		{
			$sql = "SELECT * FROM dbo.tCharacter WHERE ";
			if ($method == 0 and is_numeric($value))
			{
				$sql .= "nCharNo";
			}
			else
			{
				$sql .= "sID";
			}
			$sql .= " = ?";
			
			$results = sqlsrv_query($this->dbchar, $sql, array("$value"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			$row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC);
			
			if (sqlsrv_num_rows($results) == 0)
			{
				return $lang->no_results;
			}
			elseif ($method == 0 and is_numeric($value))
			{
				return $row['sID'];
			}
			else
			{
				return $row['nCharNo'];
			}
		}
	}
	
	/*
	Take money or fame away from a specific character. $money and $fame are the values that need to be taken away. Returns '0' if char doesn't exist, or if you would be taking away too much.
	*/
	function money_fame_away($char_id, $money = 0, $fame = 0)
	{
		$results = sqlsrv_query($this->dbchar, "SELECT * FROM dbo.tCharacter WHERE nCharNo = ?", array("$char_id"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		if (sqlsrv_num_rows($results) > 0)
		{
			//char exists
			$row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC);
			
			//New fame:
			if ($fame != 0)
			{
				if (($row['nFame'] >= $fame) && is_numeric($fame) && ($fame > 0))
				{
					$row['nFame'] = ($row['nFame'] - $fame);
				}
				else
				{
					return 0;
				}
			}
			
			//New money:
			if ($money != 0)
			{
				if (($row['nMoney'] >= $money) && is_numeric($money) && ($money > 0))
				{
					$row['nMoney'] = ($row['nMoney'] - $money);
				}
				else
				{
					return 0;
				}
			}
			
			
			$results = sqlsrv_query($this->dbacc, "UPDATE dbo.tCharacter SET nFame = ?, nMoney = ? WHERE nCharNo = ?", array($row['nFame'], $row['nMoney'], $char_id));
			return $this->check_query_success( $results );
		}
		return 0;
	}
	
	/*
		Outputs the current gender of the characted -
		$char_info is ID WHEN $what=0
					is NAME when $what=1
					
		RETURN:
		0 = female
		1 = male
		2 = fail
	*/
	function char_gender($char_info, $what=0)
	{
		if ($what == 1)
		{
			$results = sqlsrv_query($this->dbchar, "SELECT * FROM dbo.tCharacter WHERE sID = ?", array($char_info), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			if (sqlsrv_num_rows($results) == 0)
			{
				return 2;
			}
			$row = sqlsrv_fetch_array($results);
			$char_info = $row['nCharNo'];
		}
		
		$results = sqlsrv_query($this->dbchar, "SELECT * FROM dbo.tCharacterShape WHERE nCharNo = ?", array($char_info), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		if (sqlsrv_num_rows($results) == 0)
		{
			return 2;
		}
		$row = sqlsrv_fetch_array($results);
		return $row['nGender'];
	}
	
	/*
	Add log to the database.
	*/
	function usercp_log($type, $value_1,  $value_2='',  $value_3='',  $user_name='',  $ip='')
	{
		global $settings;
		if ($settings->log_usercp != 1)
		{
			return 0;
		}
		
		if ($user_name == '')
		{
			$user_name = $_SESSION['fieme_uname'];
		}
		
		if ($ip == '')
		{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
		$time = time();
		
		$results = sqlsrv_query($this->dbacc, "INSERT INTO [dbo].[fUserCPLog] ([type],[ip],[user_name],[time],[value_1],[value_2],[value_3])
												VALUES(?,?,?,?,?,?,?)", array($type, $ip, $user_name, $time, $value_1, $value_2, $value_3));
		
		return $this->check_query_success( $results );
	}
	
	/*
	Add a CS item to an account. Use? Dunno, but who cares :).
	
	NOT USEABLE
	
	function give_cs_item($acc, $item)
	{
		//read instructions at the top to make sure that you can run this!
		
		$currenttime = date("Y-m-d H:i:s:000");
		$sql = "INSERT INTO Account.dbo.tChargeItem VALUES (?, ?, ?, '1', '$currenttime', '0', '$currenttime');";
		$results = sqlsrv_query($this->dbacc, $sql, array("$acc", $this->usable_order, "$item"), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		return $this->check_query_success( $results );
	}*/
}