#!/usr/bin/php
<?php
/***************************************************************\
*                /servers & /goto mod By: Durf                  *
*              http://durf.tk   0.durf.0@gmail.com              *
*      Modified to be compatible with Light's list by Nelg      *
*        https://armanelgtron.tk/  armanelgtron@gmail.com       *
* Notes:                                                        *
* - set $server_name in script on line 14                       *
* - set custom access levels for the /set and /sendto commands  *
\***************************************************************/

/**///start servers & goto prep
$server_name = "";//your SERVER_NAME from your cfg (this is optional / for a bug fix [could connect to the same server you were in])
$ACCESS_LEVEL_SENDTO = 5;//minimal access level required to use the /sendto and /deport command (moderators)
if(!defined("STDERR")) define("STDERR",fopen("php://stderr","a"));
function filterOutColorCodes($text_to_filter) 
{ 
	$filtered_text = preg_replace("/0x(\w){6}/i", "", $text_to_filter); 
	return $filtered_text; 
}
if(!function_exists("utf8_decode"))
{
	if(function_exists("iconv"))
	{
		function utf8_decode($txt)
		{
			return iconv("UTF-8","ISO-8859-1",$txt);
		}
	}
	elseif(function_exists("mb_convert_encoding"))
	{
		function utf8_decode($txt)
		{
			return mb_convert_encoding($txt,"ISO-8859-1","UTF-8");
		}
	}
	else
	{
		print("CONSOLE_MESSAGE WARNING: There is no method to convert from utf8. Text may look garbled on your terminal.\n");
		function utf8_decode($txt)
		{
			fwrite(STDERR,"Warning: Can't convert from utf8.");
			return $txt;
		}
	}
}
$utf8 = isset($argv[1])&&($argv[1]=="-utf8");
function handle_encoding($str)
{
	global $utf8;
	if($utf8)
	{
		return $str;
	}
	return utf8_decode($str);
}
$lasttime=0;
/**///end of servers & goto prep
While(!feof(STDIN))
{
  $line = rtrim(fgets(STDIN));
  $split = explode(" ",$line);
  if($split[0] == "INVALID_COMMAND" || $split[0] == "COMMAND")
  {
	//below are keyword / easy to use variables for all custom command use
	//cmd = the command they entered with slash; user = the player name or global ID; access = the user's current access level	
	//below are custom parameter setup
	//$params[0] = first parameter; params[1] = second parameter for custom commands
	switch($split[0])
	{
		case "INVALID_COMMAND":
			$cmd = $split[1]; $user = $split[2]; $access = $split[4]; 
			$params = array(); $numparams = count($split); for ($var = 5; $var < $numparams; $var++) { array_push($params, $split[$var]); }
			break;
		case "COMMAND": //fix for 0.4 and 0.2.8.3.*
			$cmd = $split[1]; $user = $split[2];
			$params = array(); $numparams = count($split); for ($var = 3; $var < $numparams; $var++) { array_push($params, $split[$var]); }
			break;
	}
	//below is a bug fix for special cases
	if (preg_match("/^\d(\d)?$/", $user)) 
	{ 
		$cmd = "NUMBERHACK";
	}
	$user = str_replace("\"","\\\"",str_replace("'","\'",$user));
	//if the username is made up of solely 1 or 2 numbers (such as 6 or 13), 
	//force their custom command to be called number hack
	//this prevents people from executing script commands as a user ID that isn't theirs
	// /goto server name (which if it tried to send user "6" it would send the user with user ID 6 on the server, not the person who's name is "6")
	if($cmd == "/test") 
	{//default custom command
		echo "PLAYER_MESSAGE {$user} \"0xccccccScript Working! 0x808080({$user})\"\n";
	}
	/* servers & goto commands */
	elseif($cmd == "/servers" || $cmd == "/srvrs" || $cmd == "/svrs" || $cmd == "/online" || $cmd == "/srvr" || $cmd == "/svr") 
	{
		if(time() >= $lasttime+60) //don't refetch if you don't have to
		{
			echo "PLAYER_MESSAGE {$user} \"0xccccccRetrieving populated servers...\"\n";
			$servers = json_decode(file_get_contents("https://lightron.org/BrowserFeed"),true);
		}
		$serversmessage = "0xccccccActive servers:\\n";
		if($servers) 
		{ 
			foreach($servers as $p=>$server) 
			{
				if($p == 0)
				{
					$num = $server["servers_active"];
					$lasttime = $server["time"];
				}
				elseif($server['num_players'] != "0")
				{ 
					$serversmessage .= handle_encoding($server['server_name'])." 0xffffff- ";
					if($server['num_players'] == $server['max_players']) 
					{
						$serversmessage .= "(0xcc0000{$server['num_players']}0xffffff/0xdd4444{$server['max_players']}0xffffff)\\n";
					}
					else 
					{ 
						$serversmessage .= "(0x00cc00{$server['num_players']}0xffffff/0x44dd44{$server['max_players']}0xffffff)\\n"; 
					} 
					$playerslist=""; 
					foreach($server['players'] as $player) 
					{ 
						if(trim(filterOutColorCodes($player)) == null) //<-- should be fixed
						{ 
							$playerslist.="{specialchars}, "; 
						} 
						else 
						{ 
							$playerslist.=handle_encoding($player).", "; 
						} 
					} 
					$serversmessage = $serversmessage . "0x808080-> 0xffffff".preg_replace("/,\s$/", "", $playerslist)."\\n"; 
				} 
			}
			echo "PLAYER_MESSAGE {$user} \"".str_replace("\"","\\\"",$serversmessage)."0xffffff{$num} 0x808080servers listed.\"\n";
		}
		else 
		{ 
			echo "PLAYER_MESSAGE {$user} \"0xcc0000Could not retrieve listing at this time! 0x808080Try again later.\"\n"; 
		}
	}
	elseif($cmd == "/goto" || $cmd == "/go2" || $cmd == "/go" || $cmd == "/leave") 
	{
		if(!isset($params[0]) || $params[0] == "")
		{ 
			echo "PLAYER_MESSAGE {$user} \"0xcccc00No server specified! 0xcccccc/goto \"\n"; 
		}
		else 
		{ 
			$searchterms = count($params); $search = "";
			for($z = 0; $z < $searchterms; $z++)
			{ 
				$search = $search."(".$params[$z].").*"; 
			}
			$search2 = preg_replace("/(\.\*)$/", "", $search);
			$num = 0;
			$gotoname = array();$found = array(); $info = array();
			if(time() >= $lasttime+60) //don't refetch if you don't have to
			{
				echo "PLAYER_MESSAGE {$user} \"0xccccccRetrieving populated servers...\"\n";
				$servers = json_decode((file_get_contents("https://lightron.org/BrowserFeed")),true);
			}
			foreach ($servers as $server) { $cleanname = preg_replace('/0x\w{6}/', "", $server['server_name']); if (preg_match("/$search2/i", $cleanname)) { array_push($found, $server['host'].":".$server['port']." You are now being moved to ".$server['server_name']."0xffffff. Hit 0x00cc00ENTER 0xffffffto continue, or 0xcc0000ESC 0xffffffto cancel."); array_push($info, $server['server_name']." 0xffffff(".$server['num_players']."/".$server['max_players'].")"); array_push($gotoname, $server['server_name']); $num++; } }
			if($num > 1 && $num < 11) { echo "PLAYER_MESSAGE {$user} \"0xcccccc{$num} 0xcccc00matches found! Be more specific. Here's what you got:\"\n"; $numserversfound = count($info); for ($y = 0; $y < $numserversfound; $y++) { echo "PLAYER_MESSAGE {$user} \"{$info[$y]}\"\n"; } }
			elseif($num > 10) 
			{ 
				echo "PLAYER_MESSAGE {$user} \"0xcc0000Too many matches!\"\n"; 
			}//too many matches
			elseif($num < 1) 
			{
				echo "PLAYER_MESSAGE {$user} \"0xcc0000No servers found!\"\n";
			}//no matches
			else
			{ 
				if(filterOutColorCodes($gotoname[0]) == $server_name)
				{ 
					echo "PLAYER_MESSAGE {$user} \"0xcccc00You are already on 0xffffff".$gotoname[0]."\"\n"; } else { echo "PLAYER_MESSAGE {$user} \"0x00cc00Found server! Moving you to 0xffffff".$gotoname[0]."\"\n"; usleep(500000); echo "MOVE_TO {$user} ".$found[0]."\n"; echo "CONSOLE_MESSAGE 0xffffff{$user} 0xccccccleft to go to 0xffffff{$gotoname[0]}\n"; 
				} 
			}
		}//end of has setting
	}//end of /goto
	elseif($cmd == "/gosee" || $cmd == "/goc" || $cmd == "/visit" || $cmd == "/friend") 
	{
		if(!isset($params[0]) || $params[0] == "") 
		{ 
			echo "PLAYER_MESSAGE {$user} \"0xcccc00No user specified! 0xcccccc/gosee \"\n"; 
		}
		else
		{
			$searchterms = count($params); $target = implode(" ", $params); $target_text = ""; $search = "";
			for($z = 0; $z < $searchterms; $z++)
			{ 
				$search = $search."(".$params[$z].").*"; 
			}
			$search2 = preg_replace("/(\.\*)$/", "", $search); 
			$num = 0; 
			$gotoname = array(); $found = array(); $info = array(); 
			if(time() >= $lasttime+60) //don't refetch if you don't have to
			{
				echo "PLAYER_MESSAGE {$user} \"0xccccccRetrieving populated servers...\"\n";
				$servers = json_decode((file_get_contents("https://lightron.org/BrowserFeed")),true);
			}
			foreach($servers as $server) 
			{ 
				$foundperson = false;
				foreach($server['players'] as $player) 
				{ 
					$cleanname = $player;
					if(preg_match("/$search2/i", $cleanname)) 
					{ 
						$foundperson = true; 
						$target_text = $cleanname; 
					} 
				} 
				if($foundperson === true) 
				{ 
				array_push($found, $server['host'].":".$server['port']." You are now being moved to ".$server['server_name']."0xffffff. Hit 0x00cc00ENTER 0xffffffto continue, or 0xcc0000ESC 0xffffffto cancel."); array_push($info, $server['server_name']." 0xffffff(".$server['num_players']."/".$server['max_players'].")"); array_push($gotoname, $server['server_name']); $num++; 
				} 
			}
			if($num > 1 && $num < 11)
			{
				echo "PLAYER_MESSAGE {$user} \"0xcccccc{$num} 0xcccc00matches found for 0xffffff{$target}0xcccc00! Be more specific. Here's the servers:\"\n"; 
				$numserversfound = count($info);
				for($y = 0; $y < $numserversfound; $y++) 
				{ 
				echo "PLAYER_MESSAGE {$user} \"{$info[$y]}\"\n"; 
				} 
			}
			elseif($num > 10)
			{ 
				echo "PLAYER_MESSAGE {$user} \"0xcc0000Too many matches for 0xffffff{$target}0xcc0000!\"\n"; 
			}//no matches
			elseif($num < 1)
			{ 
				echo "PLAYER_MESSAGE {$user} \"0xcc0000No matches found! 0xccccccMaybe 0xffffff{$target} 0xccccccisn't online..\"\n"; 
			}//no matches
			else 
			{ 
				if(filterOutColorCodes($gotoname[0]) == $server_name) 
				{ 
					echo "PLAYER_MESSAGE {$user} \"0xcccc00You are already on 0xffffff".$gotoname[0]." 0xcccc00with 0xffffff{$target}\"\n"; 
				} 
				else 
				{ 
					echo "PLAYER_MESSAGE {$user} \"0x00cc00Found 0xffffff{$target}0x00cc00! Moving you to 0xffffff".$gotoname[0]." 0x00cc00to go see 0xffffff{$target}\"\n";
					usleep(500000);
					echo "MOVE_TO {$user} ".$found[0]."\n";
					echo "CONSOLE_MESSAGE 0xffffff{$user} 0xccccccwent to go see 0xffffff{$target_text} 0xccccccat 0xffffff{$gotoname[0]}\n"; 
				} 
			}
		}//end of has setting
	}//end of /gosee


		elseif ($cmd == "/sendto" || $cmd == "/send2" || $cmd == "/send")
		{
			if (((int) $split[4]) <= $ACCESS_LEVEL_SENDTO ) {//is admin(mod) or higher
			if (!isset($params[0]) || $params[0] == "") { echo "PLAYER_MESSAGE {$user} \"0xcccc00No user specified! 0xcccccc/sendto  \"\n"; }
			else { $searchterms = count($split); $search = "";
				for ($z = 6; $z < $searchterms; $z++) { $search = $search."(".$split[$z].").*"; }
				$search2 = preg_replace("/(\.\*)$/", "", $search); $num = 0; $gotoname = array(); $found = array(); $info = array(); if(time() >= $lasttime+60) //don't refetch if you don't have to
				{
					echo "PLAYER_MESSAGE {$user} \"0xccccccRetrieving populated servers...\"\n";
					$servers = json_decode((file_get_contents("https://lightron.org/BrowserFeed")),true);
				}
				foreach ($servers as $server) { $cleanname = preg_replace('/0x\w{6}/', "", $server['server_name']); if (preg_match("/$search2/i", $cleanname)) { array_push($found, $server['host'].":".$server['port']." You are now being moved to ".$server['server_name']."0xffffff. Hit 0x00cc00ENTER 0xffffffto continue, or 0xcc0000ESC 0xffffffto cancel."); array_push($info, $server['server_name']." 0xffffff(".$server['num_players']."/".$server['max_players'].")"); array_push($gotoname, $server['server_name']); $num++; } }//for servers
				if ($num > 1 && $num < 11) { echo "PLAYER_MESSAGE {$user} \"0xcccccc{$num} 0xcccc00matches found! Be more specific. Here's what you got:\"\n"; $numserversfound = count($info); for ($y = 0; $y < $numserversfound; $y++) { echo "PLAYER_MESSAGE {$user} \"{$info[$y]}\"\n"; } }
				else if ($num > 10) { echo "PLAYER_MESSAGE {$user} \"0xcc0000Too many matches!\"\n"; }//no matches
				else if ($num < 1) { echo "PLAYER_MESSAGE {$user} \"0xcc0000No servers found!\"\n"; }//no matches
				else { if ( filterOutColorCodes($gotoname[0]) == $server_name ) { echo "PLAYER_MESSAGE {$user} \"0xcccc00Can't send to 0xffffff".$gotoname[0]."0xcccc00. Already there!\"\n"; } else { echo "PLAYER_MESSAGE {$user} \"0x00cc00Found server! Moving 0xffffff{$params[0]} 0x00cc00to 0xffffff".$gotoname[0]."\"\n"; usleep(500000); echo "MOVE_TO {$params[0]} ".$found[0]."\n"; echo "PLAYER_MESSAGE {$user} \"{$params[0]} was sent to {$gotoname[0]}0xffffff. If they are still here, it's because your attempt matched too many users, or none.\"\n"; } }
			}
		}//end of admin action
		else { echo "PLAYER_MESSAGE {$user} \"0xcc0000You're not authorized for that!\"\n"; }
		}//end of /sendto

		else if ($cmd == "/deport" || $cmd == "/dport" || $cmd == "/xport" || $cmd == "/export") {
		$target = $params[0];
		if (((int) $split[4]) <= $ACCESS_LEVEL_SENDTO ) {//is admin(mod) or higher
		if (!isset($params[0]) || $params[0] == "") { echo "PLAYER_MESSAGE {$user} \"0xcccc00No user specified! 0xcccccc/deport  \"\n"; }
		else { $searchterms = count($split); $search = ""; $search_text = ""; $target_text = "";
			for ($z = 6; $z < $searchterms; $z++) { $search = $search."(".$split[$z].").*"; if ($search_text === "") { $search_text = $split[$z]; } else { $search_text = $search_text." ".$split[$z]; } }
			$search2 = preg_replace("/(\.\*)$/", "", $search); $num = 0; $gotoname = array(); $found = array(); $info = array();
			if(time() >= $lasttime+60) //don't refetch if you don't have to
			{
				echo "PLAYER_MESSAGE {$user} \"0xccccccRetrieving populated servers...\"\n";
				$servers = json_decode((file_get_contents("https://lightron.org/BrowserFeed")),true);
			}
			foreach ($servers as $server) { $foundperson = false; foreach($server['players'] as $player) { $cleanname = $player; if (preg_match("/$search2/i", $cleanname)) { $foundperson = true; if ($target_text === "") { $target_text = $cleanname; } else { $target_text = $target_text.", ".$cleanname; } } } if ($foundperson === true) { array_push($found, $server['host'].":".$server['port']." You are now being moved to ".$server['server_name']."0xffffff. Hit 0x00cc00ENTER 0xffffffto continue, or 0xcc0000ESC 0xffffffto cancel."); array_push($info, $server['server_name']." 0xffffff(".$server['num_players']."/".$server['max_players'].") matches: {$target_text}"); array_push($gotoname, $server['server_name']); $num++; } }//for servers
			if ($num > 1 && $num < 11) { echo "PLAYER_MESSAGE {$user} \"0xcccccc{$num} 0xcccc00matches found for 0xffffff{$search_text}0xcccc00! Be more specific. Here's the servers:\"\n"; $numserversfound = count($info); for ($y = 0; $y < $numserversfound; $y++) { echo "PLAYER_MESSAGE {$user} \"{$info[$y]}\"\n"; } }
			else if ($num > 10) { echo "PLAYER_MESSAGE {$user} \"0xcc0000Too many matches for 0xffffff{$search_text}0xcc0000!\"\n"; echo "PLAYER_MESSAGE {$user} \"0xccccccYou matched: 0xffffff{$target_text}\"\n"; }//no matches
			else if ($num < 1) { echo "PLAYER_MESSAGE {$user} \"0xcc0000No matches found! 0xccccccMaybe 0xffffff{$search_text} 0xccccccisn't online..\"\n"; }//no matches
			else { if ( filterOutColorCodes($gotoname[0]) == $server_name ) { echo "PLAYER_MESSAGE {$user} \"0xcccc00You are already on 0xffffff".$gotoname[0]." 0xcccc00with 0xffffff{$target_text}\"\n"; } else { echo "PLAYER_MESSAGE {$user} \"0x00cc00Found 0xffffff{$target_text}0x00cc00! Moving you to 0xffffff".$gotoname[0]." 0x00cc00to go see 0xffffff{$target}\"\n"; usleep(500000); echo "MOVE_TO {$user} ".$found[0]."\n"; echo "PLAYER_MESSAGE \"0xccccccSending 0xffffff{$target} 0xccccccto go see 0xffffff{$target_text} 0xccccccat 0xffffff{$gotoname[0]}\"\n"; } }
		}
		}//end of admin action
		else { echo "PLAYER_MESSAGE {$user} \"0xcc0000You're not authorized for that!\"\n"; }
		}//end of /deport
		/* end of servers & goto */

		elseif($cmd == "NUMBERHACK") 
		{//consequence for having a 1 or 2 digit name and using a custom command
			echo "PLAYER_MESSAGE {$user} \"0xcc0000You are not permitted to use script commands until you 0xccccccchange your name0xcc0000.\"\n";
		}
		else {//non-specific custom command attempt (default fall-back)
			echo "PLAYER_MESSAGE {$user} \"Unknown chat command \\\"{$cmd}\\\".\"\n";
		}
	}
}
?>