wordpress-domains-plugin/mozout-domains/includes/class-search.php

390 lines
20 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/**
* Domain search with WHOIS ([mozout_domain_finder] and block) and a price list ([mozout_tld_prices] and block).
* The visitor asks this WordPress (REST route), and WordPress asks the API with the key: the key never reaches the browser.
* Uses GET /v1/whois, GET /v1/whois/{domain} and, for reseller prices and the price list, GET /v1/catalog/tlds.
*/
class MOZOUT_DOMAINS_Search
{
public static function init()
{
add_shortcode('mozout_domain_finder', array(__CLASS__, 'shortcode_search'));
add_shortcode('mozout_tld_prices', array(__CLASS__, 'shortcode_prices'));
add_action('init', array(__CLASS__, 'register_blocks'));
add_action('rest_api_init', array(__CLASS__, 'routes'));
}
public static function default_extensions()
{
return '.com, .net, .org, .io';
}
public static function extensions($csv = '')
{
$csv = trim((string) $csv) !== '' ? $csv : (trim((string) MOZOUT_DOMAINS_Settings::get('extensions')) !== '' ? MOZOUT_DOMAINS_Settings::get('extensions') : self::default_extensions());
$out = array();
foreach (preg_split('/[\s,]+/', strtolower((string) $csv)) as $e) {
$e = '.' . ltrim(preg_replace('/[^a-z0-9.\-]/', '', $e), '.');
if (strlen($e) > 2 && !in_array($e, $out, true)) {
$out[] = $e;
}
}
return array_slice($out, 0, 10);
}
public static function register_blocks()
{
wp_register_script('mozout-domains-blocks', MOZOUT_DOMAINS_URL . 'assets/blocks.js', array('wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-server-side-render'), MOZOUT_DOMAINS_VERSION, true);
wp_localize_script('mozout-domains-blocks', 'mozoutDomainsBlocks', array(
'search' => __('Domain search', 'mozout-domains'),
'prices' => __('Domain price list', 'mozout-domains'),
'settings' => __('Settings', 'mozout-domains'),
'extensions' => __('Extensions (comma separated; empty uses the settings)', 'mozout-domains'),
'button' => __('Button text', 'mozout-domains'),
'placeholder' => __('Text inside the box', 'mozout-domains'),
));
register_block_type(MOZOUT_DOMAINS_DIR . 'blocks/domain-finder', array(
'render_callback' => function ($a) {
return MOZOUT_DOMAINS_Search::shortcode_search(array(
'extensions' => isset($a['extensions']) ? $a['extensions'] : '',
'button' => isset($a['button']) ? $a['button'] : '',
'placeholder' => isset($a['placeholder']) ? $a['placeholder'] : '',
));
},
'editor_script' => 'mozout-domains-blocks',
));
register_block_type(MOZOUT_DOMAINS_DIR . 'blocks/tld-prices', array(
'render_callback' => function ($a) {
return MOZOUT_DOMAINS_Search::shortcode_prices(array('extensions' => isset($a['extensions']) ? $a['extensions'] : ''));
},
'editor_script' => 'mozout-domains-blocks',
));
}
/* ---- Search box ---- */
public static function shortcode_search($atts)
{
$a = shortcode_atts(array('extensions' => '', 'button' => '', 'placeholder' => ''), $atts, 'mozout_domain_finder');
$exts = self::extensions($a['extensions']);
$lang = MOZOUT_DOMAINS_I18n::lang();
$color = sanitize_hex_color((string) MOZOUT_DOMAINS_Settings::get('color'));
wp_enqueue_style('mozout-domains-search', MOZOUT_DOMAINS_URL . 'assets/search.css', array(), MOZOUT_DOMAINS_VERSION);
wp_enqueue_script('mozout-domains-search', MOZOUT_DOMAINS_URL . 'assets/search.js', array(), MOZOUT_DOMAINS_VERSION, true);
wp_localize_script('mozout-domains-search', 'mozoutDomainsSearch', array(
'url' => esc_url_raw(rest_url('mozout-domains/v1/search')),
'whois' => esc_url_raw(rest_url('mozout-domains/v1/whois')),
'lang' => $lang,
'showWhois' => (int) MOZOUT_DOMAINS_Settings::get('show_whois') === 1,
'searching' => __('Searching...', 'mozout-domains'),
'error' => __('The search is not available right now. Please try again later.', 'mozout-domains'),
'available' => __('Available', 'mozout-domains'),
'registered' => __('Already registered', 'mozout-domains'),
'unknown' => __('Could not confirm', 'mozout-domains'),
'register' => __('Register', 'mozout-domains'),
'transfer' => __('Transfer', 'mozout-domains'),
'perYear' => __('per year', 'mozout-domains'),
'renew' => __('renewal', 'mozout-domains'),
'premium' => __('Premium', 'mozout-domains'),
'similar' => __('Similar names available', 'mozout-domains'),
/* translators: %s: expiry date */
'expires' => __('Expires on %s', 'mozout-domains'),
'seeWhois' => __('See WHOIS', 'mozout-domains'),
'hideWhois' => __('Hide WHOIS', 'mozout-domains'),
'created' => __('Registered on', 'mozout-domains'),
'expiresOn' => __('Expires on', 'mozout-domains'),
'daysLeft' => __('Days until it expires', 'mozout-domains'),
'state' => __('Status at the registry', 'mozout-domains'),
'ns' => __('Nameservers', 'mozout-domains'),
));
$placeholder = $a['placeholder'] !== '' ? $a['placeholder'] : __('Write the name you want, for example mycompany', 'mozout-domains');
$button = $a['button'] !== '' ? $a['button'] : __('Search', 'mozout-domains');
$id = 'mozout-domains-q-' . substr(md5(wp_json_encode($a) . wp_rand()), 0, 8);
ob_start();
?>
<form class="mozout-domains-finder" role="search" data-ext="<?php echo esc_attr(implode(',', $exts)); ?>"<?php echo $color ? ' style="--mozout-domains-accent:' . esc_attr($color) . '"' : ''; ?>>
<label class="mozout-domains-sr" for="<?php echo esc_attr($id); ?>"><?php esc_html_e('Domain name', 'mozout-domains'); ?></label>
<div class="mozout-domains-finder__row">
<input type="text" id="<?php echo esc_attr($id); ?>" name="q" maxlength="80" autocomplete="off" autocapitalize="none" spellcheck="false" placeholder="<?php echo esc_attr($placeholder); ?>" required>
<button type="submit"><?php echo esc_html($button); ?></button>
</div>
<p class="mozout-domains-finder__hint"><?php echo esc_html(sprintf(
/* translators: %s: list of domain extensions */
__('We look up: %s', 'mozout-domains'),
implode(' ', $exts)
)); ?></p>
<div class="mozout-domains-finder__results" aria-live="polite"></div>
</form>
<?php
return ob_get_clean();
}
public static function routes()
{
register_rest_route('mozout-domains/v1', '/search', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'rest_search'),
'permission_callback' => '__return_true',
));
register_rest_route('mozout-domains/v1', '/whois', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'rest_whois'),
'permission_callback' => '__return_true',
));
}
/** Cleans what the visitor wrote: "https://www.MyCompany.com/x" becomes "mycompany.com". */
public static function clean($q)
{
$q = strtolower(trim((string) $q));
$q = preg_replace('#^[a-z]+://#', '', $q);
$q = preg_replace('#^www\.#', '', $q);
$q = preg_replace('#[/?\#].*$#', '', $q);
$q = preg_replace('/\s+/', '', $q);
$q = preg_replace('/[^a-z0-9.\-]/', '', $q);
return trim($q, '.-');
}
public static function client_ip()
{
$ip = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';
}
/** Counts requests per visitor in a window; false when over the limit. */
public static function rate_ok($bucket, $max, $window)
{
$key = 'mozout_domains_rl_' . md5($bucket);
$n = (int) get_transient($key);
if ($n >= $max) {
return false;
}
set_transient($key, $n + 1, $window);
return true;
}
public static function rest_search(WP_REST_Request $req)
{
$lang = $req->get_param('lang') === 'pt' ? 'pt' : 'en';
$t = function ($s) use ($lang) {
return MOZOUT_DOMAINS_I18n::in($lang, $s);
};
$q = self::clean($req->get_param('q'));
$label = strpos($q, '.') === false ? $q : substr($q, 0, strpos($q, '.'));
if (strlen($label) < 1 || strlen($label) > 63) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('Write a valid name, with letters, numbers or hyphens.')), 422);
}
$exts = self::extensions($req->get_param('ext'));
$cache_key = 'mozout_domains_q_' . md5(MOZOUT_DOMAINS_Brands::current_id() . '|' . $lang . '|' . $q . '|' . implode(',', $exts) . '|' . wp_json_encode(MOZOUT_DOMAINS_Settings::all()));
$hit = get_transient($cache_key);
if (is_array($hit)) {
return new WP_REST_Response($hit, 200);
}
if (!self::rate_ok('search_' . self::client_ip(), max(1, (int) MOZOUT_DOMAINS_Settings::get('per_hour')), HOUR_IN_SECONDS)) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('Too many searches. Please try again later.')), 429);
}
$query = array('language' => $lang);
$cur = (string) MOZOUT_DOMAINS_Settings::get('currency');
if ($cur !== '') {
$query['currency'] = $cur;
}
$results = array();
$alternatives = array();
if (strpos($q, '.') !== false) {
// Exact name: one lookup, which also brings similar free names.
$res = MOZOUT_DOMAINS_Api::request('GET', '/v1/whois/' . rawurlencode($q), null, array('query' => $query, 'lang' => $lang, 'timeout' => 20, 'public' => true));
if (is_wp_error($res)) {
return self::error_reply($res, $t);
}
$results[] = self::simplify($res['data'], $lang);
if (!empty($res['data']['alternatives']) && is_array($res['data']['alternatives'])) {
foreach (array_slice($res['data']['alternatives'], 0, 4) as $alt) {
$alternatives[] = self::simplify(array_merge(array('status' => 'available', 'available' => true), $alt), $lang);
}
}
$others = array();
foreach ($exts as $e) {
if ($label . $e !== $q) {
$others[] = $label . $e;
}
}
if ($others) {
$query['domains'] = implode(',', array_slice($others, 0, 9));
$more = MOZOUT_DOMAINS_Api::request('GET', '/v1/whois', null, array('query' => $query, 'lang' => $lang, 'timeout' => 20, 'public' => true));
if (!is_wp_error($more) && is_array($more['data'])) {
foreach ($more['data'] as $d) {
if (isset($d['status']) && $d['status'] !== 'error') {
$results[] = self::simplify($d, $lang);
}
}
}
}
} else {
$names = array();
foreach ($exts as $e) {
$names[] = $label . $e;
}
$query['domains'] = implode(',', $names);
$res = MOZOUT_DOMAINS_Api::request('GET', '/v1/whois', null, array('query' => $query, 'lang' => $lang, 'timeout' => 20, 'public' => true));
if (is_wp_error($res)) {
return self::error_reply($res, $t);
}
foreach ((array) $res['data'] as $d) {
if (isset($d['status']) && $d['status'] !== 'error') {
$results[] = self::simplify($d, $lang);
}
}
}
if (!$results) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('This extension is not available. Try another one.')), 200);
}
$out = array('ok' => true, 'results' => $results, 'alternatives' => $alternatives);
set_transient($cache_key, $out, 10 * MINUTE_IN_SECONDS);
return new WP_REST_Response($out, 200);
}
/** Public WHOIS data of a registered name: dates, status and nameservers. */
public static function rest_whois(WP_REST_Request $req)
{
$lang = $req->get_param('lang') === 'pt' ? 'pt' : 'en';
$t = function ($s) use ($lang) {
return MOZOUT_DOMAINS_I18n::in($lang, $s);
};
if ((int) MOZOUT_DOMAINS_Settings::get('show_whois') !== 1) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('The search is not available right now. Please try again later.')), 403);
}
$d = self::clean($req->get_param('d'));
if (strpos($d, '.') === false || strlen($d) > 120) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('Write a valid name, with letters, numbers or hyphens.')), 422);
}
$key = 'mozout_domains_q_w' . md5(MOZOUT_DOMAINS_Brands::current_id() . '|' . $d);
$hit = get_transient($key);
if (is_array($hit)) {
return new WP_REST_Response($hit, 200);
}
if (!self::rate_ok('whois_' . self::client_ip(), max(1, (int) MOZOUT_DOMAINS_Settings::get('per_hour')), HOUR_IN_SECONDS)) {
return new WP_REST_Response(array('ok' => false, 'message' => $t('Too many searches. Please try again later.')), 429);
}
$res = MOZOUT_DOMAINS_Api::request('GET', '/v1/whois/' . rawurlencode($d), null, array('query' => array('language' => $lang), 'lang' => $lang, 'timeout' => 20, 'public' => true));
if (is_wp_error($res)) {
return self::error_reply($res, $t);
}
$r = isset($res['data']['registration']) && is_array($res['data']['registration']) ? $res['data']['registration'] : array();
$out = array(
'ok' => true,
'domain' => $d,
'created' => !empty($r['created']) ? substr((string) $r['created'], 0, 10) : '',
'expires' => !empty($r['expires']) ? substr((string) $r['expires'], 0, 10) : '',
'days' => isset($r['days_until_expiry']) ? (int) $r['days_until_expiry'] : null,
'status' => isset($r['domain_status']) && is_array($r['domain_status']) ? array_slice(array_map('strval', $r['domain_status']), 0, 8) : array(),
'ns' => isset($r['nameservers']) && is_array($r['nameservers']) ? array_slice(array_map('strval', $r['nameservers']), 0, 8) : array(),
);
set_transient($key, $out, 30 * MINUTE_IN_SECONDS);
return new WP_REST_Response($out, 200);
}
private static function error_reply(WP_Error $e, $t)
{
$data = $e->get_error_data();
if (is_array($data) && isset($data['status']) && (int) $data['status'] === 422 && !empty($data['api_message'])) {
return new WP_REST_Response(array('ok' => false, 'message' => $data['api_message']), 422);
}
MOZOUT_DOMAINS_Log::add('search', false, $e->get_error_message());
return new WP_REST_Response(array('ok' => false, 'message' => $t('The search is not available right now. Please try again later.')), 502);
}
/** Only what the page shows. Links are kept only when they are https. */
private static function simplify($d, $lang)
{
$status = isset($d['status']) ? (string) $d['status'] : 'unknown';
if (!in_array($status, array('available', 'registered'), true)) {
$status = 'unknown';
}
$domain = isset($d['domain']) ? (string) $d['domain'] : '';
$p = isset($d['price']) && is_array($d['price']) ? $d['price'] : array();
$f = isset($p['formatted']) && is_array($p['formatted']) ? $p['formatted'] : array();
$cur = isset($p['currency']) ? $p['currency'] : '';
$reg = isset($p['register']) ? MOZOUT_DOMAINS_Admin::money($p['register'], $cur, $lang) : (isset($f['register']) ? $f['register'] : '');
$ren = isset($p['renew']) ? MOZOUT_DOMAINS_Admin::money($p['renew'], $cur, $lang) : (isset($f['renew']) ? $f['renew'] : '');
$tra = isset($p['transfer']) ? MOZOUT_DOMAINS_Admin::money($p['transfer'], $cur, $lang) : (isset($f['transfer']) ? $f['transfer'] : '');
$premium = !empty($p['premium']);
if (MOZOUT_DOMAINS_Pricing::reseller_mode() && !$premium && $domain !== '') {
$ext = substr($domain, strpos($domain, '.'));
$own = MOZOUT_DOMAINS_Pricing::selling($ext, $lang);
if ($own) {
$reg = $own['register'] !== '' ? $own['register'] : $reg;
$ren = $own['renew'] !== '' ? $own['renew'] : $ren;
$tra = $own['transfer'] !== '' ? $own['transfer'] : $tra;
}
}
$api_url = '';
if ($status === 'available' && !empty($d['register_url'])) {
$api_url = (string) $d['register_url'];
} elseif ($status === 'registered' && !empty($d['transfer_url'])) {
$api_url = (string) $d['transfer_url'];
}
$url = self::buy_url($domain, $status, $api_url);
if ($status === 'registered' && (int) MOZOUT_DOMAINS_Settings::get('show_transfer') !== 1) {
$url = '';
}
return array(
'domain' => $domain,
'status' => $status,
'price' => $status === 'registered' ? '' : $reg,
'renew' => $ren,
'transfer' => $status === 'registered' ? $tra : '',
'premium' => $premium,
'expires' => ($status === 'registered' && !empty($d['registration']['expires'])) ? substr((string) $d['registration']['expires'], 0, 10) : '',
'url' => $url,
);
}
/**
* Where the Register (or Transfer) button goes: the brand site (link given by the API), your own address with {domain},
* or the WooCommerce cart when the Reseller plugin of the same brand is active (filter mozout_domain_buy_url).
*/
public static function buy_url($domain, $status, $api_url)
{
if ($status === 'unknown' || $domain === '') {
return '';
}
$target = (string) MOZOUT_DOMAINS_Settings::get('buy_target');
$url = $api_url;
if ($target === 'custom') {
$tpl = (string) MOZOUT_DOMAINS_Settings::get('buy_url');
$url = $tpl !== '' ? str_replace(array('{domain}', '{action}'), array(rawurlencode($domain), $status === 'available' ? 'register' : 'transfer'), $tpl) : $api_url;
} elseif ($target === 'woocommerce') {
$url = (string) apply_filters('mozout_domain_buy_url', $api_url, $domain, $status === 'available' ? 'register' : 'transfer');
}
$url = esc_url_raw($url);
return (strpos($url, 'https://') === 0 || strpos($url, home_url('/')) === 0) ? $url : '';
}
/* ---- Price list ---- */
public static function shortcode_prices($atts)
{
$a = shortcode_atts(array('extensions' => ''), $atts, 'mozout_tld_prices');
$exts = self::extensions($a['extensions']);
if (MOZOUT_DOMAINS_Settings::api_key() === '') {
return current_user_can('manage_options') ? '<!-- ' . esc_html__('The API key is missing. Save it in the plugin settings.', 'mozout-domains') . ' -->' : '';
}
$rows = MOZOUT_DOMAINS_Pricing::table($exts);
if (!$rows) {
return '';
}
wp_enqueue_style('mozout-domains-search', MOZOUT_DOMAINS_URL . 'assets/search.css', array(), MOZOUT_DOMAINS_VERSION);
$h = '<div class="mozout-domains-prices-wrap"><table class="mozout-domains-prices"><thead><tr><th>' . esc_html__('Extension', 'mozout-domains') . '</th><th>' . esc_html__('Register (1 year)', 'mozout-domains') . '</th><th>' . esc_html__('Renewal (1 year)', 'mozout-domains') . '</th><th>' . esc_html__('Transfer', 'mozout-domains') . '</th></tr></thead><tbody>';
foreach ($rows as $r) {
$h .= '<tr><td><strong>' . esc_html($r['extension']) . '</strong></td><td>' . esc_html($r['register']) . '</td><td>' . esc_html($r['renew']) . '</td><td>' . esc_html($r['transfer']) . '</td></tr>';
}
return $h . '</tbody></table></div>';
}
}