<?php

###############################################################################
# internetbs.php
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace CodePunch\LU\Registrars;

use Exception;
use CodePunch\Base\Util as UTIL;

###############################################################################

class InternetBS extends RegistrarAPI {
	
	private $api_url_base  		= 'https://api.internet.bs/';
	private $api_access_key		= null;
	private $api_password		= null;
	
	###########################################################################
	
	public function __construct($cm, $apikey, $password)
	{ 
		parent::__construct($cm);
		if(UTIL::starts_with($apikey, "sandbox::")) {
			$apikey = substr($apikey, 9);
			$this->use_sandbox(true);
		}
		$this->api_access_key = $apikey;
		$this->api_password = $password;
	}
	
	###########################################################################
	
	public static function getKeyNames()
	{
		return array('API Key', 'API Password');
	}
	
	###########################################################################
	
	public function supported() {
		return array('domainlist', 'whois');
	}
	
	###########################################################################
	
	public function use_sandbox($flag)
	{
		if($flag === true)
			$this->api_url_base = 'https://testapi.internet.bs/';
		else
			$this->api_url_base = 'https://api.internet.bs/';
		return true;
	}
	
	###########################################################################
	
	private function construct_url($command, $extraparams)
	{
		return $this->api_url_base . "$command/?apiKey={$this->api_access_key}&password={$this->api_password}&{$extraparams}";
	}
	
	###########################################################################
	
	private function cleanup_keys(&$info)
	{
		$xlate = array(
		'status' => 'Status',
		'domain' => 'Domain',
		'expirationdate' => 'Expiry Date',
		'registrarlock' => 'Registrar Lock',
		'autorenew' => 'Auto Renew',
		'privatewhois' => 'Private Whois',
		'domainstatus' => 'REGISTRAR LOCKED',
		'contacts_registrant_firstname' => 'Registrant First Name',
		'contacts_registrant_lastname' => 'Registrant Last Name',
		'contacts_registrant_email' => 'Registrant Email',
		'contacts_registrant_phonenumber' => 'Registrant Phone',
		'contacts_registrant_organization' => 'Registrant Organization',
		'contacts_registrant_city' => 'Registrant City',
		'contacts_registrant_state' => 'Registrant State',
		'contacts_registrant_street' => 'Registrant Street',
		'contacts_registrant_street2' => 'Registrant Street2',
		'contacts_registrant_street3' => 'Registrant Street3',
		'contacts_registrant_postalcode' => 'Registrant ZIP',
		'contacts_registrant_countrycode' => 'Registrant Country Code',
		'contacts_registrant_country' => 'Registrant Country',
		'contacts_technical_firstname' => 'Tech First Name',
		'contacts_technical_lastname' => 'Tech Last Name',
		'contacts_technical_email' => 'Tech Email',
		'contacts_technical_phonenumber' => 'Tech Phone',
		'contacts_technical_organization' => 'Tech Organization',
		'contacts_technical_city' => 'Tech City',
		'contacts_technical_state' => 'Tech State',
		'contacts_technical_street' => 'Tech Street',
		'contacts_technical_street2' => 'Tech Street2',
		'contacts_technical_street3' => 'Tech Street3',
		'contacts_technical_postalcode' => 'tech ZIP',
		'contacts_technical_countrycode' => 'Tech Country Code',
		'contacts_technical_country' => 'Tech Country',
		'contacts_admin_firstname' => 'Admin First Name',
		'contacts_admin_lastname' => 'Admin Last Name',
		'contacts_admin_email' => 'Admin Email',
		'contacts_admin_phonenumber' => 'Admin Phone',
		'contacts_admin_organization' => 'Admin Organization',
		'contacts_admin_city' => 'Admin City',
		'contacts_admin_state' => 'Admin State',
		'contacts_admin_street' => 'Admin Street',
		'contacts_admin_street2' => 'Admin Street2',
		'contacts_admin_street3' => 'Admin Street3',
		'contacts_admin_postalcode' => 'Admin ZIP',
		'contacts_admin_countrycode' => 'Admin Country Code',
		'contacts_admin_country' => 'Admin Country',
		'contacts_billing_firstname' => 'Billing First Name',
		'contacts_billing_lastname' => 'Billing Last Name',
		'contacts_billing_email' => 'Billing Email',
		'contacts_billing_phonenumber' => 'Billing Phone',
		'contacts_billing_organization' => 'Billing Organization',
		'contacts_billing_city' => 'Billing City',
		'contacts_billing_state' => 'Billing State',
		'contacts_billing_street' => 'Billing Street',
		'contacts_billing_street2' => 'Billing Street2',
		'contacts_billing_street3' => 'Billing Street3',
		'contacts_billing_postalcode' => 'Billing ZIP',
		'contacts_billing_countrycode' => 'Billing Country Code',
		'contacts_billing_country' => 'Billing Country',
		'dnssec' => 'DNSSEC',
		'price_ispremium' => 'Premium Price'
		);
		UTIL::array_xlate_keys($info, $xlate);
	}
	
