<?php

/**

 * Login system written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)

 * Last Updated: August 17, 2004

 */

include("constants.php");

include_once("mailer.php");



      

class MySQLDB

{

   var $connection;         //The MySQL database connection

   var $num_active_users;   //Number of active users viewing site

   var $num_active_guests;  //Number of active guests viewing site

   var $num_members;        //Number of signed-up users

   /* Note: call getNumMembers() to access $num_members! */



   /* Class constructor */

   function MySQLDB(){

      /* Make connection to database */

      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());

      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());

      

  /**

       * Only query database to find out number of members

       * when getNumMembers() is called for the first time,

       * until then, default value set.

       */

      $this->num_members = -1;

      

      /* Calculate number of users at site */

      $this->calcNumActiveUsers();

      

      /* Calculate number of guests at site */

      $this->calcNumActiveGuests();

   }

/*

   function get_config($qval)

   {

	$q = "SELECT config_value FROM general_config WHERE config_name = '".$qval."'";

	$result = mysql_query($q, $this->connection);



	if(!$result || (mysql_numrows($result) < 1))

	{

		return false;

	}



	$dbarray = mysql_fetch_array($result);

	return $dbarray['config_value'];

   }



   function modify_config($qval,$new_val)

   {

	$q = "UPDATE general_config SET config_value = '".$new_val."' WHERE config_name = '".$qval."'";

	$result = mysql_query($q, $this->connection);

   }

*/

   function query_url($url)

   {

	$timeout = 2;



	if(QUERY_METHOD == 0)

	{

		$old = @ini_set('default_socket_timeout', $timeout);

		$file = @fopen($url, 'r');

		@ini_set('default_socket_timeout', $old);

		@stream_set_timeout($file, $timeout);

		@stream_set_blocking($file, 0);

	}

	else if(QUERY_METHOD == 1)

	{

		$curl = curl_init();

		curl_setopt ($curl, CURLOPT_URL, $url);

		curl_setopt ($curl, CURLOPT_TIMEOUT, $timeout);

		curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

		$html = curl_exec ($curl);

		curl_close ($curl);

	}

   }

   

   function getUserDBID($user)

   {

	$q = "SELECT id FROM users WHERE username = '$user'";

	$result = mysql_query($q, $this->connection);

	if(!$result || (mysql_numrows($result) < 1)){

		return 1; //Indicates username failure

	}



	$dbarray = mysql_fetch_array($result);

	return $dbarray['id'];

   }



   /**

    * confirmUserPass - Checks whether or not the given

    * username is in the database, if so it checks if the

    * given password is the same password in the database

    * for that user. If the user doesn't exist or if the

    * passwords don't match up, it returns an error code

    * (1 or 2). On success it returns 0.

    */

   function confirmUserPass($username, $password){

      /* Add slashes if necessary (for query) */

	  $username = mysql_real_escape_string($username);

	  

      /* Verify that user is in database */

      $q = "SELECT password FROM users WHERE username = '$username'";

      $result = mysql_query($q, $this->connection);

      if(!$result || (mysql_numrows($result) < 1)){

         return 1; //Indicates username failure

      }



      /* Retrieve password from result, strip slashes */

      $dbarray = mysql_fetch_array($result);

      //$dbarray['password'] = stripslashes($dbarray['password']);

      //$password = stripslashes($password);



      /* Validate that password is correct */

      if($password == $dbarray['password']){

         return 0; //Success! Username and password confirmed

      }

      else{

         return 2; //Indicates password failure

      }

   }

   

   /**

    * confirmUserID - Checks whether or not the given

    * username is in the database, if so it checks if the

    * given userid is the same userid in the database

    * for that user. If the user doesn't exist or if the

    * userids don't match up, it returns an error code

    * (1 or 2). On success it returns 0.

    */

   function confirmUserID($username, $userid){

      /* Add slashes if necessary (for query) */

	  $username = mysql_real_escape_string(trim($username));

	  

      /* Verify that user is in database */

      $q = "SELECT userid FROM users WHERE username = '$username'";

      $result = mysql_query($q, $this->connection);

      if(!$result || (mysql_numrows($result) < 1)){

         return 1; //Indicates username failure

      }



      /* Retrieve userid from result, strip slashes */

      $dbarray = mysql_fetch_array($result);

      //$dbarray['userid'] = stripslashes($dbarray['userid']);

      //$userid = stripslashes($userid);



      /* Validate that userid is correct */

      if($userid == $dbarray['userid']){

         return 0; //Success! Username and userid confirmed

      }

      else{

         return 2; //Indicates userid invalid

      }

   }

   

   /**

    * usernameTaken - Returns true if the username has

    * been taken by another user, false otherwise.

    */

   function usernameTaken($username){

	  $username = mysql_real_escape_string(trim($username));

	  

      $q = "SELECT username FROM users WHERE username = '$username'";

      $result = mysql_query($q, $this->connection);

      return (mysql_numrows($result) > 0);

   }

   

   function getNameFromEmail($email){

	  $email = mysql_real_escape_string(trim($email));

	  

      $q = "SELECT username FROM users WHERE email = '$email'";

      $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);



	    return $dbarray['username'];

	  }

   }

   

   /**

    * emailTaken - Returns true if the e-mail has

    * been taken by another user, false otherwise.

    */

   function emailTaken($email){

	  $email = mysql_real_escape_string(trim($email));

	  

      $q = "SELECT email FROM users WHERE email = '$email'";

      $result = mysql_query($q, $this->connection);

      return (mysql_numrows($result) > 0);

   }



   /**

    * addNewUser - Inserts the given (username, password, email)

    * info into the database. Appropriate user level is set.

    * Returns true on success, false otherwise.

    */

   function addNewUser($username, $password, $email, $secretq, $answerq){

      $time = time();

	  

      $q = "SELECT count(*) FROM users WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      if($query_data[0] > 0)

	  {

		$ulevel = 1;

	  }

	  else

	  {

		$ulevel = 3;

	  }



      $q = "INSERT INTO users (username,password,userid,userlevel,email,timestamp,regtimestamp,secretq,answerq,autoaccept_buddies,emailabout_buddies) VALUES ('$username', '$password', '0', $ulevel, '$email', $time, $time, '$secretq', '$answerq', 1, 1)";

      return mysql_query($q, $this->connection);

   }

   

   /**

    * updateUserField - Updates a field, specified by the field

    * parameter, in the user's row of the database.

    */

   function updateUserField($username, $field, $value){

      $q = "UPDATE users SET ".$field." = '$value' WHERE username = '$username'";

      return mysql_query($q, $this->connection);

   }

   

   function updateUserFieldByID($id, $field, $value){

      $q = "UPDATE users SET ".$field." = '$value' WHERE id = '$id'";

      return mysql_query($q, $this->connection);

   }

   

   /**

    * getUserInfo - Returns the result array from a mysql

    * query asking for all information stored regarding

    * the given username. If query fails, NULL is returned.

    */

   function getUserInfo($username){

      $q = "SELECT * FROM users WHERE username = '$username'";

      $result = mysql_query($q, $this->connection);

      /* Error occurred, return given name by default */

      if(!$result || (mysql_numrows($result) < 1)){

         return NULL;

      }

      /* Return result array */

      $dbarray = mysql_fetch_array($result);

      return $dbarray;

   }

   

   function getUserInfoByID($id){

      $q = "SELECT * FROM users WHERE id = '$id'";

      $result = mysql_query($q, $this->connection);

      /* Error occurred, return given name by default */

      if(!$result || (mysql_numrows($result) < 1)){

         return NULL;

      }

      /* Return result array */

      $dbarray = mysql_fetch_array($result);

      return $dbarray;

   }

   

   /**

    * getNumMembers - Returns the number of signed-up users

    * of the website. The first

    * time the function is called on page load, the database

    * is queried, on subsequent calls, the stored result

    * is returned. This is to improve efficiency, effectively

    * not querying the database when no call is made.

    */

   function getNumMembers(){

      if($this->num_members < 0){

         $q = "SELECT * FROM users";

         $result = mysql_query($q, $this->connection);

         $this->num_members = mysql_numrows($result);

      }

      return $this->num_members;

   }

   

   /**

    * calcNumActiveUsers - Finds out how many active users

    * are viewing site and sets class variable accordingly.

    */

   function calcNumActiveUsers(){

      /* Calculate number of users at site */

      $q = "SELECT * FROM active_users";

      $result = mysql_query($q, $this->connection);

      $this->num_active_users = mysql_numrows($result);

   }

   

   /**

    * calcNumActiveGuests - Finds out how many active guests

    * are viewing site and sets class variable accordingly.

    */

   function calcNumActiveGuests(){

      /* Calculate number of guests at site */

      $q = "SELECT * FROM active_guests";

      $result = mysql_query($q, $this->connection);

      $this->num_active_guests = mysql_numrows($result);

   }

   

   /**

    * addActiveUser - Updates username's last active timestamp

    * in the database, and also adds him to the table of

    * active users, or updates timestamp if already there.

    */

   function addActiveUser($username, $time){

      $q = "UPDATE users SET timestamp = '$time' WHERE username = '$username'";

      mysql_query($q, $this->connection);

      



      $q = "REPLACE INTO active_users VALUES ('$username', '$time')";

      mysql_query($q, $this->connection);

      $this->calcNumActiveUsers();

   }

   

   /* addActiveGuest - Adds guest to active guests table */

   function addActiveGuest($ip, $time){



      $q = "REPLACE INTO active_guests VALUES ('$ip', '$time')";

      mysql_query($q, $this->connection);

      $this->calcNumActiveGuests();

   }

   

   /* These functions are self explanatory, no need for comments */

   

   /* removeActiveUser */

   function removeActiveUser($username){



      $q = "DELETE FROM active_users WHERE username = '$username'";

      mysql_query($q, $this->connection);

      $this->calcNumActiveUsers();

   }

   

   /* removeActiveGuest */

   function removeActiveGuest($ip){



      $q = "DELETE FROM active_guests WHERE ip = '$ip'";

      mysql_query($q, $this->connection);

      $this->calcNumActiveGuests();

   }

   

   /* removeInactiveUsers */

   function removeInactiveUsers(){



      $timeout = time()-USER_TIMEOUT*60;

      $q = "DELETE FROM active_users WHERE timestamp < $timeout";

      mysql_query($q, $this->connection);

      $this->calcNumActiveUsers();

   }



   /* removeInactiveGuests */

   function removeInactiveGuests(){



      $timeout = time()-GUEST_TIMEOUT*60;

      $q = "DELETE FROM active_guests WHERE timestamp < $timeout";

      mysql_query($q, $this->connection);

      $this->calcNumActiveGuests();

   }



   /* printActiveBuddies */

   function printActiveBuddies($playerid)

   {

    $buddiesOnline = false;

	

	$q = "SELECT buddy1_id, buddy2_id FROM buddy_list WHERE buddy1_id = ".$playerid." OR buddy2_id = ".$playerid;

	$result = mysql_query($q, $this->connection);

	if(mysql_numrows($result) > 0)

	{

	  while($row = mysql_fetch_array( $result ))

	  {

		  list($buddy1_id, $buddy2_id) = $row;



		  if($buddy1_id == $playerid)

		  {

			$buddyID = $buddy2_id;

		  }

		  else

		  {

			$buddyID = $buddy1_id;

		  }



		  // search for all buddies that are active. get some info about where they were last seen

		  $q_lastserver = "SELECT username,lastserver_id,lastserver_playername FROM users WHERE id = ".$buddyID." AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800);

		  $result_lastserver = mysql_query($q_lastserver, $this->connection);



		  if($result_lastserver && (mysql_numrows($result_lastserver) > 0))

		  {

			$dbarray = mysql_fetch_array($result_lastserver);

			$lastserver_id = $dbarray['lastserver_id'];

			$sendtouser = $dbarray['username'];

			$lastserver_playername = $dbarray['lastserver_playername'];



			// match that server id to a server list entry

			$q_lastservername = "SELECT server_name,server_url FROM server_list WHERE id = ".$lastserver_id;

			$result_lastservername = mysql_query($q_lastservername, $this->connection);

			if($result_lastservername && (mysql_numrows($result_lastservername) > 0))

			{

			  $dbarray = mysql_fetch_array($result_lastservername);

			  $connectto = $dbarray['server_url'];

			  

			  echo $sendtouser . " @ <a href=\"unreal://". $dbarray['server_url'] . "\">" . $dbarray['server_name'] ."</a><br>\n( as " . htmlspecialchars($this->urlSafeDecode($lastserver_playername)) . " )<br><br>\n";

			  

			  if(!$buddiesOnline)

				$buddiesOnline = true;

			}

		  }

		}

	}

	if(!$buddiesOnline)

		echo "No buddies online";

   }

   

   function checkForUpdateStatus()

   {

	  $q = "SELECT config_value FROM configuration WHERE config_name = 'newest_version'";

	  $result = mysql_query($q, $this->connection);

	  $dbarray = mysql_fetch_array($result);

	  $newest_version = $dbarray['config_value'];

	  

	  if(BUILD < $newest_version)

	  {

		return true;

	  }

	  return false;

   }

   

   function getUpdateLocation()

   {

	  $q = "SELECT config_value FROM configuration WHERE config_name = 'information_url'";

	  $result = mysql_query($q, $this->connection);

	  $dbarray = mysql_fetch_array($result);

	  return $dbarray['config_value'];

   }

   

   /* printActiveBuddies */

   function printActiveBuddiesPMList($playerid,$lastBuddyPMed)

   {

    $buddiesOnline = false;

	$i = 0;

	

	$q = "SELECT buddy1_id, buddy2_id FROM buddy_list WHERE buddy1_id = ".$playerid." OR buddy2_id = ".$playerid;

	$result = mysql_query($q, $this->connection);

	if(mysql_numrows($result) > 0)

	{

	  while($row = mysql_fetch_array( $result ))

	  {

		  list($buddy1_id, $buddy2_id) = $row;



		  if($buddy1_id == $playerid)

		  {

			$buddyID = $buddy2_id;

		  }

		  else

		  {

			$buddyID = $buddy1_id;

		  }



		  // search for all buddies that are active. get some info about where they were last seen

		  $q_lastserver = "SELECT username,lastserver_id,lastserver_playername FROM users WHERE id = ".$buddyID." AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800);

		  $result_lastserver = mysql_query($q_lastserver, $this->connection);



		  if($result_lastserver && (mysql_numrows($result_lastserver) > 0))

		  {

			$dbarray = mysql_fetch_array($result_lastserver);

			$lastserver_id = $dbarray['lastserver_id'];

			$sendtouser = $dbarray['username'];

			$lastserver_playername = $dbarray['lastserver_playername'];

			

			// match that server id to a server list entry

			$q_lastservername = "SELECT server_name FROM server_list WHERE id = ".$lastserver_id;

			$result_lastservername = mysql_query($q_lastservername, $this->connection);

			if($result_lastservername && (mysql_numrows($result_lastservername) > 0))

			{

			  $dbarray = mysql_fetch_array($result_lastservername);

			  

			  echo "<option value=\"".$buddyID."\"";

			  if(isset($lastBuddyPMed) && $lastBuddyPMed == $buddyID)

				echo " selected";

			  echo ">".$sendtouser." @ ".$dbarray['server_name']." ( as " . htmlspecialchars($this->urlSafeDecode($lastserver_playername)) . " )</option>\n";

			  

			  if(!$buddiesOnline)

				$buddiesOnline = true;

			}

		  }

		}

	}

	if(!$buddiesOnline)

		echo "<option value=\"\">No buddies online</option>";

   }

   

   /* printBuddyListCount */

   function printBuddyListCount($dbID){

      /* Calculate number of guests at site */

      $q = "SELECT id FROM buddy_list WHERE buddy1_id = ".$dbID." OR buddy2_id = ".$dbID;

      $result = mysql_query($q, $this->connection);

      echo mysql_numrows($result);

   }

   

   /* printBuddyListCount */

   function removeFromBuddyList($dbID,$buddyID){

      /* Remove buddy who's ID = $buddyID from $dbID's list */

      $q = "DELETE FROM buddy_list WHERE buddy1_id = ".$dbID." AND buddy2_id = ".$buddyID." OR buddy1_id = ".$buddyID." AND buddy2_id = ".$dbID;

      $result = mysql_query($q, $this->connection);

   }

   

   /* AddToBuddyList */

   function AddToBuddyList($dbID,$buddyID){

      /* adds $buddyID as requester and $dbID as recipient to buddY_requests table */



	  // check and see if they are already buddies

	  if($this->getUserAlreadyIsBuddy($dbID,$buddyID))

	  {

		return "You are already buddies with that player!";

	  }

	  if($this->getUserAlreadyHasBuddyRequest($dbID,$buddyID))

	  {

		return "You already have an outstanding buddy request with that player!";

	  }



	  $q = "SELECT autoaccept_buddies,username FROM users WHERE id = ".$buddyID;

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

		 $dbarray = mysql_fetch_array($result);

		 $autoaccept = $dbarray['autoaccept_buddies'];

		 $username = $dbarray['username'];

	  }

	  // if buddy automatically accepts requests

	  if($autoaccept == 1)

	  {

	      $q = "INSERT INTO buddy_list (buddy1_id, buddy2_id) VALUES ($dbID,$buddyID)";

	      $result = mysql_query($q, $this->connection);

		  return "Buddy has been added!";

	  }

	  else

	  {

	      $q = "INSERT INTO buddy_requests (requester_id, receiver_id) VALUES ($dbID,$buddyID)";

	      $result = mysql_query($q, $this->connection);

		  

		  $mailer = new Mailer();

		  $mailer->sendBuddyRequest($this->getNameFromID($buddyID),$this->getEmailFromID($buddyID),$this->getNameFromID($dbID));

		  return "Buddy request has been sent successfully! ".$username." has been notified and must accept or deny your request.";

	  }

   }

   

   function printAdminServerList()

   {

	  $q = "SELECT id,server_name,server_url,server_tcpport,allow_local_lookup,allow_universal_lookup,briefinfo_cachetime FROM server_list WHERE 1 ORDER BY id ASC";

	  $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

		echo "<h1>Existing Server Enteries</h1><hr><br>";

	    while($row = mysql_fetch_array( $result ))

	    {

		  list($id,$server_name,$server_url,$server_tcpport,$allow_local_lookup,$allow_universal_lookup,$briefinfo_cachetime) = $row;

?>

		  <form name="editServerForm-<?php echo $id; ?>" action="process.php" method="POST">

		  Server Name: <input type="text" name="server_name" size="20" value="<?php echo $server_name; ?>">&nbsp;&nbsp;Server URL: <input type="text" name="server_url" size="22" value="<?php echo $server_url; ?>"><br>

		  Server TCP Port: <input type="text" name="server_tcpport" size="4" value="<?php echo $server_tcpport; ?>">&nbsp;&nbsp;Cache Time (seconds): <input type="text" name="briefinfo_cachetime" size="3" value="<?php echo $briefinfo_cachetime; ?>"><br>

		  <input type="checkbox" name="allow_local_lookup" value="1"<?php if($allow_local_lookup == 1) echo " checked"; ?>>Allow Local Player Information Lookups<br>

		  <input type="checkbox" name="allow_universal_lookup" value="1"<?php if($allow_universal_lookup == 1) echo " checked"; ?>>Allow Universal Player Information Lookups<br>

		  <p align="right"><input type="submit" value="Update Entry">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="Delete Entry" onclick="deleteserversubmit.value='true';if(confirmSubmit('Are you sure you want to remove this server entry?')) submit();">&nbsp;&nbsp;&nbsp;&nbsp;</p>

		  <input type="hidden" name="editserversubmit" value="true">

		  <input type="hidden" name="deleteserversubmit" id="deleteserversubmit" value="">

		  <input type="hidden" name="servernum" value="<?php echo $id; ?>"></form><br><hr><br>

<?php

	    }

	  }

   }

   

   function addServer($server_name,$server_url,$server_tcpport,$briefinfo_cachetime,$allow_local_lookup,$allow_universal_lookup)

   {

      $q = "INSERT INTO server_list (server_name,server_url,server_tcpport,briefinfo_cachetime,allow_local_lookup,allow_universal_lookup) VALUES ('$server_name','$server_url',$server_tcpport,$briefinfo_cachetime,$allow_local_lookup,$allow_universal_lookup)";

      return mysql_query($q, $this->connection);

   }

   

   function editServer($id,$server_name,$server_url,$server_tcpport,$briefinfo_cachetime,$allow_local_lookup,$allow_universal_lookup,$bDelete)

   {

      if($bDelete)

	  {

	    $q = "DELETE FROM server_list WHERE id = $id";

	  }

	  else

	  {

	    $q = "UPDATE server_list SET server_name = '$server_name', server_url = '$server_url', server_tcpport = $server_tcpport, briefinfo_cachetime = $briefinfo_cachetime, allow_local_lookup = $allow_local_lookup, allow_universal_lookup = $allow_universal_lookup WHERE id = $id";

	  }

      return mysql_query($q, $this->connection);

   }

   

   function removeAccount($playerid)

   {

	  $q = "DELETE FROM buddy_list WHERE buddy1_id = ".$playerid." OR buddy2_id = ".$playerid;

	  $result = mysql_query($q, $this->connection);

	  

	  $q = "DELETE FROM buddy_requests WHERE requester_id = ".$playerid." OR receiver_id = ".$playerid;

	  $result = mysql_query($q, $this->connection);

	  

	  $q = "DELETE FROM users WHERE id = ".$playerid;

	  $result = mysql_query($q, $this->connection);

   }

   

   function getNameFromID($id)

   {

	  $q = "SELECT username FROM users WHERE id = ".$id;

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

	    return $dbarray['username'];

	  }

   }

   

   function getIDFromName($name)

   {

	  $q = "SELECT id FROM users WHERE username = '".$name."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

	    return $dbarray['id'];

	  }

   }

   

   function getEmailFromID($id)

   {

	  $q = "SELECT email FROM users WHERE id = ".$id;

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

	    return $dbarray['email'];

	  }

   }

   

   /* doBuddyAcceptDeny */

   function doBuddyAcceptDeny($dbID,$buddyID,$value){

      /* adds $buddyID as requester and $dbID as recipient to buddY_requests table */



	  $q = "DELETE FROM buddy_requests WHERE requester_id = ".$buddyID." AND receiver_id = ".$dbID;

	  $result = mysql_query($q, $this->connection);



	  if($value == "accept")

	  {

		$q = "INSERT INTO buddy_list (buddy1_id, buddy2_id) VALUES ($dbID,$buddyID)";

		$result = mysql_query($q, $this->connection);

	  }

   }

   

   /* RemoveFromBuddyRequestList*/

   function RemoveFromBuddyRequestList($dbID,$buddyID){



	  if($this->getUserAlreadyHasBuddyRequest($dbID,$buddyID))

	  {

	    $q = "DELETE FROM buddy_requests WHERE requester_id = ".$dbID." AND receiver_id = ".$buddyID." OR requester_id = ".$buddyID." AND receiver_id = ".$dbID;

	    $result = mysql_query($q, $this->connection);

	  }

   }

   

   function SendPM($toID, $fromID, $msg)

   {

		$q = "SELECT lastserver_id,username FROM users WHERE id = ".$toID." AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800) ." LIMIT 1";

		$result = mysql_query($q, $this->connection);

		if($result && mysql_numrows($result) > 0)

		{

	  	  $dbarray = mysql_fetch_array($result);

		  $lastserver_id = $dbarray['lastserver_id'];

		  $to = $dbarray['username'];



		  $q = "SELECT server_name,server_url,server_tcpport FROM server_list WHERE id = $lastserver_id";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

			$dbarray = mysql_fetch_array($result);

		    $connectto = substr($dbarray['server_url'], 0, strpos($dbarray['server_url'],":") + 1) . $dbarray['server_tcpport'];

	

		    $this->query_url("http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::receivepm:::".$this->getNameFromID($toID).":::Website:::".$this->getNameFromID($fromID).":::$msg&");

			

			// log the message

			$this->savePMHistory($fromID,$toID,mysql_real_escape_string($this->getNameFromID($fromID)." (at Website) to ".$this->getNameFromID($toID). " (at ".$dbarray['server_name'].")"),mysql_real_escape_string(trim($msg)));

		  }

		}

		else

		{

		  // not online

		  return false;

		}

		return true;

   }

   

   /* printBuddyListNotResponded */

   function printBuddyListNotResponded($dbID){



      $q = "SELECT receiver_id FROM buddy_requests WHERE requester_id = ".$dbID;

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$outputArray = array();

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($receiver_id) = $row;



			$q_name = "SELECT username FROM users WHERE id = ".$receiver_id;

			$result_name = mysql_query($q_name, $this->connection);

			if($result_name && (mysql_numrows($result_name) > 0))

			{

				$dbarray = mysql_fetch_array($result_name);

				$outputArray[$i] = $dbarray['username'].";".$receiver_id;

				$i++;

			}

		}

		natcasesort($outputArray);

		foreach($outputArray as $entry)

		{

			$entry = explode(";",$entry);

			echo '<option value="'.$entry[1].'">'.$entry[0].'</option>';

		}

	  }

   }

   

   /* printCurrentBuddyNotifications */

   function printCurrentBuddyNotifications($dbID){



      $q = "SELECT requester_id FROM buddy_requests WHERE receiver_id = ".$dbID;

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$outputArray = array();

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($requester_id) = $row;



			$q_name = "SELECT username FROM users WHERE id = ".$requester_id;

			$result_name = mysql_query($q_name, $this->connection);

			if($result_name && (mysql_numrows($result_name) > 0))

			{

				$dbarray = mysql_fetch_array($result_name);

				$outputArray[$i] = $dbarray['username'].";".$requester_id;

				$i++;

			}

		}

		natcasesort($outputArray);

		foreach($outputArray as $entry)

		{

			$entry = explode(";",$entry);

			echo '<option value="'.$entry[1].'">'.$entry[0].'</option>';

		}

	  }

   }

   

   /* printServerData */

   function printServerData(){

      /* Calculate number of servers at site */

      $q = "SELECT id,server_name,server_url,briefinfo_numplayers,briefinfo_maxplayers,briefinfo_map,briefinfo_timestamp,briefinfo_cachetime FROM server_list WHERE 1 ORDER BY briefinfo_timestamp <= (".time()." - (2 * briefinfo_cachetime)) ASC, briefinfo_numplayers DESC LIMIT 20";

      $result = mysql_query($q, $this->connection);



	  if(mysql_numrows($result) > 0)

	  {

		echo "<br><br>\n";

		while($row = mysql_fetch_array( $result ))

		{

			list($id, $server_name, $server_url, $briefinfo_numplayers,$briefinfo_maxplayers,$briefinfo_map,$briefinfo_timestamp,$briefinfo_cachetime) = $row;

			echo "<b>$server_name</b> (<a href=\"unreal://$server_url\">$server_url</a>)<br>";

			

		    if(strlen($briefinfo_map) >= 20)

		    {

			  $briefinfo_map = substr($briefinfo_map, 0, 20) . "...";

		    }

			

		    // if the data is older than (2 * cachetime), consider it unreliable (server down, whatever...)

		    if($briefinfo_timestamp <= (time() - (2 * $briefinfo_cachetime)))

		    {

			  echo "No Data (Down?)";

		    }

		    else

		    {

			  echo $this->urlSafeDecode($briefinfo_map) . " (<a href=\"index.php?p=players&id=".$id."\">" . $briefinfo_numplayers . "/" . $briefinfo_maxplayers . "</a>)";

		    }



			echo "<br><br>";

		}

	  }

   }

   

   function printDBSize()

   {

      $q = "SHOW TABLE STATUS";

	  $result = mysql_query($q, $this->connection);

      $dbsize = 0;

	

      while( $row = mysql_fetch_array( $result ) )

	  {  

          $dbsize += $row[ "Data_length" ] + $row[ "Index_length" ];

      }

      echo $this->file_size_info($dbsize);

   }

   

   function file_size_info($filesize)

   { 

      $bytes = array('KB', 'KB', 'MB', 'GB', 'TB');

      if ($filesize < 1024) $filesize = 1;

      for ($i = 0; $filesize > 1024; $i++) $filesize /= 1024; 

      $file_size_info = ceil($filesize); 

      $file_size_info = $file_size_info . " " . $bytes[$i]; 

      return $file_size_info;

	}

   

   /* printUserCount */

   function printUserCount()

   {

      /* Calculate number of users at site */

      $q = "SELECT count(*) FROM users WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo $query_data[0];

   }

   

   /* printPMCount */

   function printPMCount()

   {

      /* Calculate number of users at site */

      $q = "SELECT count(*) FROM private_msg WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo $query_data[0];

   }

   

   /* printBuddyRequestsCount */

   function printBuddyRequestCount()

   {

      /* Calculate number of users at site */

      $q = "SELECT count(*) FROM buddy_requests WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo $query_data[0];

   }

   

   /* printPlayerAccessCount */

   function printPlayerAccessCount()

   {

      /* Calculate number of users at site */

      $q = "SELECT count(*) FROM access_log WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo $query_data[0];

   }

   

   /* printServerCount */

   function printServerCount()

   {

      /* Calculate number of servers */

      $q = "SELECT count(*) FROM server_list WHERE 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo $query_data[0];

   }

   

   /* printActiveUsers */

   function printActiveUsers()

   {

      /* print active usernames */

      $q = "SELECT username FROM active_users WHERE 1 ORDER BY username ASC";

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

		echo "<br><br>\n";

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($username) = $row;

			echo $username;

			$i++;

			if(mysql_numrows($result) != $i)

			{

				echo ", ";

			}

		}

	  }

   }

   

   function printDateFirstAccessEntry()

   {

      /* Calculate number of users at site */

      $q = "SELECT timestamp FROM access_log WHERE 1 ORDER BY timestamp ASC LIMIT 1";

      $result = mysql_query($q, $this->connection);

      $query_data = mysql_fetch_row($result);

      echo date("F j Y, g:ia",$query_data[0]);

   }

   

   function isOnlineWebUser($username)

   {

      /* print active usernames */

      $q = "SELECT * FROM active_users WHERE username = '$username'";

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

			return true;

	  }

	  return false;

   }



   /* printPlayerList */

   function printPlayerList($id){

      /* output a players list */



      $q = "SELECT briefinfo_players,briefinfo_timestamp,briefinfo_cachetime FROM server_list WHERE id = ".mysql_real_escape_string($id);  

      $result = mysql_query($q, $this->connection);

      $dbarray = mysql_fetch_array($result);



// reload the page once in a while	  

echo "<script type=\"text/JavaScript\">setTimeout(\"location.reload(true);\",15000);</script>";

echo "<p align=\"center\"><b>This Page Automatically Reloads Every 15 Seconds</b><br><hr></p><br>";



	  // if the data is older than (2 * cachetime), consider it unreliable (server down, whatever...)

	  if($dbarray['briefinfo_timestamp'] <= (time() - (2 * $dbarray['briefinfo_cachetime'])))

	  {

			echo "<p align=\"center\"><b>No Server Data, Server May Be Down</b></p>";

	  }

	  else if(strlen($dbarray['briefinfo_players']) > 0)

	  {

			$rowStr = ""; $i = 0;

echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\">\n";

			$players = explode(",",$this->urlSafeDecode($dbarray['briefinfo_players']));

			foreach($players as $entry)

			{

				$entry = htmlspecialchars($entry);

				if($i % 2 == 0)

				{

					$rowStr = $rowStr . "<tr><td><p align=\"center\"><b>$entry</b><br><br></p></td>";

				}

				else

				{

					$rowStr = $rowStr . "<td><p align=\"center\"><b>$entry</b><br><br></p></td></tr>\n";

				}

				$i++;

			}

			if($i % 2 > 0) // if did not end cleanly, tidy up last entry

			{

				$rowStr = $rowStr . "<td><h1>&nbsp;</h1></td></tr>\n";

			}

			echo $rowStr;

echo "</table>\n";

	  }

	  else

	  {

		echo "<p align=\"center\"><b>There are currently no players on this server</b></p>";

	  }

   }

   

   /* printUserList */

   function printUserList($pageno,$dbID){

      /* output a members list */

	  

	  $pagination_output = "";

	  

	  $query_count = "SELECT count(*) FROM users WHERE 1";

      $q = "SELECT id,username,lastserver_timestamp FROM users WHERE 1 ORDER BY id ASC";

	  

	  $result = mysql_query($query_count, $this->connection);

	  $query_data = mysql_fetch_row($result);

	  $numrows = $query_data[0];

	  

	  $rows_per_page = 20;

	  $lastpage      = ceil($numrows/$rows_per_page);

	

	  $pageno = (int)$pageno;

	  if ($pageno > $lastpage)

	  {

		  $pageno = $lastpage;

	  }

	  if ($pageno < 1)

	  {

		  $pageno = 1;

	  }



	  if ($pageno == 1)

	  {

		  $pagination_output = $pagination_output .  " FIRST PREV ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " <a href='index.php?p=members&pageno=1'>FIRST</a> ";

		  $prevpage = $pageno-1;

		  $pagination_output = $pagination_output .  " <a href='index.php?p=members&pageno=$prevpage'>PREV</a> ";

	  }

	  if($lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

	  }

	

	  if ($pageno == $lastpage or $lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " NEXT LAST ";

	  }

	  else

	  {

		  $nextpage = $pageno+1;

		  $pagination_output = $pagination_output .  " <a href='index.php?p=members&pageno=$nextpage'>NEXT</a> ";

		  $pagination_output = $pagination_output .  " <a href='index.php?p=members&pageno=$lastpage'>LAST</a> ";

	  }

	  echo "<p align=\"right\">" . $pagination_output . "</p><hr>";

	

	  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



	  $q = $q . " " . $limit;

	  

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {



echo "<form name=\"addBuddyForm\" action=\"process.php\" method=\"POST\">\n";

echo "<input type=\"hidden\" name=\"buddysearchresults\">";

echo "<input type=\"hidden\" name=\"addbuddy\" value=\"1\">";

echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\">\n";

echo "	<tr>\n";

echo "		<td><b>Username</b></td>\n";

echo "		<td><b>Last Seen Playing</b></td>\n";

echo "		<td><b>Buddy Status</b></td>\n";

echo "	</tr>\n";

echo "	<tr>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "	</tr>\n";



		while($row = mysql_fetch_array( $result ))

		{

			list($id,$username,$lastserver_timestamp) = $row;

			

			if($lastserver_timestamp == 0)

				$lastserver_timestamp = "&nbsp;";

			else

			{

				$lastserver_timestamp = date("D M j, Y, g:i a",$lastserver_timestamp);

			}

			

			if($dbID == $id)

			{

				$status = "&nbsp;";

			}

			else if($this->getUserAlreadyIsBuddy($dbID,$id))

			{

				$status = "already buddy";

			}

			else

			{

				$status = "<a href=\"#\" onclick=\"document.addBuddyForm.buddysearchresults.value=".$id.";document.addBuddyForm.submit();return false\">not buddy (add)</a>";

			}

			

			echo "<tr><td>$username</td><td>$lastserver_timestamp</td><td>$status</td></tr>\n<tr><td><hr></td><td><hr></td><td><hr></td></tr>\n";

		}

echo "</table></form>\n";

echo "<p align=\"right\">" . $pagination_output . "</p>";

	  }

	  else

	  {

		echo "<h2>There are no registered users</h2>";

	  }

   }

   

   

   /* printUserList */

   function printAdminUserList($pageno,$privilegedOnly = false){

      /* output a members list */

	  

	  $pagination_output = "";

	  

	  if($privilegedOnly)

	  {

		$suffix = "userlevel > 1";

	  }

	  else

	  {

		$suffix = "1";

	  }

	  

	  $query_count = "SELECT count(*) FROM users WHERE $suffix";

      $q = "SELECT id,username,email,userlevel FROM users WHERE $suffix ORDER BY username ASC";

	  

	  $result = mysql_query($query_count, $this->connection);

	  $query_data = mysql_fetch_row($result);

	  $numrows = $query_data[0];

	  

	  $rows_per_page = 20;

	  $lastpage      = ceil($numrows/$rows_per_page);

	

	  $pageno = (int)$pageno;

	  if ($pageno > $lastpage)

	  {

		  $pageno = $lastpage;

	  }

	  if ($pageno < 1)

	  {

		  $pageno = 1;

	  }



	  if ($pageno == 1)

	  {

		  $pagination_output = $pagination_output .  " FIRST PREV ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " <a href='index.php?p=admin&admin=members&pageno=1'>FIRST</a> ";

		  $prevpage = $pageno-1;

		  $pagination_output = $pagination_output .  " <a href='index.php?p=admin&admin=members&pageno=$prevpage'>PREV</a> ";

	  }

	  if($lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

	  }

	

	  if ($pageno == $lastpage or $lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " NEXT LAST ";

	  }

	  else

	  {

		  $nextpage = $pageno+1;

		  $pagination_output = $pagination_output .  " <a href='index.php?p=admin&admin=members&pageno=$nextpage'>NEXT</a> ";

		  $pagination_output = $pagination_output .  " <a href='index.php?p=admin&admin=members&pageno=$lastpage'>LAST</a> ";

	  }

	  echo "<p align=\"right\">" . $pagination_output . "</p><hr>";

	

	  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



	  $q = $q . " " . $limit;

	  

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\">\n";

echo "	<tr>\n";

echo "		<td><b>Username</b></td>\n";

echo "		<td><b>E-Mail Address</b></td>\n";

echo "		<td><b>Status</b></td>\n";

echo "		<td><b>Actions</b></td>\n";

echo "	</tr>\n";

echo "	<tr>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "	</tr>\n";



		while($row = mysql_fetch_array( $result ))

		{

			list($id,$username,$email,$userlevel) = $row;

			if($userlevel == 1) $userlevel = "----------";

			else if($userlevel == 2) $userlevel = "Query Admin";

			else if($userlevel == 3) $userlevel = "Administrator";

			echo "<tr><td>$username</td><td>$email</td><td>$userlevel</td><td><a href=\"index.php?p=admin&admin=modify&user=$id\">Modify User</a></td></tr>\n<tr><td><hr></td><td><hr></td><td><hr></td><td><hr></td></tr>\n";

		}

echo "</table>\n";

echo "<p align=\"right\">" . $pagination_output . "</p>";

	  }

	  else

	  {

		echo "<h2>There are no registered users</h2>";

	  }

   }

   

   function printAdminSearchList($pageno,$name)

   {

      /* output a members list */

	  

	  $pagination_output = "";

	  

	  $query_count = "SELECT count(*) FROM users WHERE username LIKE '%".$name."%' OR email LIKE '".$name."'";

      $q = "SELECT id,username,email FROM users WHERE username LIKE '%".$name."%' OR email LIKE '%".$name."%' ORDER BY username ASC";

	  

	  $result = mysql_query($query_count, $this->connection);

	  $query_data = mysql_fetch_row($result);

	  $numrows = $query_data[0];

	  

	  $rows_per_page = 20;

	  $lastpage      = ceil($numrows/$rows_per_page);

	

	  $pageno = (int)$pageno;

	  if ($pageno > $lastpage)

	  {

		  $pageno = $lastpage;

	  }

	  if ($pageno < 1)

	  {

		  $pageno = 1;

	  }



	  if ($pageno == 1)

	  {

		  $pagination_output = $pagination_output .  " FIRST PREV ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.getElementById('pageno').value=1;document.forms['adminSearchForm'].submit();\">FIRST</a> ";

		  $prevpage = $pageno-1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.getElementById('pageno').value=$prevpage;document.forms['adminSearchForm'].submit();\">PREV</a> ";

	  }

	  if($lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

	  }

	

	  if ($pageno == $lastpage or $lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " NEXT LAST ";

	  }

	  else

	  {

		  $nextpage = $pageno+1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.getElementById('pageno').value=$nextpage;document.forms['adminSearchForm'].submit();\">NEXT</a> ";

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.getElementById('pageno').value=$lastpage;document.forms['adminSearchForm'].submit();\">LAST</a> ";

	  }

	  echo "<p align=\"right\">" . $pagination_output . "</p><hr>";

	

	  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



	  $q = $q . " " . $limit;

	  

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\">\n";

echo "	<tr>\n";

echo "		<td><b>Username</b></td>\n";

echo "		<td><b>E-Mail Address</b></td>\n";

echo "		<td><b>Actions</b></td>\n";

echo "	</tr>\n";

echo "	<tr>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "		<td>&nbsp;</td>\n";

echo "	</tr>\n";



		while($row = mysql_fetch_array( $result ))

		{

			list($id,$username,$email) = $row;

			echo "<tr><td>$username</td><td>$email</td><td><a href=\"index.php?p=admin&admin=modify&user=$id\">Modify User</a></td></tr>\n<tr><td><hr></td><td><hr></td><td><hr></td></tr>\n";

		}

echo "</table>\n";

echo "<p align=\"right\">" . $pagination_output . "</p>";

	  }

	  else

	  {

		echo "<h2>User(s) not found in the database</h2>";

	  }

   }



   function printAdminQuery($pageno,$field,$wide,$name)

   {

	  $pagination_output = "";

	  if($field == "client_id" || $field == "playername" || $field == "player_ip" || $field == "hostname")

	  	{$show_simpleoverview = true;}

		

	  if($field == "client_id" || $field == "playername" || $field == "player_ip" || $field == "hostname" || $field == "server_name")

	  {

	    if($field == "playername")

		{

			$name = $this->urlSafeReplace($name);

		}

	    // eg. WHERE client_id = 'pants'

		if($wide)

		{

			$field = $field . " LIKE '%".$name."%'";

		}

		else

		{

			$field = $field . " LIKE '".$name."'";

		}

	  }

	  else

	  {

		$field = "1"; // WHERE 1, browses all

	  }

	  

	  $query_count = "SELECT count(*) FROM access_log WHERE " . $field;

      $q = "SELECT id,client_id,playername,player_ip,hostname,server_name,timestamp FROM access_log WHERE " . $field . " ORDER BY timestamp DESC";

      $z = "SELECT client_id,playername,player_ip FROM access_log WHERE " . $field . " ORDER BY timestamp DESC";

	  

	  $result = mysql_query($query_count, $this->connection);

	  $query_data = mysql_fetch_row($result);

	  $numrows = $query_data[0];

	  

	  $rows_per_page = 20;

	  $lastpage      = ceil($numrows/$rows_per_page);

	

	  $pageno = (int)$pageno;

	  if ($pageno > $lastpage)

	  {

		  $pageno = $lastpage;

	  }

	  if ($pageno < 1)

	  {

		  $pageno = 1;

	  }



	  if ($pageno == 1)

	  {

		  $pagination_output = $pagination_output .  " FIRST PREV ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].pageno.value=1;document.forms['adminQueryForm'].submit();\">FIRST</a> ";

		  $prevpage = $pageno-1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].pageno.value=$prevpage;document.forms['adminQueryForm'].submit();\">PREV</a> ";

	  }

	  if($lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

	  }

	

	  if ($pageno == $lastpage or $lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " NEXT LAST ";

	  }

	  else

	  {

		  $nextpage = $pageno+1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].pageno.value=$nextpage;document.forms['adminQueryForm'].submit();\">NEXT</a> ";

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].pageno.value=$lastpage;document.forms['adminQueryForm'].submit();\">LAST</a> ";

	  }

	// quick overview..................................................

	// We can't limit the results for this, or we would only get the info of this particular page.

	// We only use this when the searchfunction is "EXACT MATCH" or the search result will get too big anyway

	if(!isset($_SESSION['adminQueryWide']) && $show_simpleoverview == true)

	{

	$overview = mysql_query($z, $this->connection);

	if(mysql_numrows($overview) > 0)

	{

		while($row = mysql_fetch_array( $overview ))

		{

			list($client_id,$playername,$player_ip) = $row;

			$a_client_id[]=$client_id;

			$a_playername[]=$playername;

			$a_player_ip[]=$player_ip;

		}

	

	echo '<h1>Simple Overview</h1><hr><br>';

	if(count($a_client_id) >= 2){$a_client_id=array_unique($a_client_id);}

	if(count($a_playername) >= 2){$a_playername=array_unique($a_playername);}

	if(count($a_player_ip) >= 2){$a_player_ip=array_unique($a_player_ip);}

	echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n";

	echo '<tr><th>ID\'s ('.count($a_client_id).')</th><th>Nickname\'s ('.count($a_playername).')</th><th>Ip\'s ('.count($a_player_ip).')</th></tr>';

	echo '<tr><td style="vertical-align:top"><div style="max-height:100px; width:100%; overflow:auto;" align="center">';

	foreach($a_client_id as $a){

	echo "<a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 0;document.forms['adminQueryForm'].query.value='$a';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$a</a><br>";

	}

	echo'</div></td><td style="vertical-align:top"><div style="max-height:100px; width:100%; overflow:auto;" align="center">';

	foreach($a_playername as $b){

		echo "<a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 1;document.forms['adminQueryForm'].query.value='".$this->urlSafeDecode($b)."';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">".$this->urlSafeDecode($b)."</a><br>";}

	echo'</div></td><td style="vertical-align:top"><div style="max-height:100px; width:100%; overflow:auto;" align="center">';

	foreach($a_player_ip as $c){

		echo"<a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 2;document.forms['adminQueryForm'].query.value='$c';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$c</a><br>";}

	echo'</div></td></tr>';

	// out put custom query...

	echo "</table>\n<hr>";

	empty($client_id);

	empty($playername);

	empty($player_ip);

	}

	}

	// quick overview...................................................

	echo '<br><h1>Detailed Overview</h1>';



	  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



	  $q = $q . " " . $limit;

	  

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

		  	echo "<p align=\"right\">" . $pagination_output . "</p><hr>";



echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n";

		while($row = mysql_fetch_array( $result ))

		{

			list($id,$client_id,$playername,$player_ip,$hostname,$server_name,$timestamp) = $row;

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 0;document.forms['adminQueryForm'].query.value='$client_id';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$client_id</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 1;document.forms['adminQueryForm'].query.value='".$this->urlSafeDecode($playername)."';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">".$this->urlSafeDecode($playername)."</a></td></tr>\n";

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 3;document.forms['adminQueryForm'].query.value='$hostname';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$hostname</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 2;document.forms['adminQueryForm'].query.value='$player_ip';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$player_ip</a></td></tr>\n";

			echo "<tr><td>".date("F j, Y, g:i a",$timestamp)."</td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminQueryForm'].searchby.selectedIndex = 4;document.forms['adminQueryForm'].query.value='$server_name';document.forms['adminQueryForm'].wide.selectedIndex = 0;document.forms['adminQueryForm'].submit();\">$server_name</a></td></tr>\n";

			echo "<tr><td><hr></td><td><hr></td></tr>\n";

		}

echo "</table>\n";

echo "<p align=\"right\">" . $pagination_output . "</p>";



	  }

	  else

	  {

		echo "<h2>No matches found in the database</h2>";

	  }

   }

   

   function printActionsQuery($pageno,$field,$wide,$name)

   {

	  $pagination_output = "";

	  

	  if($field == "performer_client_id" || $field == "performer_playername" || $field == "performer_player_ip" || $field == "performer_hostname" || $field == "receiver_client_id" || $field == "receiver_playername" || $field == "receiver_player_ip" || $field == "receiver_hostname" || $field == "server_name")

	  {

	    if($field == "performer_playername" || $field == "receiver_playername")

		{

			$name = $this->urlSafeReplace($name);

		}

	    // eg. WHERE client_id = 'pants'

		if($wide)

		{

			$field = $field . " LIKE '%".$name."%'";

		}

		else

		{

			$field = $field . " LIKE '".$name."'";

		}

	  }

	  else if($field == "browse_muted")

	  {

		$field = "information LIKE '%muted%'";

	  }

	  else if($field == "browse_renamed")

	  {

		$field = "information LIKE '%renamed%'";

	  }

	  else if($field == "browse_kicked")

	  {

		$field = "information LIKE '%kicked%'";

	  }

	  else if($field == "browse_banned")

	  {

		$field = "information LIKE '%banned%'";

	  }

	  else

	  {

		$field = "1"; // WHERE 1, browses all

	  }

	  

	  $query_count = "SELECT count(*) FROM actions_log WHERE " . $field;

      $q = "SELECT id,performer_client_id,performer_playername,performer_player_ip,performer_hostname,receiver_client_id,receiver_playername,receiver_player_ip,receiver_hostname,server_name,information,timestamp FROM actions_log WHERE " . $field . " ORDER BY timestamp DESC";



	  $result = mysql_query($query_count, $this->connection);

	  $query_data = mysql_fetch_row($result);

	  $numrows = $query_data[0];

	  

	  $rows_per_page = 10;

	  $lastpage      = ceil($numrows/$rows_per_page);

	

	  $pageno = (int)$pageno;

	  if ($pageno > $lastpage)

	  {

		  $pageno = $lastpage;

	  }

	  if ($pageno < 1)

	  {

		  $pageno = 1;

	  }



	  if ($pageno == 1)

	  {

		  $pagination_output = $pagination_output .  " FIRST PREV ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].pageno.value=1;document.forms['adminActionsForm'].submit();\">FIRST</a> ";

		  $prevpage = $pageno-1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].pageno.value=$prevpage;document.forms['adminActionsForm'].submit();\">PREV</a> ";

	  }

	  if($lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

	  }

	  else

	  {

		  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

	  }

	

	  if ($pageno == $lastpage or $lastpage == 0)

	  {

		  $pagination_output = $pagination_output .  " NEXT LAST ";

	  }

	  else

	  {

		  $nextpage = $pageno+1;

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].pageno.value=$nextpage;document.forms['adminActionsForm'].submit();\">NEXT</a> ";

		  $pagination_output = $pagination_output .  " <a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].pageno.value=$lastpage;document.forms['adminActionsForm'].submit();\">LAST</a> ";

	  }

	  echo "<p align=\"right\">" . $pagination_output . "</p><hr>";

	

	  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



	  $q = $q . " " . $limit;

	  

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n";

		while($row = mysql_fetch_array( $result ))

		{

			list($id,$performer_client_id,$performer_playername,$performer_player_ip,$performer_hostname,$receiver_client_id,$receiver_playername,$receiver_player_ip,$receiver_hostname,$server_name,$information,$timestamp) = $row;

			echo "<tr><td>Action Performed By:</td><td>&nbsp;</td></tr>";

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 0;document.forms['adminActionsForm'].query.value='$performer_client_id';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$performer_client_id</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 1;document.forms['adminActionsForm'].query.value='".$this->urlSafeDecode($performer_playername)."';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">".$this->urlSafeDecode($performer_playername)."</a></td></tr>\n";

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 3;document.forms['adminActionsForm'].query.value='$performer_hostname';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$performer_hostname</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 2;document.forms['adminActionsForm'].query.value='$performer_player_ip';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$performer_player_ip</a></td></tr>\n";

			echo "<tr><td><br>Action Performed Upon:</td><td><br>&nbsp;</td></tr>";

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 4;document.forms['adminActionsForm'].query.value='$receiver_client_id';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$receiver_client_id</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 5;document.forms['adminActionsForm'].query.value='".$this->urlSafeDecode($receiver_playername)."';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">".$this->urlSafeDecode($receiver_playername)."</a></td></tr>\n";

			echo "<tr><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 7;document.forms['adminActionsForm'].query.value='$receiver_hostname';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$receiver_hostname</a></td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 6;document.forms['adminActionsForm'].query.value='$receiver_player_ip';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$receiver_player_ip</a></td></tr>\n";

			echo "<tr><td><br></td><td><br></td></tr>";

			echo "<tr><td valign=\"top\">".$this->urlSafeDecode($information)."</td><td><a href=\"javascript:void(0);\" onclick=\"document.forms['adminActionsForm'].searchby.selectedIndex = 8;document.forms['adminActionsForm'].query.value='$server_name';document.forms['adminActionsForm'].wide.selectedIndex = 0;document.forms['adminActionsForm'].submit();\">$server_name</a><br>".date("F j, Y, g:i a",$timestamp)."</td></tr>\n";

			echo "<tr><td><hr></td><td><hr></td></tr>\n";

		}

