<?php
###############################################################################
# Import sub-domains from DNSMadeEasy
#
# Rename thirdparty/config-sample.php to config.php
# Edit it to include the API keys from DNSMadeEasy
# Run this from console to import the subdomains
#
# php dns-made-easy.php
#
###############################################################################

require_once(dirname(__FILE__) . "/../include.php");
require_once(dirname(__FILE__) . "/config.check.php");
require_once(dirname(__FILE__) . "/../lib/php/idn/idn.php");

###############################################################################
# Parse command line if running in CLI

if(is_cli())
	parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);

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

$startfrom = getNumericRequestVariable("s", 0);
$timeoffset = getNumericRequestVariable("to", 0);

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

loginIfRequired(true);

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

$pdo = init_db(false);
if($pdo !== false)
{
	if(!is_cli())
		echo "<pre>";
	$hostnames = array();
	$ddata = dnsmadeeasy_call("dns/managed/", 10);
	$records = get_dnsmadeeasy_data($ddata);
	$index = 0;
	foreach($records as $r) {
		$did = $r['id'];
		$domain = $r['name'];
		echo ($index+1) . "] " . $domain;
		if($index < $startfrom) {
			$index++;
			echo "... Ignoring\n";
			continue;
		}
		echo  "\n---\n";
		$types = array('CNAME', 'A', 'TXT');
		foreach($types as $type) {
			$dinfo = dnsmadeeasy_call("dns/managed/$did/records?type=$type", 10);
			$irecords = get_dnsmadeeasy_data($dinfo);
			foreach($irecords as $ir) {
				$name = $ir['name'];
				if($name != "") {
					if(!isset($hostnames[$domain])) {
						$hostnames[$domain] = array();
					}
					$hostnames[$domain][] = "{$name}.{$domain}";
					echo "{$name}.{$domain}\n";
					$sid = $pdo->getSingleEntry($pdo->getDomainTableName(), "domain", $domain, "sid");
					if($sid > 0) 
						$pdo->addSubdomain($sid, $name);
					else {
						$pdo->addDomain($domain, 0, $sid);
						if($sid > 0) {
							$pdo->logAuditEntry(AUDIT_ADD_DOMAINS, "Added domain '$domain'");
							$pdo->doDefaultDomainLookups($sid);
							$pdo->addSubdomain($sid, $name);
						}
					}
					if($sid > 0) {
						//$pdo->addToLookupQueue($sid, LOOKUP_IP_ADDRESS);
						$pdo->addToLookupQueue($sid, LOOKUP_SUB_DOMAINS);
					}
				}
			}
			echo "\n";
		}
		$index++;
	}
	$pdo->showLog();
}

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

function get_dnsmadeeasy_data($thedata)
{
	$records = array();
	if($thedata['status'] == 200) {
		$data = (array)json_decode($thedata['result']);
		if(isset($data['data'])) {
			foreach($data['data'] as $record) {
				$records[] = (array)$record;
			}
		}
	}
	else {
		if(isset($thedata['result']))
			echo $thedata['result'] . "\n";
		else
			print_r($thedata);
		exit;
	}
	return $records;
}

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

function request_headers($apikey, $secretkey)
{
	global $timeoffset;
	$requestDate = gmdate('r', time()+$timeoffset);
	return array(
		"x-dnsme-apiKey: $apikey",
		"x-dnsme-requestDate: $requestDate",
		"x-dnsme-hmac: " . hash_hmac('sha1', $requestDate, $secretkey),
		'Content-Type: application/json',
	);
}

###############################################################################
	
function dnsmadeeasy_call($operation, $timeout=10)
{
	global $dnsme_api_key, $dnsme_secret_key;
	
	$retv = array('result' => "", 'status' => 0);
	$url = "https://api.dnsmadeeasy.com/V2.0/" . $operation;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, request_headers($dnsme_api_key, $dnsme_secret_key));
	
	// reset the header values
	$apiResponse = curl_exec($ch);
	if (($errno = curl_errno($ch)) > 0) {
		echo curl_error($ch);
	}
	$ci = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	$retv['result'] = $apiResponse;
	$retv['result'] = ($retv['result'] === false) ? "" : $retv['result'];
	$retv['status'] = $ci;
	return $retv;
}

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