<?php
class PHPWhois {
	protected $domain,
						$tld,
						$server_list = array(),
						$server_charset = array();

	public function __construct($domain, $server_list_path, $server_charset_path) {
		$this -> domain = $domain;
		$this -> server_list = include_once $server_list_path;
		$this -> server_charset = include_once $server_charset_path;
		$this -> tld = $this -> getTld();
	}

	protected function getTld() {
		$domain_parts = explode(".", $this->domain);
		// domain level > 2 ?
		if(count($domain_parts) > 2) {
			$tld = implode(".", array_slice($domain_parts, -2));
			return isset($this->server_list[$tld]) ? $tld : array_pop($domain_parts);
		} else {
			return array_pop($domain_parts);
		}
	}

	protected function getWhoisServer() {
		return isset($this->server_list[$this->tld]) ? $this->server_list[$this->tld] : false;
	}

	public function query() {
		$output = "No whois server is known for this kind of object.\n";
		if(!$server = $this->getWhoisServer()) {
			return $output;
		}
		if(count($server) > 1) {
			$type = $server[1]; // ex: ARPA, NONE, WEB
			switch($type) {
				case "NONE":
					$output = "This TLD has no whois server.\n";
				break;
				case "WEB":
					$output = "This TLD has no whois server, but you can access the whois database at \n". $server[0]. "\n";
				break;
				case "ARPA":
				default;
				break;
			}
			return $output;
		} else {
			$res = $this->socketQuery($server[0], $this->domain);
			/*while(preg_match_all("/Whois Server: (.*)/", $res, $matches)) {
				$server = array_pop($matches[1]);
				$res = $this->socketQuery($server, $this->domain);
			}*/
			return isset($this->server_charset[$server[0]]) ? @iconv($this->server_charset[$server[0]], "utf-8//IGNORE", $res) : $res;
		}
	}

	protected function socketQuery($server, $domain) {
		$fp = @fsockopen($server, 43, $errno, $errstr, 20);
		if(!$fp) {
			return false;
		}
		fputs($fp, $domain . "\r\n");
		$out = "";
		while(!feof($fp)){
			$out .= fgets($fp);
		}
		fclose($fp);
		return $out;
	}
}