<?php
/**
 * Helper script to check the availibility of a Kerio mailbox useable with ajax requests
 * 
 * @see https://www.kerio.com
 * @copyright Copyright (c) Thurdata GmbH 2020
 * @license GPL
 * 
 */


$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false) {
    die('Restricted access');
}

/**
 * Requires the whmcs init
 * Requires this PHP api to make soap calls and parse responses
 */
require_once(__DIR__ . '/../../../init.php');
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;
use WHMCS\Database\Capsule;

/**
 * Requires this PHP api to make soap calls and parse responses
 * This is an extend version of:
 * @see https://github.com/alloylab/kerio-admin-api-soap-php
 */
require_once(__DIR__ . '/api/KerioWhmcs.php');

$whmcs = App::self();
$domainName = $_GET['domain'];
$productID = $_GET['pid'];
if(!filter_var($domainName, FILTER_VALIDATE_DOMAIN)) {
    echo "invalid";
    exit;
}
// check active Kerio Domains
$accessData = array('kerioServer' => '', 'adminUser' => '', 'adminPass' => '');
$serverGroupIDObj = Capsule::table('tblproducts')
	->select('servergroup')
	->where('id', '=', $productID)
	->get();
$serverGroupID = $serverGroupIDObj[0]->servergroup;
$serverIDObj = Capsule::table('tblservergroupsrel')
    ->select('serverid')
    ->where('groupid', '=', $serverGroupID)
    ->get();
$serverID = $serverIDObj[0]->serverid;
$server = Capsule::table('tblservers')
	->select('hostname', 'username', 'password')
	->where('id', '=', $serverID)
	->get();
$accessData['kerioServer'] = $server[0]->hostname;
$accessData['adminUser'] = $server[0]->username;
$adminPassDecrypt = localAPI('DecryptPassword', array('password2' => $server[0]->password));
if ($adminPassDecrypt['result'] == 'success') {
	$accessData['adminPass'] = $adminPassDecrypt['password'];
}
$api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
try {
	$api->login($accessData['kerioServer'], $accessData['adminUser'], $accessData['adminPass']);
} catch (KerioApiException $error) {
	logModuleCall(
		'kerioEmail',
		__FUNCTION__,
		$accessData,
		'Error: cannot login to ' . $accessData['kerioServer'],
		$error->getMessage()
	);
	exit();
}
$respond = $api->getDomains(['name','aliasList']);
$domains= [];
foreach($respond as $domain) {
	array_push($domains,$domain['name']);
	foreach($domain['aliasList'] as $alias) {
		array_push($domains,$alias);
	}
}
if(in_array($domainName,$domains)) {
	echo 'no';
} else {
	echo 'yes';
}
$api->logout();
