<?php

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

namespace CodePunch\LU\Registrars;

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

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

class NameSilo extends RegistrarAPI {
	
	private $api_url_base  		= 'https://www.namesilo.com/api/';
	private $api_access_key		= null;
	private $contact_info 		= array();
	
	###########################################################################
	
	public function __construct($cm, $apikey)
	{ 
		parent::__construct($cm);
		if(UTIL::starts_with($apikey, "sandbox::")) {
			$apikey = substr($apikey, 9);
			$this->use_sandbox(true);
		}
		$this->api_access_key = $apikey;
	}
	
	###########################################################################
	
	public static function getKeyNames()
	{
		return array('API Key');
	}
	
	###########################################################################
	
	public function supported() {
		return array('domainlist', 'whois');
	}
	
	###########################################################################
	
	public function use_sandbox($flag)
	{
		if($flag === true)
			$this->api_url_base = 'https://sandbox.namesilo.com/api/';
		else
			$this->api_url_base = 'https://www.namesilo.com/api/';
		return true;
	}
	
	###########################################################################
	
	private function construct_url($operation, $extraparams)
	{
		$url = $this->api_url_base . "$operation?version=1&type=xml&key=" . $this->api_access_key;
		if($extraparams != "")
			$url .= "&{$extraparams}";
		return $url;
	}
	
	
	###########################################################################
	
	private function cleanup_keys(&$info)
	{
		$xlate = array(
		'created'=>'Creation Date',
		'expires'=>'Expiry Date',
		'auto_renew'=>'Auto Renew',
		'detail'=>'Detail',
		'locked'=>'Locked',
		'email_verification_required'=>'Email Verification Required',
		'status'=>'Status',
		'traffic_type'=>'Traffic Type',
		'private'=>'Private',
		'portfolio'=>'Portfolio',
		'forward_url'=>'Forward URL',
		'forward_type'=>'Forward Type',
		'nameserversnameserver0' => 'Name Server 0',
		'nameserversnameserver1' => 'Name Server 1',
		'nameserversnameserver2' => 'Name Server 2',
		'nameserversnameserver3' => 'Name Server 3',
		'nameserversnameserver4' => 'Name Server 4',
		'nameserversnameserver5' => 'Name Server 5',
		'nameserversnameserver6' => 'Name Server 6',
		'nameserversnameserver7' => 'Name Server 7',
		'nameserversnameserver8' => 'Name Server 8',
		);
		UTIL::array_xlate_keys($info, $xlate);
	}
	
	###########################################################################
	
	public function getContactInfo($contacttype, $contactid)
	{
		$contacttype = str_ireplace("Administrative", "Admin", $contacttype);
		$contacttype = str_ireplace("Technical", "Tech", $contacttype);
		
		if(isset($this->contact_info[$contactid])) {
			$cinfo = $this->contact_info[$contactid];
			$cinfo = UTIL::array_flatten($cinfo, ucfirst($contacttype), " ");
			$this->cleanup_keys($cinfo);
			$cinfo = UTIL::array_to_text($cinfo);
		}
		else {
			$url = $this->construct_url("contactList", "contact_id={$contactid}");
			$udata = UTIL::curl_get_url($url, 10);
			// curl_get_url will always return an array
			$cinfo = $udata['result'];
			if($cinfo != "") {
				$cinfo = simplexml_load_string($cinfo);
				$cinfo = json_decode(json_encode($cinfo), TRUE);
				if(isset($cinfo['reply']['detail'])) {
					if($cinfo['reply']['detail'] == "success") {
						if(isset($cinfo['reply']['contact'])) {
							$cinfo = $cinfo['reply']['contact'];
							if(is_array($cinfo)) {
								$cc = array();
								foreach($cinfo as $k=>$v) {
									$k = str_replace("_", " ", $k);
									$k = ucwords($k);
									$cc[$k] = $v;
								}
								$cinfo = $cc;
							}
							$this->contact_info[$contactid] = $cinfo;
							$cinfo = UTIL::array_flatten($cinfo, ucfirst($contacttype), " ");
							$this->cleanup_keys($cinfo);
							$cinfo = UTIL::array_to_text($cinfo);
						}
					}
				}
			}
		}
		return $cinfo;
	}
	
