<?php
	class OpenSim
	{
		public function isLoginValid($name, $password)
		{
			global $RUNTIME;

			$statementUser = $RUNTIME['PDO']->prepare("SELECT * FROM UserAccounts WHERE FirstName = ? AND LastName = ? LIMIT 1");
			$statementUser->execute(explode(" ", trim($name))); 

			while($rowUser = $statementUser->fetch()) 
			{
				$statementAuth = $RUNTIME['PDO']->prepare("SELECT * FROM auth WHERE UUID = ? LIMIT 1");
				$statementAuth->execute(array($rowUser['PrincipalID'])); 

				while($rowAuth = $statementAuth->fetch()) 
				{
					if(md5(md5($password).":".$rowAuth['passwordSalt']) == $rowAuth['passwordHash'])
					{
						return true;
					}
				}
			}

			return false;
		}

		public function getUserName($userID)
		{
			global $RUNTIME;
			
			if(isset($RUNTIME['CACHE']['USERNAME'][$userID]))
				return $RUNTIME['CACHE']['USERNAME'][$userID];

			$statementUser = $RUNTIME['PDO']->prepare("SELECT * FROM UserAccounts WHERE PrincipalID = ?");
			$statementUser->execute(array($userID));

			while($rowUser = $statementUser->fetch()) 
			{
				$RUNTIME['CACHE']['USERNAME'][$userID] = $rowUser['FirstName']." ".$rowUser['LastName'];
				return $rowUser['FirstName']." ".$rowUser['LastName'];
			}

			return "Unknown User";
		}

		public function getRegionName($regionID)
		{
			global $RUNTIME;
			
			$statementRegion = $RUNTIME['PDO']->prepare("SELECT * FROM regions WHERE uuid = ?");
			$statementRegion->execute(array($regionID));

			while($rowRegion = $statementRegion->fetch()) 
			{
				return $rowRegion['regionName'];
			}

			return "Unknown Region";
		}

		public function allowOfflineIM($userID)
		{
			global $RUNTIME;
			
			$statement = $RUNTIME['PDO']->prepare("SELECT * FROM usersettings WHERE useruuid = ?");
			$statement->execute(array($userID));

			while($row = $statement->fetch()) 
			{
				return strtoupper($row['imviaemail']);
			}

			return "FALSE";
		}

		public function getUserMail($userID)
		{
			global $RUNTIME;
			
			$statement = $RUNTIME['PDO']->prepare("SELECT * FROM UserAccounts WHERE PrincipalID = ?");
			$statement->execute(array($userID));

			while($row = $statement->fetch()) 
			{
				return $row['Email'];
			}

			return "";
		}

		public function getUserCount()
		{
			global $RUNTIME;
			
			$statementUser = $RUNTIME['PDO']->prepare("SELECT * FROM UserAccounts");
			$statementUser->execute();
			return $statementUser->rowCount();
		}

		public function getRegionCount()
		{
			global $RUNTIME;
			
			$statementUser = $RUNTIME['PDO']->prepare("SELECT * FROM regions");
			$statementUser->execute();
			return $statementUser->rowCount();
		}

		public function getOnlineCount()
		{
			global $RUNTIME;


			$statementUser = $RUNTIME['PDO']->prepare("SELECT * FROM Presence");
			$statementUser->execute();
			return $statementUser->rowCount();
		}
    }
?>