	###########################################################################
	
	public function whois($domain)
	{
		$responce = array('status'=>false,'error'=>'','data'=>'');
		try
		{
			$url = $this->construct_url("Domain/Info", "Domain={$domain}");
			$udata = UTIL::curl_get_url($url, 10);
			// curl_get_url will always return an array
			$whois = $udata['result'];
			if($whois != "") {
				$parts = explode("\n", $whois);
				$whois = array();
				foreach($parts as $p) {
					$info = explode("=", $p);
					if(count($info) == 2) {
						if($info[0] == 'transferauthinfo')
							$info[1] = "******";
						$whois[$info[0]] = $info[1];
					}
				}
				unset($whois['transactid']);
				self::cleanup_keys($whois);
				$whoisdata = UTIL::array_to_text($whois);
				$responce['data'] = $whoisdata;
				$responce['status'] = true;
			}
			else
				throw new Exception("Unable to connect to Internet.BS API server");
		}
		catch (Exception $e) {
			$responce['error'] = $e->getMessage();
		}
		return $responce;
	}
	
	###########################################################################

	public function isWorking()
	{
		$url = $this->construct_url("Domain/Check", "Domain=example.com");
		$info = UTIL::curl_get_url($url, 10);
		if(isset($info['status']) && $info['status'] == 200) {
			if($info['result'] != "") {
				$info = $info['result'];
				if(stristr($info, "status=FAILURE") !== false)
					return UTIL::get_string_between($info . "\n", "message=", "\n");
				else if(stristr($info, "status=UNAVAILABLE") !== false)
					return true;
			}
		}
		return "Unable to connect";
	}

	###########################################################################
	
	public function domainlist(?callable $callback=null)
	{
		$url = $this->construct_url("Domain/Count", "");
		$info = UTIL::curl_get_url($url, 10);
		if($info['result'] != "") 
			$domaincount = UTIL::get_string_between($info['result'] . "\n", "totaldomains=", "\n");

		$domains = array();
		$rangeFrom = 0;
		$count = 1000;
		while(1) {
			$thisdata = array();
			$rangeTo = $rangeFrom + $count;
			$url = $this->construct_url("Domain/List", "&rangeFrom={$rangeFrom}&rangeTo={$rangeTo}&CompactList=yes");
			$info = UTIL::curl_get_url($url, 10);
			if($info['result'] != "") {
				$info = $info['result'];
				$parts = explode("\n", $info);
				$failed = false;
				$message = "";
				foreach($parts as $p) {
					$info = explode("=", $p);
					if(count($info) == 2) {
						if($info[0] == "status" && $info[1] == "FAILURE") 
							$failed = true;
						if($info[0] == "message") 
							$message = $info[1];
						if(UTIL::starts_with($info[0], "domain_")) 
							$thisdata[] = $info[1];		
					}
				}
				if($failed) 
					throw new Exception($message);
			}
			else 
				throw new Exception("Unable to connect to InternetBS API server");
			
			if(!count($thisdata))
				break;
			$rangeFrom += count($thisdata);
			
			if($callback != null) {
				$status = call_user_func($callback, "", count($domains), $thisdata);
				if($status == self::REGAPI_STOP)
					break;
			}
			if(count($thisdata))
				$domains = array_merge($domains, $thisdata);
		}
		return $domains;
	}
}

###############################################################################

?>