	###########################################################################
	
	public function whois($domain)
	{
		$responce = array('status'=>false,'error'=>'','data'=>'');
		try
		{
			$url = $this->construct_url("getDomainInfo", "domain={$domain}");
			$udata = UTIL::curl_get_url($url, 10);
			// curl_get_url will always return an array
			$whois = $udata['result'];
			if($whois != "") {
				$whoisdata = simplexml_load_string($whois);
				$whoisdata = json_decode(json_encode($whoisdata), TRUE);
				if($whoisdata !== false) {
					$contactinfo = "";
					if(isset($whoisdata['reply']['contact_ids'])) {
						$contactids = $whoisdata['reply']['contact_ids'];
						unset($whoisdata['reply']['contact_ids']);
						foreach($contactids as $contacttype=>$contactid) {
							$contactinfo .= $this->getContactInfo($contacttype, $contactid);
							$contactinfo .= "\n";
						}
					}
					if(isset($whoisdata['reply'])) {
						$whoisdata = $whoisdata['reply'];
						$whoisdata = UTIL::array_flatten($whoisdata);
						$whoisdata['Registrar'] = "NameSilo";
						$whoisdata['Domain'] = $domain;
						$this->cleanup_keys($whoisdata);
						$whoisdata = UTIL::array_to_text($whoisdata);
						$whoisdata .= "\n" . $contactinfo;
					}
					$responce['data'] = $whoisdata;
					$responce['status'] = true;
				}
			}
			else
				throw new Exception("Unable to connect to NameSilo API server");
		}
		catch (Exception $e) {
			$responce['error'] = $e->getMessage();
		}
		return $responce;
	}
	
	###########################################################################

	public function isWorking()
	{
		$url = $this->construct_url("contactList", "");
		$info = UTIL::curl_get_url($url, 10);
		if(isset($info['status']) && $info['status'] == 200) {
			if($info['result'] != "") {
				$info = $info['result'];
				$info = simplexml_load_string($info);
				$dinfo = json_decode(json_encode($info), TRUE);
				if(isset($dinfo['reply']['code']) && $dinfo['reply']['code'] == 300)
					return true;
				if(isset($dinfo['reply']['detail']))
					return $dinfo['reply']['detail'];
			}
		}
		return "Unable to connect";
	}

	###########################################################################
	
	public function domainlist(?callable $callback=null)
	{
		$domains = array();
		while(1) {
			$thisdata = array();
			$url = $this->construct_url("listDomains", "");
			$info = UTIL::curl_get_url($url, 10);
			if($info['result'] != "")
			{
				$info = $info['result'];
				$info = simplexml_load_string($info);
				$domaininfo = json_decode(json_encode($info), TRUE);
				if(isset($domaininfo['reply']['detail'])) {
					if($domaininfo['reply']['detail'] == "success") {
						if(isset($domaininfo['reply']['domains']['domain']) == "success") {
							if(is_array($domaininfo['reply']['domains']['domain']))
								$thisdata = $domaininfo['reply']['domains']['domain'];
							else
								$thisdata[] = $domaininfo['reply']['domains']['domain'];
						}
					}
				}
			}
			else 
				throw new Exception("Unable to connect to NameSilo API server");

			if($callback != null && count($thisdata)) {
				$status = call_user_func($callback, "", count($domains), $thisdata);
				if($status == self::REGAPI_STOP)
					break;
			}
			if(count($thisdata))
				$domains = array_merge($domains, $thisdata);
			
			break;
		}

		return $domains;
	}
}

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

?>