<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

use Iodev\Whois\Factory;
use Iodev\Whois\Exceptions\ConnectionException;
use Iodev\Whois\Exceptions\ServerMismatchException;
use Iodev\Whois\Exceptions\WhoisException;
use Iodev\Whois\Loaders\SocketLoader;
use Iodev\Whois\Loaders\MemcachedLoader;

$json = [];
$domain = $VARS["domain"];
if (empty($VARS["nocache"])) {
    $cacheresp = $memcache->get("net.whois.$domain");
    if ($cacheresp !== false) {
        exitWithJson(json_decode($cacheresp, true));
    }
}
try {
    if ($memcache->enabled() && empty($VARS["nocache"])) {
        $loader = new MemcachedLoader(new SocketLoader(), $memcache->getMemcached(), $memcache->getPrefix());
        $whois = Factory::get()->createWhois($loader);
    } else {
        $whois = Factory::get()->createWhois();
    }
    $info = $whois->loadDomainInfo($domain);
    $response = $whois->lookupDomain($domain);
    if (!$info) {
        $json = [
            "domain" => $domain,
            "registered" => false
        ];
    } else {
        $json = [
            "domain" => $info->domainName,
            "registered" => true,
            "created" => $info->creationDate,
            "expires" => $info->expirationDate,
            "updated" => $info->updatedDate,
            "registrar" => $info->registrar,
            "owner" => $info->owner,
            "nameservers" => $info->nameServers,
            "raw" => $response->text
        ];
    }
    $json["status"] = "OK";
    $memcache->set("net.whois.$domain", json_encode($json), 60 * 60 * 4);
    exitWithJson($json);
} catch (ConnectionException $e) {
    sendJsonResp("Disconnect or connection timeout", "ERROR");
} catch (ServerMismatchException $e) {
    sendJsonResp("TLD server not found in current server hosts", "ERROR");
} catch (WhoisException $e) {
    sendJsonResp("Whois server responded with error '{$e->getMessage()}'", "ERROR");
} catch (Exception $e) {
    Logger::log("network.whois error: " . $e->getMessage());
    sendJsonResp("An unknown error occurred.", "ERROR");
    \Sentry\captureException($ex);
}