echo "</table>\n";

echo "<p align=\"right\">" . $pagination_output . "</p>";

	  }

	  else

	  {

		echo "<h2>No matches found in the database</h2>";

	  }

   }

   

   /* getUserHasBuddyNotification */

   function getUserHasBuddyNotification($dbID){

      /* checks to see if user has any buddy notifications waiting */

      $q = "SELECT id FROM buddy_requests WHERE receiver_id = ".$dbID;

      $result = mysql_query($q, $this->connection);



      if(mysql_numrows($result) > 0)

	  {

		 return true;

	  }

	  return false;

   }

   

   function getUserBuddyNotifications($dbID){

      /* return buddy requests as a comma-delimited string */

	  $outStr = "";

      $q = "SELECT requester_id FROM buddy_requests WHERE receiver_id = ".$dbID." LIMIT 16";

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$outputArray = array();

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($requester_id) = $row;



			$q_name = "SELECT username FROM users WHERE id = ".$requester_id;

			$result_name = mysql_query($q_name, $this->connection);

			if($result_name && (mysql_numrows($result_name) > 0))

			{

				$dbarray = mysql_fetch_array($result_name);

				$outputArray[$i] = $dbarray['username'].";".$requester_id;

				$i++;

			}

		}

		natcasesort($outputArray);

		foreach($outputArray as $entry)

		{

			$entry = explode(";",$entry);

			$outStr = $outStr . $entry[1].';'.$entry[0].",";

		}

		// slice off last comma

		$outStr = substr($outStr, 0, -1);

		return $outStr;

	  }

	  else

	  {

		return "none";

	  }

   }



   /* getUserAlreadyHasBuddyRequest */

   function getUserAlreadyHasBuddyRequest($dbID,$buddyID){

      /* checks to see if user $dbID already has a buddy request that is unanswered from $buddyID */

      $q = "SELECT id FROM buddy_requests WHERE receiver_id = ".$buddyID." AND requester_id = ".$dbID;

      $result = mysql_query($q, $this->connection);



      if(mysql_numrows($result) > 0)

	  {

		 return true;

	  }

	  return false;

   }

   

   /* getUserAlreadyIsBuddy */

   function getUserAlreadyIsBuddy($dbID,$buddyID){

   /* checks to see if user $dbID already is a buddy of $buddyID */

      $q = "SELECT id FROM buddy_list WHERE buddy1_id = ".$dbID." AND buddy2_id = ".$buddyID." OR buddy1_id = ".$buddyID." AND buddy2_id = ".$dbID;

      $result = mysql_query($q, $this->connection);



      if(mysql_numrows($result) > 0)

	  {

		 return true;

	  }

	  return false;

   }



    // urlSafeReplace, based on urlEncode by Defrost, Zeropoint Productions, 2009

	function urlSafeReplace($url)

	{

		$index = 0;

		$cs = "";

		$ns = "";

		$ascnr = 0;

		$output = "";

		

		// Encode each character in the string.

		while ($index < strlen($url)) {

			// Retrieve character to encode.

			$cs = substr($url, $index, 1);

			

			// Encode character.

			if(ctype_alnum($cs) || ($cs == "-") || ($cs == "_") || ($cs == ".") || ($cs == "[") || ($cs == "]") || ($cs == "<") || ($cs == ">") ||

				 ($cs == "(") || ($cs == ")") || ($cs == "*") || ($cs == "|") || ($cs == "~") || ($cs == "^") ||

					 ($cs == "{") || ($cs == "}") || ($cs == "$") || ($cs == "=") || ($cs == ":") || ($cs == ";") || ($cs == "!") || ($cs == "+"))

			{

			    $ns = $cs;

			}

			else

			{

				$ascnr = ord($cs);



				if ($ascnr > 126) // higher than valid character

					$ascnr = 95; //95 = underscore



				$ns = "@" . str_pad($ascnr, 3, "0", STR_PAD_LEFT);

			}



			$output = $output . $ns;

			$index++;

		}

		

		// Return encoded string

		return $output;

	}

   

   function urlSafeDecode($url,$safeStoreMode = False)

   {

		$index = 0;

		$output = "";

		$cs = "";



		while ($index < strlen($url))

		{

			$cs = substr($url, $index, 1);

			if($cs == "@")

			{

				if(substr($url, $index + 1, 3) > 126) // last human-readable character on the ASCII table is 126

				{

					$output = $output . "_";

					$index += 4;

				}

				else if(!$safeStoreMode)

				{

					$output = $output . chr(substr($url, $index + 1, 3));

					$index += 4;

				}

				else

				{

					$output = $output . $cs;

					$index++;

				}

			}

			else

			{

				$output = $output . $cs;

				$index++;

			}

		}	

		return $output;

   }

   

   function savePMHistory($sender_id,$receiver_id,$preamble,$msg)

   {

      $query_count = "SELECT count(*) FROM private_msg WHERE receiver_id = $receiver_id";

      $result = mysql_query($query_count, $this->connection);

      $query_data = mysql_fetch_row($result);

      $numrows = $query_data[0];



	  if($numrows >= 100)

	  {

		// delete messages, save the most recent 100

		$q = "DELETE FROM private_msg WHERE receiver_id = $receiver_id ORDER BY timestamp ASC LIMIT 1";

		$result = mysql_query($q, $this->connection);

	  }



      $q = "INSERT INTO private_msg (sender_id, receiver_id, timestamp, preamble, msg) VALUES ($sender_id,$receiver_id,".time().",'$preamble','$msg')";

      $result = mysql_query($q, $this->connection);

   }

   

   function secretQuestionIsCorrect($user,$answerq)

   {

      $q = "SELECT answerq FROM users WHERE username = '$user' LIMIT 1";

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$dbarray = mysql_fetch_array($result);

		if($dbarray['answerq'] == md5($answerq))

			return true;

		else

			return false;

	  }

	  return false;

   }

   

   function printSecretQuestion($user)

   {

      $q = "SELECT secretq FROM users WHERE username = '$user' LIMIT 1";

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$dbarray = mysql_fetch_array($result);

		echo "<h1>Secret Question: ".$dbarray['secretq']."</h1>";

	  }

	  else

	  {

		$q = "SELECT secretq FROM users WHERE email = '$user' LIMIT 1";

		$result = mysql_query($q, $this->connection);

		if(mysql_numrows($result) > 0)

		{

			$dbarray = mysql_fetch_array($result);

			echo "<h1>Secret Question: ".$dbarray['secretq']."</h1>";

		}

		else

		{

			echo "<h1>Invalid username!</h1>";

		}

	  }

   }

   

   function printCurrentPMHistory($dbID,$realtime = true,$pageno = 0)

   {

	  $pagination_output = "";

	  

	  $query_count = "SELECT count(*) FROM private_msg WHERE sender_id = ".$dbID." OR receiver_id = ".$dbID;

      $q = "SELECT timestamp,preamble,msg FROM private_msg WHERE sender_id = ".$dbID." OR receiver_id = ".$dbID." ORDER BY timestamp DESC";

	  

	  if($realtime)

	  {

		$q = $q . " LIMIT 25";

	  }

	  else

	  {	  

		  $result = mysql_query($query_count, $this->connection);

		  $query_data = mysql_fetch_row($result);

		  $numrows = $query_data[0];

		  

		  $rows_per_page = 20;

		  $lastpage      = ceil($numrows/$rows_per_page);

		

		  $pageno = (int)$pageno;

		  if ($pageno > $lastpage)

		  {

			  $pageno = $lastpage;

		  }

		  if ($pageno < 1)

		  {

			  $pageno = 1;

		  }



		  if ($pageno == 1)

		  {

			  $pagination_output = $pagination_output .  " FIRST PREV ";

		  }

		  else

		  {

			  $pagination_output = $pagination_output .  " <a href='index.php?p=messages&archive=true&pageno=1'>FIRST</a> ";

			  $prevpage = $pageno-1;

			  $pagination_output = $pagination_output .  " <a href='index.php?p=messages&archive=true&pageno=$prevpage'>PREV</a> ";

		  }

		  if($lastpage == 0)

		  {

			  $pagination_output = $pagination_output .  " ( Page 1 of 1 ) ";

		  }

		  else

		  {

			  $pagination_output = $pagination_output .  " ( Page $pageno of $lastpage ) ";

		  }

		

		  if ($pageno == $lastpage or $lastpage == 0)

		  {

			  $pagination_output = $pagination_output .  " NEXT LAST ";

		  }

		  else

		  {

			  $nextpage = $pageno+1;

			  $pagination_output = $pagination_output .  " <a href='index.php?p=messages&archive=true&pageno=$nextpage'>NEXT</a> ";

			  $pagination_output = $pagination_output .  " <a href='index.php?p=messages&archive=true&pageno=$lastpage'>LAST</a> ";

		  }

		

		  $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;



		  $q = $q . " " . $limit;

	  }

	  

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		if(!$realtime && strlen($pagination_output) > 0)

			echo "<p align=\"right\">" . $pagination_output . "</p><hr>";

	    echo "<table border=\"0\" width=\"98%\" cellspacing=\"0\" cellpadding=\"0\">\n";

		while($row = mysql_fetch_array( $result ))

		{

			list($timestamp, $preamble, $msg) = $row;

			echo "<tr>\n";

			echo "<td valign=\"top\" width=\"30%\">" . date("M j Y, g:i:sa",$timestamp) . "</td><td>".$this->urlSafeDecode($preamble).":\n<br>" . $this->urlSafeDecode($msg) . "<br>&nbsp;</td>\n";

			echo "</tr>\n";

		}

		echo "</table>";

		if(!$realtime && strlen($pagination_output) > 0)

			echo "<hr><p align=\"right\">" . $pagination_output . "</p>";

	  }

	  else

	  {

		echo "Your private message log is empty.";

	  }

   }

   

   /* printBuddyListOptions */

   function printBuddyListOptions($dbID){



      $q = "SELECT buddy1_id, buddy2_id FROM buddy_list WHERE buddy1_id = ".$dbID." OR buddy2_id = ".$dbID;

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$outputArray = array();

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($buddy1_id, $buddy2_id) = $row;



			if($buddy1_id == $dbID)

			{

				$buddyID = $buddy2_id;

			}

			else

			{

				$buddyID = $buddy1_id;

			}



			$q_name = "SELECT username FROM users WHERE id = ".$buddyID;

			$result_name = mysql_query($q_name, $this->connection);

			if($result_name && (mysql_numrows($result_name) > 0))

			{

				$dbarray = mysql_fetch_array($result_name);

				$outputArray[$i] = $dbarray['username'].";".$buddyID;

				$i++;

			}

		}

		natcasesort($outputArray);

		foreach($outputArray as $entry)

		{

			$entry = explode(";",$entry);

			echo '<option value="'.$entry[1].'">'.$entry[0].'</option>';

		}

	  }

	  else

	  {

		echo '<option value="">No Buddies on List</option>';

	  }

   }

   

   /* printBuddySearchResults */

   function printBuddySearchResults(){

   

	  if(!isset($_POST['buddysearchname']) || strlen($_POST['buddysearchname']) == 0)

	  {

		 return;

	  }

	  else if(strlen($_POST['buddysearchname']) < 2)

	  {

		echo '<option value="">Your search is too short!</option>';

		echo '<option value="">There is a two character minimum.</option>';

		return;

	  }

	  $usernameSearch = mysql_real_escape_string(trim($_POST['buddysearchname']));

	  

      $q = "SELECT id,username FROM users WHERE username LIKE '%".$usernameSearch."%'";

      $result = mysql_query($q, $this->connection);

      if(mysql_numrows($result) > 0)

	  {

		$outputArray = array();

		$i = 0;

		while($row = mysql_fetch_array( $result ))

		{

			list($id, $username) = $row;

			$outputArray[$i] = $username.";".$id;

			$i++;

		}

		natcasesort($outputArray);

		foreach($outputArray as $entry)

		{

			$entry = explode(";",$entry);

			echo '<option value="'.$entry[1].'">'.$entry[0].'</option>';

		}

	  }

	  else

	  {

		echo '<option value="">No Matches Found</option>';

	  }

   }

   

   // UT-related functions

   //==========================================================================



   /* UTAttemptServerPlayerLogin */

   function UTAttemptPlayerLogin($universeusername, $universeuserpass, $playername, $fromserver){

      // see if username and password match any rows



	  $buddyStr = "";

	  $k = 0;

	  $i = 0;

	  $universeuserpass = strtolower($universeuserpass);

	  $sendStr = Array();

	  

      $q = "SELECT id,username FROM users WHERE username = '$universeusername' AND password = '$universeuserpass'";

      $result = mysql_query($q, $this->connection);

      if($result && mysql_numrows($result) > 0)

	  {

		// great, user exists and passwords match

		$dbarray = mysql_fetch_array($result);

		$playerid = $dbarray['id'];

		$universeusername = $dbarray['username'];



		//so let's get some server data for the server this player is *currently playing on*

		$q = "SELECT id,server_name FROM server_list WHERE server_url = '$fromserver'";

		$result = mysql_query($q, $this->connection);

		if($result && mysql_numrows($result) > 0)

		{

			// great, server exists

			$dbarray = mysql_fetch_array($result);

			$serverid = $dbarray['id'];

			$servername = $dbarray['server_name'];



			$q = "UPDATE users SET lastserver_id = $serverid, lastserver_timestamp = ".time().", lastserver_playername = '$playername', active_now = 1 WHERE id = $playerid";

			mysql_query($q, $this->connection);

			

		    $q = "SELECT buddy1_id, buddy2_id FROM buddy_list WHERE buddy1_id = ".$playerid." OR buddy2_id = ".$playerid;

		    $result = mysql_query($q, $this->connection);

		    if(mysql_numrows($result) > 0)

		    {

			  while($row = mysql_fetch_array( $result ))

			  {

				  list($buddy1_id, $buddy2_id) = $row;



				  if($buddy1_id == $playerid)

				  {

				  	$buddyID = $buddy2_id;

				  }

				  else

				  {

					$buddyID = $buddy1_id;

				  }



				  // search for all buddies that are active. get some info about where they were last seen

				  $q_lastserver = "SELECT username,lastserver_id,lastserver_playername FROM users WHERE id = ".$buddyID." AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800);

				  $result_lastserver = mysql_query($q_lastserver, $this->connection);



				  if($result_lastserver && (mysql_numrows($result_lastserver) > 0))

				  {

					$dbarray = mysql_fetch_array($result_lastserver);

					$lastserver_id = $dbarray['lastserver_id'];

					$sendtouser = $dbarray['username'];

					$lastserver_playername = $dbarray['lastserver_playername'];

					

					// match that server id to a server list entry

					$q_lastservername = "SELECT server_name,server_url,server_tcpport FROM server_list WHERE id = ".$lastserver_id;

					$result_lastservername = mysql_query($q_lastservername, $this->connection);

					if($result_lastservername && (mysql_numrows($result_lastservername) > 0))

					{

					  $dbarray = mysql_fetch_array($result_lastservername);

					  $connectto = $dbarray['server_url'];

					  $connectto = substr($connectto, 0, strpos($connectto,":") + 1) . $dbarray['server_tcpport'];



					  $sendStr[$i] = "http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::alertbuddy:::".$sendtouser.":::".$universeusername.":::".$playername.":::".$servername.":::".$fromserver."&";

					  $i++;



					  if($k < 10) // limits the buddyStr to 10 players, which is as much as our UT component can handle

					  {

						  $buddyStr = $buddyStr . $sendtouser . " (as " . $lastserver_playername . ") @064 " . $dbarray['server_name'] . ":::";

						  $k++;

					  }

					}	

				  }

			    }

			}

		}

		else

		{

			echo "!!!return-data!!!&universe-player-login#".$universeusername."#error#the server url given did not exist in the database&";

			return;

		}

		if(strlen($buddyStr) > 0)

		{

			$buddyStr = substr($buddyStr, 0, -3);

		}

		else

		{

			$buddyStr = "none";

		}



		$hasBuddyNotification = $this->getUserBuddyNotifications($playerid);

		echo "!!!return-data!!!&universe-player-login#".$universeusername."#accepted#".$hasBuddyNotification."#".$buddyStr."&<!--EOL-->";



		ob_flush();

		flush();

		

		foreach ($sendStr as $value)

		{

			$this->query_url($value);

		}

	  }

	  else

	  {

		echo "!!!return-data!!!&universe-player-login#".$universeusername."#denied&";

	  }

   }

   

   function UTStartNewMatch($fromserver,$newgamesession) {



	  $players = array();

	  $i = 0;

	  

	  $q = "SELECT id FROM server_list WHERE server_url = '$fromserver'";

	  $result = mysql_query($q, $this->connection);

	  if($result && mysql_numrows($result) > 0)

	  {

		$dbarray = mysql_fetch_array($result);

		$serverid = $dbarray['id'];

		$q = "SELECT username FROM users WHERE lastserver_id = $serverid AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800);

		$result = mysql_query($q, $this->connection);

		if(mysql_numrows($result) > 0)

		{

		  while($row = mysql_fetch_array( $result ))

		  {

			$players[$i] = $row['username'];

			$i++;

			if($i > 32) break; // UT array can only store 32

		  }

		}

		$this->UTAttemptMassPlayerLogout($players, $fromserver);

		

	    $q = "UPDATE server_list SET gamesession = '$newgamesession' WHERE id = $serverid";

	    $result = mysql_query($q, $this->connection);

	  }

   }

   

   function UTAttemptMassPlayerLogout($players, $fromserver) {



	   $playerStr = "";

	   $playersFound = 0;

   

	   foreach($players as $universeusername)

	   {

	      $q = "SELECT id,lastserver_id FROM users WHERE username = '$universeusername'";

	      $result = mysql_query($q, $this->connection);

	      if($result && mysql_numrows($result) > 0)

		  {

			$dbarray = mysql_fetch_array($result);

			$playerid = $dbarray['id'];

			$serverid = $dbarray['lastserver_id'];

			

			$q = "SELECT server_url FROM server_list WHERE id = '$serverid'";

			$result = mysql_query($q, $this->connection);

			if($result && mysql_numrows($result) > 0)

			{

				$dbarray = mysql_fetch_array($result);



				if($fromserver != $dbarray['server_url'])

				{

					// huh?  The last server they were on isn't the one this request came from?

					// Perhaps they jumped from one to another so quickly that Universal hasn't caught up...

					continue;

				}



				$q = "UPDATE users SET active_now = 0 WHERE id = $playerid";

				mysql_query($q, $this->connection);

				

				$playerStr = $playerStr . $universeusername . ",";

				$playersFound++;

			}

		  }

	   }

	   // slices off the last comma

	   if($playersFound > 0)

	      $playerStr = substr($playerStr, 0, -1);



	   if($playersFound == 0)

	     return;



	   $q = "SELECT server_url,server_tcpport FROM server_list WHERE briefinfo_players != ''";

	   $result = mysql_query($q, $this->connection);

	   if(mysql_numrows($result) > 0)

	   {

	     while($row = mysql_fetch_array( $result ))

	     {

		   list($server_url,$server_tcpport) = $row;

		   $connectto = substr($server_url, 0, strpos($server_url,":") + 1) . $server_tcpport;



		   $this->query_url("http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::processlogout:::".$playerStr."&");

	     }

	   }

   }



   function UTAttemptPlayerLogout($universeusername, $fromserver) {



      $q = "SELECT id,lastserver_id FROM users WHERE username = '$universeusername'";

      $result = mysql_query($q, $this->connection);

      if($result && mysql_numrows($result) > 0)

	  {

		$dbarray = mysql_fetch_array($result);

		$playerid = $dbarray['id'];

		$serverid = $dbarray['lastserver_id'];

		

		$q = "SELECT server_url FROM server_list WHERE id = '$serverid'";

		$result = mysql_query($q, $this->connection);

		if($result && mysql_numrows($result) > 0)

		{

			$dbarray = mysql_fetch_array($result);



			if($fromserver != $dbarray['server_url'])

			{

				// huh?  The last server they were on isn't the one this request came from?

				// Perhaps they jumped from one to another so quickly that Universal hasn't caught up...

				return;

			}



			$q = "UPDATE users SET active_now = 0 WHERE id = $playerid";

			mysql_query($q, $this->connection);



			$q = "SELECT server_url,server_tcpport FROM server_list WHERE briefinfo_players != ''";

			$result = mysql_query($q, $this->connection);

			if(mysql_numrows($result) > 0)

			{

			  while($row = mysql_fetch_array( $result ))

			  {

				list($server_url,$server_tcpport) = $row;

				$connectto = substr($server_url, 0, strpos($server_url,":") + 1) . $server_tcpport;



				$this->query_url("http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::processlogout:::".$universeusername."&");

			  }

		    }

		}

	  }

   }



   function UTCheckBriefInfo()

   {

	  $q = "SELECT id,server_url,server_tcpport,briefinfo_timestamp,briefinfo_cachetime FROM server_list WHERE 1";

	  $result = mysql_query($q, $this->connection);

	  if($result && mysql_numrows($result) > 0)

	  {

	    while($row = mysql_fetch_array( $result ))

	    {

		  list($id,$server_url,$server_tcpport,$briefinfo_timestamp,$briefinfo_cachetime) = $row;

		  

		  if($briefinfo_timestamp <= (time() - $briefinfo_cachetime))

		  {

		    $connectto = substr($server_url, 0, strpos($server_url,":") + 1) . $server_tcpport;



		    $this->query_url("http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::sendbriefinfo&");

		  }

	    }

	  }

   }

   

   function UTPlayerLookup($fromserver, $scope, $clientid, $username, $segment)

   {

      $scopeStr = "";

	  $nameStr = "";

	  $ipHostStr = "";

	  $accessStr = "";

	  $actionsStr = "";



	  if(strtolower($scope) == "local")

	  {

		$scopeStr = "AND server_name = '".$this->UTRetrieveNameByURL($fromserver)."' ";

	  }

	  else

	  {

		if(strtolower($scope) != "universal")

		{

			die();

		}

	  }

	  

	  $outStr = "!!!return-data!!!&player-lookup-" . $segment . "#" . $username;

	  

	  if($segment == "1")

	  {

		  $q = "SELECT DISTINCT playername FROM access_log WHERE client_id = '".$clientid."' ".$scopeStr." ORDER BY playername ASC LIMIT 32";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

		    while($row = mysql_fetch_array( $result ))

		    {

			  $nameStr = $nameStr . $row['playername'] . ",";

			}

			$nameStr = substr($nameStr, 0, -1);

		  }

		  else

		  {

			  $nameStr = "None Found";

		  }

		  $outStr = $outStr . "#" . $nameStr;

	  }

	  else if($segment == "2")

	  {

		  $q = "SELECT DISTINCT player_ip,hostname FROM access_log WHERE client_id = '".$clientid."' ".$scopeStr." ORDER BY player_ip ASC LIMIT 32";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

		    while($row = mysql_fetch_array( $result ))

		    {

			  $ipHostStr = $ipHostStr . $row['player_ip'] . "/" . $row['hostname'] . ",";

			}

			$ipHostStr = substr($ipHostStr, 0, -1);

		  }

		  else

		  {

			  $ipHostStr = "None Found";

		  }

		  $outStr = $outStr . "#" . $ipHostStr;

	  }

	  else if($segment == "3")

	  {

		  $q = "SELECT playername,server_name,player_ip,timestamp FROM access_log WHERE client_id = '".$clientid."' ".$scopeStr." ORDER BY timestamp DESC LIMIT 32";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

		    while($row = mysql_fetch_array( $result ))

		    {

			  $accessStr = $accessStr . date("m/d/y g:ia",$row['timestamp']) . "; " . $this->urlSafeDecode($row['playername']) . "; " . $row['server_name'] . "; " . $row['player_ip'] .",";

			}

			$accessStr = substr($accessStr, 0, -1);

		  }

		  else

		  {

			  $accessStr = "None Found";

		  }

		  $outStr = $outStr . "#" . $accessStr;

	  }

	  else if($segment == "4")

	  {

		  $q = "SELECT performer_playername,receiver_playername,information,server_name,timestamp FROM actions_log WHERE receiver_client_id = '".$clientid."' ".$scopeStr." ORDER BY timestamp DESC LIMIT 16";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

		    while($row = mysql_fetch_array( $result ))

		    {

			  $actionsStr = $actionsStr . date("m/d/y g:ia",$row['timestamp']) . "; Done to " . $this->urlSafeDecode($row['receiver_playername']) . " by " . $this->urlSafeDecode($row['performer_playername']) . ":::" . $row['server_name'] . "; " . $row['information'] .",";

			}

			$actionsStr = substr($actionsStr, 0, -1);

		  }

		  else

		  {

			  $actionsStr = "None Found";

		  }

		  $outStr = $outStr . "#" . $actionsStr;

	  }

	  

	  $outStr = $outStr . "&";

	  echo $outStr;

   }

   

   function UTSendPM($fromserver, $to, $from, $msg)

   {

	  $q = "SELECT server_name FROM server_list WHERE server_url = '$fromserver'";

	  $result = mysql_query($q, $this->connection);

	  if($result && mysql_numrows($result) > 0)

	  {

	  	// great, server exists

	  	$dbarray = mysql_fetch_array($result);

		$fromserver = $dbarray['server_name'];

		

		$q = "SELECT id,lastserver_id,username FROM users WHERE username = '".$to."' AND active_now = 1 AND lastserver_timestamp >= ".(time() - 1800) ." LIMIT 1";

		$result = mysql_query($q, $this->connection);

		if($result && mysql_numrows($result) > 0)

		{

	  	  $dbarray = mysql_fetch_array($result);

		  $lastserver_id = $dbarray['lastserver_id'];

		  $toID = $dbarray['id'];

		  $to = $dbarray['username'];



		  $q = "SELECT server_name,server_url,server_tcpport FROM server_list WHERE id = $lastserver_id";

		  $result = mysql_query($q, $this->connection);

		  if($result && mysql_numrows($result) > 0)

		  {

			$dbarray = mysql_fetch_array($result);

		    $connectto = substr($dbarray['server_url'], 0, strpos($dbarray['server_url'],":") + 1) . $dbarray['server_tcpport'];

	

		    $this->query_url("http://".$connectto."/?universalunreal&".$this->urlSafeReplace(UNIVERSE_ID).":::".UNIVERSE_PASS.":::receivepm:::$to:::$fromserver:::$from:::$msg&");

			

			// log the message

			$this->savePMHistory($this->getIDFromName($from),$toID,mysql_real_escape_string($from." (at ".$fromserver.") to ".$to. " (at ".$dbarray['server_name'].")"),mysql_real_escape_string($msg));

		  }

		}

		else

		{

		  // not online

		  if($this->isOnlineWebUser($to))

		  {

			$this->savePMHistory($this->getIDFromName($from),$this->getIDFromName($to),mysql_real_escape_string($from." (at ".$fromserver.") to ".$to. " (at Website)"),mysql_real_escape_string($msg));

		  }

		  else

		  {

			echo "!!!return-data!!!&send-pm-fail#".$from."#not-online&";

		  }

		}

	  }

   }

   

   function UTGetBriefInfo()

   {

	  $q = "SELECT server_name,briefinfo_numplayers,briefinfo_maxplayers,briefinfo_map,briefinfo_timestamp,briefinfo_cachetime FROM server_list WHERE 1 ORDER BY briefinfo_timestamp <= (".time()." - (2 * briefinfo_cachetime)) ASC, briefinfo_numplayers DESC LIMIT 10";

	  $result = mysql_query($q, $this->connection);

	  if($result && mysql_numrows($result) > 0)

	  {

		$outStr = "!!!return-data!!!&brief-info#";

	    while($row = mysql_fetch_array( $result ))

	    {

		  list($server_name,$briefinfo_numplayers,$briefinfo_maxplayers,$briefinfo_map,$briefinfo_timestamp,$briefinfo_cachetime) = $row;

		  

		  if(strlen($briefinfo_map) >= 20)

		  {

			$briefinfo_map = substr($briefinfo_map, 0, 20) . "...";

		  }

		  

		  // if the data is older than (2 * cachetime), consider it unreliable (server down, whatever...)

		  if($briefinfo_timestamp <= (time() - (2 * $briefinfo_cachetime)))

		  {

			$outStr = $outStr . $server_name . ": no data (down?):::";

		  }

		  else

		  {

			$outStr = $outStr . $server_name . ": " . $briefinfo_map . " (" . $briefinfo_numplayers . "/" . $briefinfo_maxplayers . "):::";

		  }

	    }

		$outStr = substr($outStr, 0, -3) . "&<!--EOL-->";

		echo $outStr;

		

		ob_flush();

		flush();

	  }

   }

   

   function UTRecordPlayerData($clientid,$playername,$playerip,$servername)

   {

		// optional param True causes chars with ASCII values > 126 to be stripped to underscores, nothing more

		$playername = mysql_real_escape_string($this->urlSafeDecode($playername,true));



		$q = "DELETE FROM access_log WHERE timestamp <= ".strtotime("-3 Months");

		$result = mysql_query($q, $this->connection);

	  

   		$q = "INSERT INTO access_log (client_id,playername,player_ip,hostname,server_name,timestamp) VALUES ('$clientid','$playername','$playerip','".gethostbyaddr($playerip)."','$servername',".time().")";

		$result = mysql_query($q, $this->connection);

   }



   function UTRecordPlayerActions($performerid,$performername,$performerip,$receiverid,$receivername,$receiverip,$information,$servername)

   {

		// optional param True causes chars with ASCII values > 126 to be stripped to underscores, nothing more

		$performername = mysql_real_escape_string($this->urlSafeDecode($performername,true));

		$receivername = mysql_real_escape_string($this->urlSafeDecode($receivername,true));



		$q = "DELETE FROM actions_log WHERE timestamp <= ".strtotime("-6 Months");

		$result = mysql_query($q, $this->connection);



   		$q = "INSERT INTO actions_log (performer_client_id,performer_playername,performer_player_ip,performer_hostname,receiver_client_id,receiver_playername,receiver_player_ip,receiver_hostname,information,server_name,timestamp) VALUES ('$performerid','$performername','$performerip','".gethostbyaddr($performerip)."','$receiverid','$receivername','$receiverip','".gethostbyaddr($receiverip)."','$information','$servername',".time().")";

		$result = mysql_query($q, $this->connection);

   }

   

   function UTReturnBriefInfo($fromserver, $map, $numplayers, $maxplayers, $players)

   {

	  $q = "UPDATE server_list SET briefinfo_timestamp = " . time() . ", briefinfo_numplayers = $numplayers, briefinfo_maxplayers = $maxplayers, briefinfo_map = '$map', briefinfo_players = '$players' WHERE server_url = '$fromserver'";

	  $result = mysql_query($q, $this->connection);

   }

   

   function UTRetrieveConnectToByURL($url){

	  // match that server id to a server list entry

	  $q = "SELECT server_tcpport FROM server_list WHERE server_url = '".$url."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

		$connectto = substr($url, 0, strpos($url,":") + 1) . $dbarray['server_tcpport'];

		return $connectto;

      }

	  return "255.255.255.255";

   }

   

   function UTCheckLocalLookupAllowed($url){

	  // match that server id to a server list entry

	  $q = "SELECT allow_local_lookup FROM server_list WHERE server_url = '".$url."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

		$dbarray = mysql_fetch_array($result);

		if($dbarray['allow_local_lookup'] > 0)

		{

			return true;

		}

      }

	  return false;

   }

   

   function UTCheckUniversalLookupAllowed($url){

	  // match that server id to a server list entry

	  $q = "SELECT allow_universal_lookup FROM server_list WHERE server_url = '".$url."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

		$dbarray = mysql_fetch_array($result);

		if($dbarray['allow_universal_lookup'] > 0)

		{

			return true;

		}

      }

	  return false;

   }

   

   function UTRetrieveURLByName($name)

   {

	  // match a server name to its URL, different from ConnectToByName because it provides the game port, not the TCP port

	  $q = "SELECT server_url FROM server_list WHERE server_name = '".$name."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

		return $dbarray['server_url'];

      }

	  return "255.255.255.255";

   }

   

   function UTRetrieveNameByURL($url)

   {

	  // match a server name to its URL, different from ConnectToByName because it provides the game port, not the TCP port

	  $q = "SELECT server_name FROM server_list WHERE server_url = '".$url."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

		return $dbarray['server_name'];

      }

	  return "";

   }

   

   function UTRetrieveNameByID($id)

   {

	  // match a server name to its database ID

	  $q = "SELECT server_name FROM server_list WHERE id = ".mysql_real_escape_string($id);

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

		return $dbarray['server_name'];

      }

	  return "";

   }

   

   function UTRetrieveServerListString()

   {

	  // return all servers as comma-delimited to user

      $q = "SELECT server_name FROM server_list WHERE 1 ORDER BY server_name ASC";

      $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

		$i = 0;

		$output = "";

		while($row = mysql_fetch_array( $result ))

		{

			list($server_name) = $row;

			$output = $output . $server_name;

			$i++;

			if(mysql_numrows($result) != $i)

			{

				$output = $output . ", ";

			}

		}

		return $output;

	  }

	  else

	  {

		return "";

	  }

   }

   

   function UTRetrieveConnectToByName($name){

	  // match that server id to a server list entry

	  $q = "SELECT server_url,server_tcpport FROM server_list WHERE server_name = '".$name."'";

	  $result = mysql_query($q, $this->connection);

	  if($result && (mysql_numrows($result) > 0))

	  {

	    $dbarray = mysql_fetch_array($result);

		$url = $dbarray['server_url'];

		$connectto = substr($url, 0, strpos($url,":") + 1) . $dbarray['server_tcpport'];

		return $connectto;

      }

	  return "255.255.255.255";

   }



   //==========================================================================



   /**

    * query - Performs the given query on the database and

    * returns the result, which may be false, true or a

    * resource identifier.

    */

   function query($query){

      return mysql_query($query, $this->connection);

   }

   

   function dailyFunctions()

   {

	  // UPDATE FROM "1.10 Build 3" DATABASE TO "1.10 Build 4" ===================================

	  $q = "SELECT briefinfo_players FROM server_list WHERE briefinfo_players LIKE '%%' LIMIT 1";

	  mysql_query($q, $this->connection) or mysql_query("ALTER TABLE server_list ADD briefinfo_players VARCHAR( 1024 ) NOT NULL AFTER briefinfo_map", $this->connection);

	  // END UPDATE ==========================================================================



	  $servers = "";

	  // e-mail players that haven't been logged in to a server before

	  $q = "SELECT id,email,username FROM users WHERE regtimestamp <= ".(time() - 604800)." AND lastserver_timestamp = 0 AND emailnologinsent = 0";

	  $result = mysql_query($q, $this->connection);

	  if(mysql_numrows($result) > 0)

	  {

	    while($row = mysql_fetch_array( $result ))

	    {

		    list($id, $email, $username) = $row;

			$q_update = "UPDATE users SET emailnologinsent = 1 WHERE id = $id";

			$result_update = mysql_query($q_update, $this->connection);



		    $mailer = new Mailer();

		    $mailer->sendHelp($username,$email);

		}

	  }

	  // check for updates?

	  $q = "SELECT config_value FROM configuration WHERE config_name = 'last_update_check'";

	  $result = mysql_query($q, $this->connection);

	  $dbarray = mysql_fetch_array($result);

	  $last_update_check = $dbarray['config_value'];



	  if($last_update_check <= (time() - 86400))

	  {

		$q = "UPDATE configuration SET config_value = '".time()."' WHERE config_name = 'last_update_check';";

	    $result = mysql_query($q, $this->connection);



	    $q = "SELECT config_value FROM configuration WHERE config_name = 'update_url'";

	    $result = mysql_query($q, $this->connection);

	    $dbarray = mysql_fetch_array($result);

	    $update_url = $dbarray['config_value'];

		

	    $q = "SELECT config_value FROM configuration WHERE config_name = 'newest_version'";

	    $result = mysql_query($q, $this->connection);

	    $dbarray = mysql_fetch_array($result);

	    $old_version = $dbarray['config_value'];

		

		$q = "SELECT count(*) FROM users WHERE 1";

		$result = mysql_query($q, $this->connection);

		$query_data = mysql_fetch_row($result);

		$numusers = $query_data[0];

		

		$q = "SELECT server_url FROM server_list WHERE 1";

		$result = mysql_query($q, $this->connection);

		if(mysql_numrows($result) > 0)

		{

		  while($row = mysql_fetch_array( $result ))

		  {

			  $servers = $row['server_url'] . "," . $servers;

		  }

		  $servers = substr($servers, 0, -1);

		}

		

		$update = @file_get_contents($update_url . "?universe=" . urlencode(UNIVERSE_ID) . "&url=" . urlencode(UNIVERSE_URL) . "&servers=" . urlencode($servers) . "&numusers=" . $numusers);

		$update = explode("|",$update);

		

	    $q = "UPDATE configuration SET config_value = '".mysql_real_escape_string($update[0])."' WHERE config_name = 'newest_version'";

		$result = mysql_query($q, $this->connection);

		$q = "UPDATE configuration SET config_value = '".mysql_real_escape_string($update[1])."' WHERE config_name = 'update_url';";

	    $result = mysql_query($q, $this->connection);

		$q = "UPDATE configuration SET config_value = '".mysql_real_escape_string($update[2])."' WHERE config_name = 'information_url';";

	    $result = mysql_query($q, $this->connection);

		

		if($old_version < $update[0])

		{

		  $mailer = new Mailer();

		  $mailer->sendUpdate($update[2]);

		}

	  }

   }

};



/* Create database connection */

$database = new MySQLDB;

?>

