Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório whmcs-domains-module, anteriormente
0
whmcs-domains-module/modules/registrars/mozout_domains/mozout_domains.php
2026-11-28 15:28:08 +02:00

510 linhas
20 KiB
PHP

<?php
/**
* Domain registration module for the resellers' WHMCS.
* Talks to the public API (v1) of the chosen brand: MozOut. A brand edition has brand.php next
* to this file: then the brand and the API address are fixed.
*
* Compatible with PHP 7.4 and 8.x and WHMCS 7.10 or newer.
*/
if (!defined('WHMCS')) {
die('This file cannot be accessed directly');
}
require_once __DIR__ . '/lib/Api.php';
use MozoutDomains\Api;
use MozoutDomains\ApiException;
use MozoutDomains\I18n;
use WHMCS\Domains\DomainLookup\ResultsList;
use WHMCS\Domains\DomainLookup\SearchResult;
function mozout_domains_MetaData()
{
return array(
'DisplayName' => Api::brandName(I18n::context()) . ' (API)',
'APIVersion' => '1.1',
);
}
function mozout_domains_getConfigArray()
{
$l = I18n::context();
$t = function ($k) use ($l) { return I18n::t($l, $k); };
$fixed = Api::fixedBrand();
$config = array(
'FriendlyName' => array('Type' => 'System', 'Value' => Api::brandName($l) . ' (API)'),
'Description' => array('Type' => 'System', 'Value' => sprintf($t('cfg_description'), Api::brandName($l))),
);
if (!$fixed) {
$brands = array();
foreach (Api::brands() as $code => $b) {
$brands[$code] = $l === 'pt' ? $b['name'] : $b['name_en'];
}
$config['Brand'] = array(
'FriendlyName' => $t('cfg_brand'),
'Type' => 'dropdown',
'Options' => $brands,
'Default' => key($brands),
'Description' => $t('cfg_brand_desc'),
);
}
$config += array(
'ApiKey' => array(
'FriendlyName' => $t('cfg_api_key'),
'Type' => 'password',
'Size' => '60',
'Description' => $t('cfg_api_key_desc'),
),
'ExpectedMode' => array(
'FriendlyName' => $t('cfg_mode'),
'Type' => 'dropdown',
'Options' => array('any' => $t('opt_any'), 'sandbox' => 'Sandbox', 'production' => $t('opt_production')),
'Default' => 'any',
'Description' => $t('cfg_mode_desc'),
),
'Language' => array(
'FriendlyName' => $t('cfg_language'),
'Type' => 'dropdown',
'Options' => array('auto' => $t('opt_auto'), 'en' => 'English', 'pt' => 'Português'),
'Default' => 'auto',
'Description' => $t('cfg_language_desc'),
),
'PricingCurrency' => array(
'FriendlyName' => $t('cfg_currency'),
'Type' => 'text',
'Size' => '5',
'Description' => $t('cfg_currency_desc'),
),
'DisableUpstreamAutoRenew' => array(
'FriendlyName' => $t('cfg_auto_renew'),
'Type' => 'yesno',
'Default' => 'on',
'Description' => $t('cfg_auto_renew_desc'),
),
'LabelEndCustomer' => array(
'FriendlyName' => $t('cfg_label'),
'Type' => 'yesno',
'Default' => 'on',
'Description' => $t('cfg_label_desc'),
),
);
if (!$fixed) {
$config['ApiUrl'] = array(
'FriendlyName' => $t('cfg_api_url'),
'Type' => 'text',
'Size' => '50',
'Description' => $t('cfg_api_url_desc'),
);
}
return $config;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function mozout_domains__domain(array $params)
{
$sld = isset($params['sld']) ? trim((string) $params['sld']) : '';
$tld = isset($params['tld']) ? ltrim(trim((string) $params['tld']), '.') : '';
if ($sld === '' && !empty($params['domainname'])) {
return strtolower((string) $params['domainname']);
}
return strtolower($sld . '.' . $tld);
}
function mozout_domains__ns(array $params)
{
$l = array();
for ($i = 1; $i <= 5; $i++) {
$v = isset($params['ns' . $i]) ? strtolower(trim((string) $params['ns' . $i])) : '';
if ($v !== '' && !in_array($v, $l, true)) {
$l[] = $v;
}
}
return $l;
}
function mozout_domains__err(\Exception $e)
{
return array('error' => $e->getMessage());
}
function mozout_domains__path($domain, $suffix = '')
{
return '/v1/domains/' . rawurlencode($domain) . $suffix;
}
/** After registering or transferring: end customer label and renewal on our side. */
function mozout_domains__after_purchase(Api $api, array $params, $domain)
{
try {
$r = $api->get(mozout_domains__path($domain), array(), 'Domain info');
} catch (\Exception $e) {
return; /* not in the account yet (order in progress or Sandbox) */
}
$d = isset($r['data']) ? $r['data'] : array();
mozout_domains__fix_auto_renew($api, $params, $domain, $d);
if (!empty($params['LabelEndCustomer']) && !empty($d['id'])) {
$name = trim(isset($params['companyname']) && $params['companyname'] !== '' ? $params['companyname'] : (isset($params['fullname']) ? $params['fullname'] : ''));
if ($name === '') {
$name = trim((isset($params['firstname']) ? $params['firstname'] : '') . ' ' . (isset($params['lastname']) ? $params['lastname'] : ''));
}
if ($name !== '') {
try {
$api->put('/v1/reseller/customers/domain/' . (int) $d['id'], array('name' => function_exists('mb_substr') ? mb_substr($name, 0, 100) : substr($name, 0, 100)), 'Label end customer');
} catch (\Exception $e) {
/* no Reseller Program or no reseller:write: not a registration error */
}
}
}
}
function mozout_domains__fix_auto_renew(Api $api, array $params, $domain, array $d)
{
if (!empty($params['DisableUpstreamAutoRenew']) && !empty($d['auto_renew'])) {
try {
$api->put(mozout_domains__path($domain, '/auto-renew'), array('auto_renew' => false), 'Turn off upstream auto-renew');
} catch (\Exception $e) {
/* left for the next sync */
}
}
}
/* ------------------------------------------------------------------ */
/* Registration, transfer and renewal */
/* ------------------------------------------------------------------ */
function mozout_domains_RegisterDomain($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
$body = array('domain' => $domain, 'years' => max(1, min(10, (int) $params['regperiod'])), 'locked' => true);
$ns = mozout_domains__ns($params);
if (count($ns) >= 2) {
$body['nameservers'] = $ns;
}
$key = Api::idempotencyKey('register', (int) $params['domainid'], $body);
$api->post('/v1/domains/register', $body, $key, 'RegisterDomain');
mozout_domains__after_purchase($api, $params, $domain);
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_TransferDomain($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
$code = isset($params['eppcode']) ? trim((string) html_entity_decode($params['eppcode'], ENT_QUOTES, 'UTF-8')) : '';
if ($code === '') {
return array('error' => I18n::t($api->lang(), 'err_no_epp'));
}
/* The code only goes in the request: it is never saved and never appears in the module log */
$api->addSecret($code);
$body = array('domain' => $domain, 'transfer_code' => $code);
$key = Api::idempotencyKey('transfer', (int) $params['domainid'], $body);
$api->post('/v1/domains/transfer', $body, $key, 'TransferDomain');
mozout_domains__after_purchase($api, $params, $domain);
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_RenewDomain($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
$body = array('years' => max(1, min(10, (int) $params['regperiod'])));
/* The expiry date is part of the key: next year's renewal is another operation */
$ref = (int) $params['domainid'] . '|' . (isset($params['expirydate']) ? $params['expirydate'] : date('Y-m-d'));
$key = Api::idempotencyKey('renew', $ref, $body);
$api->post(mozout_domains__path($domain, '/renew'), $body, $key, 'RenewDomain');
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
/* ------------------------------------------------------------------ */
/* Nameservers, lock and EPP code */
/* ------------------------------------------------------------------ */
function mozout_domains_GetNameservers($params)
{
try {
$api = Api::fromParams($params);
$r = $api->get(mozout_domains__path(mozout_domains__domain($params), '/nameservers'), array(), 'GetNameservers');
$l = isset($r['data']['nameservers']) && is_array($r['data']['nameservers']) ? array_values($r['data']['nameservers']) : array();
$out = array();
for ($i = 1; $i <= 5; $i++) {
$out['ns' . $i] = isset($l[$i - 1]) ? (string) $l[$i - 1] : '';
}
return $out;
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_SaveNameservers($params)
{
try {
$api = Api::fromParams($params);
$ns = mozout_domains__ns($params);
if (count($ns) < 2) {
return array('error' => I18n::t($api->lang(), 'err_two_ns'));
}
$api->put(mozout_domains__path(mozout_domains__domain($params), '/nameservers'), array('nameservers' => $ns), 'SaveNameservers');
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_GetRegistrarLock($params)
{
try {
$api = Api::fromParams($params);
$r = $api->get(mozout_domains__path(mozout_domains__domain($params), '/lock'), array(), 'GetRegistrarLock');
$locked = isset($r['data']['locked']) ? $r['data']['locked'] : null;
if ($locked === null) {
return '';
}
return $locked ? 'locked' : 'unlocked';
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_SaveRegistrarLock($params)
{
try {
$api = Api::fromParams($params);
$lock = (isset($params['lockenabled']) && $params['lockenabled'] === 'locked');
$api->put(mozout_domains__path(mozout_domains__domain($params), '/lock'), array('locked' => $lock), 'SaveRegistrarLock');
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
/**
* The API never returns the code: it sends it by email to the address of the account
* or of the domain owner. Without «eppcode» in the answer, WHMCS shows that
* it was sent by email.
*/
function mozout_domains_GetEPPCode($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
$api->post(mozout_domains__path($domain, '/transfer-code'), array('confirm' => $domain), '', 'GetEPPCode');
return array('success' => true);
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
/* ------------------------------------------------------------------ */
/* Sync */
/* ------------------------------------------------------------------ */
function mozout_domains_Sync($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
$r = $api->get(mozout_domains__path($domain), array(), 'Sync');
$d = isset($r['data']) ? $r['data'] : array();
$status = isset($d['status']) ? (string) $d['status'] : '';
$out = array();
if (!empty($d['expires_at']) && preg_match('~^\d{4}-\d{2}-\d{2}~', $d['expires_at'])) {
$out['expirydate'] = substr($d['expires_at'], 0, 10);
}
$out['active'] = ($status === 'active');
$out['expired'] = in_array($status, array('expired', 'grace', 'redemption'), true);
$out['transferredAway'] = ($status === 'transferred_away');
$out['cancelled'] = in_array($status, array('cancelled', 'fraud'), true);
mozout_domains__fix_auto_renew($api, $params, $domain, $d);
return $out;
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
function mozout_domains_TransferSync($params)
{
try {
$api = Api::fromParams($params);
$domain = mozout_domains__domain($params);
try {
$r = $api->get(mozout_domains__path($domain), array(), 'TransferSync');
} catch (ApiException $e) {
if ($e->httpStatus === 404) {
return array(); /* has not reached the account yet: stays pending */
}
throw $e;
}
$d = isset($r['data']) ? $r['data'] : array();
$status = isset($d['status']) ? (string) $d['status'] : '';
if ($status === 'active') {
$out = array('completed' => true);
if (!empty($d['expires_at'])) {
$out['expirydate'] = substr($d['expires_at'], 0, 10);
}
mozout_domains__after_purchase($api, $params, $domain);
return $out;
}
if (in_array($status, array('cancelled', 'fraud'), true)) {
return array('failed' => true, 'reason' => I18n::t($api->lang(), 'err_transfer_cancelled'));
}
return array();
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
/* ------------------------------------------------------------------ */
/* Availability (domain search) */
/* ------------------------------------------------------------------ */
function mozout_domains_CheckAvailability($params)
{
try {
$api = Api::fromParams($params);
$sld = !empty($params['isIdnDomain']) && !empty($params['punyCodeSearchTerm']) ? $params['punyCodeSearchTerm'] : $params['searchTerm'];
$sld = strtolower(trim((string) $sld));
$tlds = array();
foreach ((array) $params['tldsToInclude'] as $t) {
$t = ltrim(strtolower(trim((string) $t)), '.');
if ($t !== '') {
$tlds[$t] = true;
}
}
$results = new ResultsList();
foreach (array_chunk(array_keys($tlds), 10) as $chunk) {
$names = array();
foreach ($chunk as $t) {
$names[] = $sld . '.' . $t;
}
$query = array('domains' => implode(',', $names), 'language' => $api->lang());
if (!empty($params['PricingCurrency'])) {
$query['currency'] = strtoupper(trim($params['PricingCurrency']));
}
$r = $api->get('/v1/whois', $query, 'CheckAvailability');
$byName = array();
foreach ((isset($r['data']) ? $r['data'] : array()) as $row) {
if (isset($row['domain'])) {
$byName[strtolower($row['domain'])] = $row;
}
}
foreach ($chunk as $t) {
$sr = new SearchResult($sld, '.' . $t);
$row = isset($byName[$sld . '.' . $t]) ? $byName[$sld . '.' . $t] : array();
$st = isset($row['status']) ? $row['status'] : 'unknown';
$premium = !empty($row['premium']) || !empty($row['price']['premium']) || !empty($row['quote_required']);
if ($st === 'available' && $premium) {
/* Premium names and names with their own price are handled in the brand's panel */
$sr->setStatus(SearchResult::STATUS_RESERVED);
} elseif ($st === 'available') {
$sr->setStatus(SearchResult::STATUS_NOT_REGISTERED);
} elseif ($st === 'registered') {
$sr->setStatus(SearchResult::STATUS_REGISTERED);
} elseif ($st === 'not_allowed') {
$sr->setStatus(SearchResult::STATUS_RESERVED);
} elseif ($st === 'error' && isset($row['error']) && stripos((string) (is_array($row['error']) ? json_encode($row['error']) : $row['error']), 'extension') !== false) {
$sr->setStatus(SearchResult::STATUS_TLD_NOT_SUPPORTED);
} else {
$sr->setStatus(SearchResult::STATUS_UNKNOWN);
}
$results->append($sr);
}
}
return $results;
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}
/* ------------------------------------------------------------------ */
/* Extension prices (Registrar TLD Sync) */
/* ------------------------------------------------------------------ */
function mozout_domains__price_rows(Api $api, $path, array $query)
{
$rows = array();
$page = 1;
do {
$query['page'] = $page;
$query['per_page'] = 100;
$r = $api->get($path, $query, 'GetTldPricing p' . $page);
foreach ((isset($r['data']) ? $r['data'] : array()) as $row) {
$rows[] = $row;
}
$pages = isset($r['meta']['total_pages']) ? (int) $r['meta']['total_pages'] : 1;
$page++;
} while ($page <= $pages && $page <= 50);
return $rows;
}
function mozout_domains_GetTldPricing($params)
{
try {
$api = Api::fromParams($params);
$query = array();
if (!empty($params['PricingCurrency'])) {
$query['currency'] = strtoupper(trim($params['PricingCurrency']));
}
/* Reseller prices (Reseller Program); without it, the catalog already has the account price */
try {
$rows = mozout_domains__price_rows($api, '/v1/reseller/pricing', $query + array('type' => 'domains'));
} catch (ApiException $e) {
if ($e->httpStatus !== 403) {
throw $e;
}
$rows = mozout_domains__price_rows($api, '/v1/catalog/tlds', $query);
}
$results = new \WHMCS\Results\ResultsList();
foreach ($rows as $row) {
$ext = isset($row['extension']) ? '.' . ltrim((string) $row['extension'], '.') : '';
$reg = isset($row['register']) && is_array($row['register']) ? $row['register'] : array();
$ren = isset($row['renew']) && is_array($row['renew']) ? $row['renew'] : array();
$tra = isset($row['transfer']) && is_array($row['transfer']) ? $row['transfer'] : array();
if ($ext === '.' || !isset($reg['1']) && !isset($reg[1])) {
continue;
}
$years = array();
foreach (array_keys($reg) as $y) {
if ((int) $y >= 1 && (int) $y <= 10) {
$years[] = (int) $y;
}
}
sort($years);
$item = (new \WHMCS\Domain\TopLevel\ImportItem())
->setExtension($ext)
->setMinYears(min($years))
->setMaxYears(max($years))
->setRegisterPrice((float) $reg[1])
->setRenewPrice(isset($ren[1]) ? (float) $ren[1] : (float) $reg[1])
->setCurrency(isset($row['currency']) ? (string) $row['currency'] : 'USD')
->setEppRequired(!isset($row['features']['transfer_code_required']) || (bool) $row['features']['transfer_code_required']);
if (isset($tra[1]) || isset($tra['1'])) {
$item->setTransferPrice((float) $tra[1]);
}
if (method_exists($item, 'setYears')) {
$item->setYears($years);
}
$results[] = $item;
}
return $results;
} catch (\Exception $e) {
return mozout_domains__err($e);
}
}