'sanitize_text_field', 'default' => '', )); register_setting('ad_unblock_options', 'ad_unblock_site_domain', array( 'sanitize_callback' => array($this, 'sanitize_site_domain'), 'default' => '', )); register_setting('ad_unblock_options', 'ad_unblock_custom_api_endpoint', array( 'sanitize_callback' => 'esc_url_raw', 'default' => '', )); register_setting('ad_unblock_options', 'ad_unblock_page_rules', array( 'sanitize_callback' => array($this, 'sanitize_page_rules'), 'default' => array( 'all_pages' => 'yes', 'url_patterns' => '', 'categories' => array(), 'tags' => array(), ), )); add_settings_section( 'ad_unblock_section_main', esc_html__('Main Settings', 'ad-unblock'), array($this, 'render_section_main'), 'ad_unblock' ); add_settings_field( 'ad_unblock_verification_code', esc_html__('Account ID', 'ad-unblock'), array($this, 'render_verification_code_field'), 'ad_unblock', 'ad_unblock_section_main' ); add_settings_field( 'ad_unblock_page_rules', esc_html__('Enable On Pages', 'ad-unblock'), array($this, 'render_page_rules_field'), 'ad_unblock', 'ad_unblock_section_main' ); add_settings_field( 'ad_unblock_site_domain', esc_html__('Site Domain', 'ad-unblock'), array($this, 'render_site_domain_field'), 'ad_unblock', 'ad_unblock_section_main' ); add_settings_field( 'ad_unblock_custom_api_endpoint', esc_html__('API Endpoint', 'ad-unblock'), array($this, 'render_custom_api_endpoint_field'), 'ad_unblock', 'ad_unblock_section_main' ); } /** * Sanitize the site domain setting * * Stored in the same normalized form the API keys its per-domain script * lists on, so a pasted URL ("https://www.example.com/") and a bare host * ("www.example.com") resolve to the same list. An unusable value is * stored as empty, which falls back to the site's own domain. */ public function sanitize_site_domain($input) { return $this->normalize_domain(is_string($input) ? $input : ''); } /** * Sanitize page rules */ public function sanitize_page_rules($input) { $sanitized = array( 'all_pages' => isset($input['all_pages']) && $input['all_pages'] === 'yes' ? 'yes' : 'no', 'url_patterns' => isset($input['url_patterns']) ? sanitize_textarea_field($input['url_patterns']) : '', 'categories' => array(), 'tags' => array(), ); if (isset($input['categories']) && is_array($input['categories'])) { $sanitized['categories'] = array_map('intval', $input['categories']); } if (isset($input['tags']) && is_array($input['tags'])) { $sanitized['tags'] = array_map('intval', $input['tags']); } return $sanitized; } /** * Render the admin page */ public function render_admin_page() { if (!current_user_can('manage_options')) { return; } ?>

render_connect_notice(); ?>
Ad Unblock Logo AdUnblock

  1. ad-unblock.com, then confirm this site. You are sent back here with your Account ID saved and the site added to your account.', 'ad-unblock'), array('a' => array('href' => array(), 'target' => array()))); ?>

render_page_cache_help(); ?>
'; echo '

' . esc_html__('Configure your Ad Unblock integration settings below.', 'ad-unblock') . '

'; echo ''; } /** * Render verification code field */ public function render_verification_code_field() { $account_id = $this->get_account_id(); $has_id = '' !== $account_id; $is_account_id = $this->is_account_id($account_id); $can_connect = $this->can_connect(); $domain = $this->get_site_domain(); // The field is open when it is the only way in (a site Connect can't // reach), or holds something that needs fixing. Otherwise it sits // behind a link, as a second way to do what Connect does. $field_open = ($has_id && !$is_account_id) || (!$has_id && !$can_connect); ?>
render_script_sources_problem(); } ?>

' . esc_html($account_id) . '' ); ?>

is_verified()) { esc_html_e('Verified. Ad Unblock found the tag on this site.', 'ad-unblock'); } ?>

render_unreachable_site_note($domain, true); ?>

render_unreachable_site_note($domain, false); ?>

>

get_connect_url()) . '">', '' ); ?>

' . esc_html($domain) . ''; if ($has_id) { printf( /* translators: %s: this site's domain, in a code element */ esc_html__('Ad Unblock cannot reach %s from the internet, so this site cannot be verified from here. The tag is still added to its pages with this Account ID.', 'ad-unblock'), $domain_html // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above ); } else { printf( /* translators: %s: this site's domain, in a code element */ esc_html__('Ad Unblock cannot reach %s from the internet, so this site cannot be connected from here. Enter an Account ID to try the plugin on it.', 'ad-unblock'), $domain_html // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above ); } } /** * Say so when the script sources cannot be loaded * * Without them there is no script for the tag to load, so insert_script() * prints nothing: no tag, and no meta tag for the verification check to * find. Nothing else on this page tells the admin why. The sources are * asked for the way a page view asks, so a saved list is used while it is * fresh and the API is tried when it is not. */ private function render_script_sources_problem() { $script_sources = $this->get_script_sources(); $missing = empty($script_sources) || !is_array($script_sources); $cache_status = $this->get_cache_status(); // A request that failed with an earlier list to fall back on leaves // the tag on the pages, so it is a warning and not an error. if (!$missing && !$cache_status['has_error']) { return; } $endpoint_html = '' . esc_html($this->get_api_endpoint()) . ''; echo '

'; if ($missing) { printf( /* translators: %s: the address of the script source API, in a code element */ esc_html__('The Ad Unblock tag is not being added to your pages. This site could not load the script sources from %s, and has no earlier copy to use.', 'ad-unblock'), $endpoint_html // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above ); } else { printf( /* translators: %s: the address of the script source API, in a code element */ esc_html__('This site could not load the script sources from %s just now. Your pages keep the tag, with the sources loaded earlier.', 'ad-unblock'), $endpoint_html // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above ); } echo ' '; if ('' !== (string) get_option('ad_unblock_custom_api_endpoint', '')) { esc_html_e('Check the custom API endpoint below.', 'ad-unblock'); } else { esc_html_e('If this message is still here in a few minutes, ask your host whether it blocks outgoing requests to that address.', 'ad-unblock'); } echo '

'; } /** * Show what came of a connect attempt, once, after its redirect back here */ private function render_connect_notice() { $transient = self::CONNECT_RESULT_TRANSIENT . get_current_user_id(); $result = get_transient($transient); if (false === $result) { return; } delete_transient($transient); if ('connected' === $result && $this->is_account_id($this->get_account_id())) { echo '

'; printf( /* translators: %s: the 8-digit Account ID, in a code element */ esc_html__('Connected to Ad Unblock account %s. If your site uses a page cache, clear it now so the tag reaches every page.', 'ad-unblock'), '' . esc_html($this->get_account_id()) . '' ); echo '

'; } elseif ('expired' === $result) { echo '

'; esc_html_e('That connection could not be finished: it was started too long ago, or in another browser or login. Nothing was changed. Click Connect to try again.', 'ad-unblock'); echo '

'; } elseif ('invalid' === $result) { echo '

'; esc_html_e('Ad Unblock sent back something that is not an Account ID. Nothing was changed. Try again, or enter your Account ID yourself.', 'ad-unblock'); echo '

'; } } /** * Render site domain field */ public function render_site_domain_field() { $detected = $this->get_default_site_domain(); $configured = $this->normalize_domain(get_option('ad_unblock_site_domain', '')); $effective = '' !== $configured ? $configured : $detected; ?>

' . esc_html($effective) . '' ); } else { printf( /* translators: 1: the configured domain, 2: the domain detected from the site address */ esc_html__('Currently sending %1$s. Clear this field to follow your site address (%2$s) instead.', 'ad-unblock'), '' . esc_html($configured) . '', '' . esc_html('' !== $detected ? $detected : '—') . '' ); } ?>


get_page_rules(); ?>




ad-unblock-verification' ); ?>

'yes', 'url_patterns' => '', 'categories' => array(), 'tags' => array(), )); } /** * Whether a request's address matches one of the URL patterns * * One pattern per line, matched from the start of the address, with `*` * standing for any run of characters. */ private function matches_url_patterns($url, $url_patterns) { $patterns = explode("\n", $url_patterns); foreach ($patterns as $pattern) { $pattern = trim($pattern); if (empty($pattern)) { continue; } // Convert wildcard pattern to regex. preg_quote() escapes the // delimiter as well, so only the wildcard is left to put back. $regex = str_replace('\*', '.*', preg_quote($pattern, '/')); if (preg_match('/^' . $regex . '/i', $url)) { return true; } } return false; } /** * Whether a post is in one of the categories or tags of the page rules */ private function post_matches_term_rules($post_id, $page_rules) { // Check categories if (!empty($page_rules['categories'])) { $post_categories = wp_get_post_categories($post_id); foreach ($post_categories as $category) { if (in_array($category, $page_rules['categories'])) { return true; } } } // Check tags if (!empty($page_rules['tags'])) { $post_tags = wp_get_post_tags($post_id, array('fields' => 'ids')); foreach ($post_tags as $tag) { if (in_array($tag, $page_rules['tags'])) { return true; } } } return false; } /** * Whether the page rules put the tag on this site's home page * * should_enable_on_current_page() for a visit to the home page, worked * out from the settings page: every page, a URL pattern the home page's * address matches, or a static front page in a chosen category or tag. * The home page is where Ad Unblock looks for the tag to verify a site. */ private function is_enabled_on_home_page() { $page_rules = $this->get_page_rules(); if (isset($page_rules['all_pages']) && $page_rules['all_pages'] === 'yes') { return true; } if (!empty($page_rules['url_patterns']) && $this->matches_url_patterns($this->get_home_path(), $page_rules['url_patterns'])) { return true; } $front_page = 'page' === get_option('show_on_front') ? (int) get_option('page_on_front') : 0; return $front_page > 0 && $this->post_matches_term_rules($front_page, $page_rules); } /** * Check if the current page should have the script */ private function should_enable_on_current_page() { $page_rules = $this->get_page_rules(); // All pages option is enabled if (isset($page_rules['all_pages']) && $page_rules['all_pages'] === 'yes') { return true; } // Check URL patterns if (!empty($page_rules['url_patterns'])) { $current_url = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : ''; if (empty($current_url)) { return false; } if ($this->matches_url_patterns($current_url, $page_rules['url_patterns'])) { return true; } } // Check categories and tags if (is_singular()) { global $post; if ($this->post_matches_term_rules($post->ID, $page_rules)) { return true; } } // Check category archive pages if (is_category() && !empty($page_rules['categories'])) { $category = get_queried_object_id(); if (in_array($category, $page_rules['categories'])) { return true; } } // Check tag archive pages if (is_tag() && !empty($page_rules['tags'])) { $tag = get_queried_object_id(); if (in_array($tag, $page_rules['tags'])) { return true; } } return false; } /** * Get the script sources from API with caching */ private function get_script_sources() { $cache_key = 'ad_unblock_script_sources_' . get_current_blog_id(); $error_cache_key = $cache_key . '_error'; // Get cached data and check if it's valid $cached_data = get_transient($cache_key); $is_cache_valid = $this->is_cache_data_valid($cached_data); $is_in_error_state = $this->is_in_error_state($error_cache_key); // Return valid cache if not in error state if ($is_cache_valid && !$is_in_error_state) { return $cached_data['data']; } // Try to fetch fresh data from API $fresh_data = $this->fetch_script_sources_from_api(); // If API call succeeded, update cache and return fresh data if (false !== $fresh_data) { $this->refresh_script_sources_cache($cache_key, $error_cache_key, $fresh_data); return $fresh_data; } // API failed - set error state $this->set_error_state($error_cache_key); // Return stale cache if available, otherwise empty array if ($cached_data && isset($cached_data['data']) && is_array($cached_data['data'])) { return $cached_data['data']; } return array(); } /** * Check if cached data is valid and not expired */ private function is_cache_data_valid($cached_data) { return false !== $cached_data && is_array($cached_data) && isset($cached_data['timestamp'], $cached_data['data']) && is_array($cached_data['data']) && !empty($cached_data['data']) && $this->cache_matches_request($cached_data) && (time() - $cached_data['timestamp']) < self::CACHE_DURATION; } /** * Check that cached data was fetched for the request we would make now * * A changed domain, endpoint or site address has to re-fetch rather than * keep serving another request's script list. Entries written before the * domain parameter existed carry no request URL and so never match, which * refreshes them once on upgrade. */ private function cache_matches_request($cached_data) { $cached_url = isset($cached_data['request_url']) ? $cached_data['request_url'] : ''; return $cached_url === $this->get_api_request_url(); } /** * Check if we're currently in an error state */ private function is_in_error_state($error_cache_key) { $error_data = get_transient($error_cache_key); if (false === $error_data || !is_array($error_data) || !isset($error_data['timestamp'])) { return false; } // Consider error state active for 60 seconds return (time() - $error_data['timestamp']) < 60; } /** * Reduce any host-bearing string to a bare hostname * * Mirrors the normalization the API applies to the domain it receives: * lowercase, no scheme, userinfo, port, path or trailing dot. Anything * that is not left looking like a hostname returns an empty string. */ private function normalize_domain($value) { if (!is_string($value)) { return ''; } $host = strtolower(trim($value)); if ('' === $host) { return ''; } $scheme_end = strpos($host, '://'); if (false !== $scheme_end) { $host = substr($host, $scheme_end + 3); } // Path, query and fragment. $host = preg_split('#[/?\#]#', $host)[0]; // Userinfo, then port. $at = strrpos($host, '@'); if (false !== $at) { $host = substr($host, $at + 1); } $colon = strpos($host, ':'); if (false !== $colon) { $host = substr($host, 0, $colon); } $host = rtrim($host, '.'); // An internationalized domain has to travel as punycode, because that // is the form the API's per-domain lists are keyed on. if (preg_match('/[^\x20-\x7e]/', $host) && function_exists('idn_to_ascii')) { $ascii = idn_to_ascii($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46); if (is_string($ascii) && '' !== $ascii) { $host = strtolower($ascii); } } return preg_match('/^[a-z0-9][a-z0-9.-]*$/', $host) ? $host : ''; } /** * The domain of this WordPress site, from its configured site address */ private function get_default_site_domain() { $domain = $this->normalize_domain(wp_parse_url(home_url(), PHP_URL_HOST)); if ('' === $domain && isset($_SERVER['HTTP_HOST'])) { $domain = $this->normalize_domain(sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST']))); } return $domain; } /** * The domain sent to the API, configured or auto-detected */ private function get_site_domain() { $configured = $this->normalize_domain(get_option('ad_unblock_site_domain', '')); return '' !== $configured ? $configured : $this->get_default_site_domain(); } /** * The path of this site's home page: "/" unless WordPress lives in a * subdirectory ("/blog/"), which is also what a multisite subsite in a * subdirectory has */ private function get_home_path() { $path = wp_parse_url(home_url('/'), PHP_URL_PATH); return is_string($path) && '' !== $path ? $path : '/'; } /** * Whether this site's home page is somewhere below the top of its domain * * Ad Unblock looks for the tag at the top of the domain when it is given * only a domain, which is all Connect and the verification check send. * Such a site is found once it is added with its full address. */ private function is_home_in_subdirectory() { return '/' !== $this->get_home_path(); } /** * The address of this site's home page, for Ad Unblock to load * * The site address itself, unless a Site Domain says the site is reached * from the internet under another name: then the same path on that one. */ private function get_home_page_url() { $domain = $this->get_site_domain(); if ($domain === $this->get_default_site_domain()) { return home_url('/'); } return 'https://' . $domain . $this->get_home_path(); } /** * Get the API endpoint to use (custom or default) */ private function get_api_endpoint() { $custom_endpoint = get_option('ad_unblock_custom_api_endpoint', ''); return !empty($custom_endpoint) ? $custom_endpoint : self::API_ENDPOINT; } /** * Build the API request URL for this site * * The `domain` parameter tells the service which site is asking, so it can * answer with a script host reserved for this domain when a filter list has * blocked the shared one for it. A request without the parameter still gets * the default list, so an empty domain is not an error. */ private function get_api_request_url() { $api_endpoint = $this->get_api_endpoint(); $domain = $this->get_site_domain(); if ('' === $domain) { return $api_endpoint; } // Passed unencoded: normalize_domain() has already restricted the value // to characters that are literal in a query string, and add_query_arg() // does not encode what it is given. return add_query_arg('domain', $domain, $api_endpoint); } /** * Fetch script sources from API */ private function fetch_script_sources_from_api() { $response = wp_remote_get($this->get_api_request_url(), array('timeout' => 10)); if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) { return false; } $body = wp_remote_retrieve_body($response); if (empty($body)) { return false; } $script_sources = json_decode($body, true); // Validate JSON structure and content if (!is_array($script_sources) || empty($script_sources)) { return false; } // Additional validation: ensure all items are strings (URLs) foreach ($script_sources as $source) { if (!is_string($source) || empty($source)) { return false; } } return $script_sources; } /** * Refresh script sources cache with fresh data and clear error state */ private function refresh_script_sources_cache($cache_key, $error_cache_key, $script_sources) { // Clear error state since we have fresh data delete_transient($error_cache_key); // Store fresh data with timestamp $cache_data = array( 'data' => $script_sources, 'timestamp' => time(), 'request_url' => $this->get_api_request_url() ); set_transient($cache_key, $cache_data, WEEK_IN_SECONDS); } /** * Set error state with timestamp */ private function set_error_state($error_cache_key) { $error_data = array( 'timestamp' => time() ); set_transient($error_cache_key, $error_data, HOUR_IN_SECONDS); } /** * Insert the script into the page head */ public function insert_script() { $verification_code = get_option('ad_unblock_verification_code', ''); if (empty($verification_code) || !$this->should_enable_on_current_page()) { return; } $script_sources = $this->get_script_sources(); if (empty($script_sources) || !is_array($script_sources)) { return; } // Get the first script source only $script_url = reset($script_sources); // Get cache status and full cached data for meta tag $cache_status = $this->get_cache_status(); $cache_key = 'ad_unblock_script_sources_' . get_current_blog_id(); $cached_data = get_transient($cache_key); // Prepare cache details for meta tag $cache_details = array( 'verification' => $verification_code, 'domain' => $this->get_site_domain(), 'cache_active' => $cache_status['has_cache'] ? 'true' : 'false', 'error_state' => $cache_status['has_error'] ? 'true' : 'false', 'sources_count' => $cache_status['cache_data_count'], 'expires_in' => $cache_status['time_until_expiry'], 'timestamp' => time(), 'cached_sources' => $script_sources, 'cache_timestamp' => (false !== $cached_data && is_array($cached_data) && isset($cached_data['timestamp'])) ? $cached_data['timestamp'] : null ); // Add verification code and cache details as a meta tag in DOM echo '' . "\n"; echo '' . "\n"; // Printed directly rather than enqueued, for three reasons: // // 1. wp_enqueue_script() cannot emit a valueless attribute, and it // always builds the tag with `src` first — Cloudflare only honours // `data-cfasync` when it appears BEFORE `src`. // 2. Enqueued head scripts print at wp_head priority 9, after styles. // This runs at priority 0, so recovery loads ahead of the ad code. // 3. The `strategy` argument is WP 6.3+; on older WP that array is a // truthy $in_footer and the tag would land in the footer. // // The two attributes opt the tag out of Cloudflare Rocket Loader and // WP Rocket's Delay JavaScript Execution, both of which would defer or // rewrite it. Neither covers WP Rocket's separate "Load JavaScript // deferred" option — that one has no attribute, and needs the script // URL in its Excluded JavaScript Files list. // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript echo '' . "\n"; } /** * Enqueue admin styles and scripts */ public function enqueue_admin_assets($hook) { if ('settings_page_ad-unblock' !== $hook) { return; } wp_enqueue_style( 'ad-unblock-admin', plugin_dir_url(__FILE__) . 'assets/css/admin.css', array(), AD_UNBLOCK_VERSION ); // Enqueue Select2 wp_enqueue_style( 'ad-unblock-select2-css', plugin_dir_url(__FILE__) . 'assets/css/admin-select2.css' ); wp_enqueue_script( 'ad-unblock-select2-js', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), null, true ); wp_enqueue_style( 'select2-css', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css' ); wp_enqueue_script( 'ad-unblock-admin-js', plugin_dir_url(__FILE__) . 'assets/js/admin.js', array('jquery', 'ad-unblock-select2-js'), AD_UNBLOCK_VERSION, true ); wp_localize_script('ad-unblock-admin-js', 'adUnblock', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ad-unblock-admin-nonce'), 'auto_verify' => $this->take_verify_on_load(), 'i18n' => array( 'checking' => __('Checking your site…', 'ad-unblock'), 'verified' => __('Verified. Ad Unblock found the tag on this site.', 'ad-unblock'), 'unverified' => __('Not verified yet. Ad Unblock did not find this site, with its tag, in your account.', 'ad-unblock'), 'error' => __('Could not reach Ad Unblock to check. Try again in a minute.', 'ad-unblock'), 'confirm_disconnect' => __('Disconnect this site from Ad Unblock? The tag is no longer added to your pages, so ad recovery stops. Your other settings are saved as they are now.', 'ad-unblock'), ), )); } /** * AJAX handler to search for terms (categories, tags) */ public function ajax_search_terms() { check_ajax_referer('ad-unblock-admin-nonce', 'nonce'); $search = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : ''; $taxonomy = isset($_GET['taxonomy']) ? sanitize_text_field(wp_unslash($_GET['taxonomy'])) : 'category'; if (!taxonomy_exists($taxonomy)) { wp_send_json_error(array('message' => 'Invalid taxonomy.')); } $terms = get_terms(array( 'taxonomy' => $taxonomy, 'name__like' => $search, 'hide_empty' => false, 'number' => 20, )); $results = array(); if (!is_wp_error($terms) && !empty($terms)) { foreach ($terms as $term) { $results[] = array( 'id' => $term->term_id, 'text' => $term->name, ); } } wp_send_json_success($results); } /** * Get cache status information */ private function get_cache_status() { $cache_key = 'ad_unblock_script_sources_' . get_current_blog_id(); $error_cache_key = $cache_key . '_error'; $cached_data = get_transient($cache_key); $error_data = get_transient($error_cache_key); $has_cache = false; $cache_timestamp = null; $cache_data_count = 0; $time_until_expiry = 0; $cache_expires = null; // Check if we have valid cached data with timestamp if (false !== $cached_data && is_array($cached_data) && isset($cached_data['timestamp'], $cached_data['data'])) { $has_cache = true; $cache_timestamp = $cached_data['timestamp']; $cache_data_count = is_array($cached_data['data']) ? count($cached_data['data']) : 0; $cache_expiry_time = $cache_timestamp + self::CACHE_DURATION; $time_until_expiry = max(0, $cache_expiry_time - time()); $cache_expires = $cache_expiry_time; } // Check error state - only consider recent errors (within 60 seconds) $has_error = false; if (false !== $error_data && is_array($error_data) && isset($error_data['timestamp'])) { $has_error = (time() - $error_data['timestamp']) < 60; } return array( 'has_cache' => $has_cache, 'has_error' => $has_error, 'cache_expires' => $cache_expires, 'cache_data_count' => $cache_data_count, 'time_until_expiry' => $time_until_expiry ); } /** * The saved Account ID */ private function get_account_id() { return trim((string) get_option('ad_unblock_verification_code', '')); } /** * Whether a value has the shape of an Account ID: 8 digits */ private function is_account_id($value) { return is_string($value) && 1 === preg_match('/^\d{8}$/', $value); } /** * The Ad Unblock dashboard's address */ private function get_app_url() { $url = defined('AD_UNBLOCK_APP_URL') ? (string) AD_UNBLOCK_APP_URL : self::APP_URL; return untrailingslashit($url); } /** * This plugin's settings page */ private function get_settings_url() { return admin_url('options-general.php?page=ad-unblock'); } /** * Whether Ad Unblock could reach a domain from the internet * * The dashboard has the final say (it checks the public suffix list). This * only keeps the plain cases from being offered a Connect that would end * in an error there: no dot (localhost), an IP address, or a name reserved * for local use. */ private function is_public_domain($domain) { if (!is_string($domain) || '' === $domain || false === strpos($domain, '.')) { return false; } if (false !== filter_var($domain, FILTER_VALIDATE_IP)) { return false; } $tld = substr(strrchr($domain, '.'), 1); return !in_array($tld, array('local', 'localhost', 'test', 'invalid', 'example', 'internal', 'lan'), true); } /** * Whether this site can be connected and verified through the dashboard */ private function can_connect() { return $this->is_public_domain($this->get_site_domain()); } /** * Where "Connect" sends the admin * * `site` is the domain this site already reports to the script source API, * `return` is this settings page, and `state` is a nonce: the dashboard * hands it back with the Account ID, and handle_connect_return() only * saves an ID that arrives with it. `v` lets the dashboard tell plugin * versions apart if this exchange ever changes. */ private function get_connect_url() { return add_query_arg( array( 'site' => rawurlencode($this->get_site_domain()), 'return' => rawurlencode($this->get_settings_url()), 'state' => wp_create_nonce(self::CONNECT_NONCE_ACTION), 'v' => rawurlencode(AD_UNBLOCK_VERSION), ), $this->get_app_url() . '/connect/wordpress' ); } /** * An account's sites in the dashboard, with the Add Site form open on a * site when one is given * * `$site` is a domain, or a full address: the dashboard looks for the tag * at the top of a domain, and on the very page of an address. */ private function get_add_site_url($account_id, $site = '') { $url = $this->get_app_url() . '/dashboard/' . rawurlencode($account_id) . '/sites'; return '' === $site ? $url : $url . '?add=' . rawurlencode($site); } /** * Save the Account ID the dashboard sends back after "Connect" * * The admin lands on this settings page with `ad_unblock_account` and * `ad_unblock_state` in the URL. The Account ID is not a secret (it is in * the page source of every site that uses it), so the nonce is not hiding * anything: it proves this admin started the connection from this login. * Without it, a link could set someone else's Account ID on this site, * and that account could then claim the site as its own. * * Always ends in a redirect to the clean settings URL, so the ID and nonce * do not stay in the address bar and a reload does nothing. */ public function handle_connect_return() { // The nonce is verified below, as the request's `state`. // phpcs:disable WordPress.Security.NonceVerification.Recommended if (!isset($_GET['page'], $_GET['ad_unblock_account'])) { return; } if ('ad-unblock' !== sanitize_key(wp_unslash($_GET['page'])) || !current_user_can('manage_options')) { return; } $account_id = sanitize_text_field(wp_unslash($_GET['ad_unblock_account'])); $state = isset($_GET['ad_unblock_state']) ? sanitize_text_field(wp_unslash($_GET['ad_unblock_state'])) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended if (!wp_verify_nonce($state, self::CONNECT_NONCE_ACTION)) { $result = 'expired'; } elseif (!$this->is_account_id($account_id)) { $result = 'invalid'; } else { update_option('ad_unblock_verification_code', $account_id); // Connecting again to the account already saved changes nothing, // so the option's own hook would not ask for a check. set_transient(self::VERIFY_ON_LOAD_TRANSIENT, 1, 10 * MINUTE_IN_SECONDS); $result = 'connected'; } // The result waits for the settings page in a transient, not in the // URL: options.php sends the admin back to the address the form was // loaded from, so a parameter there would come back with every later // save and show its notice again. set_transient(self::CONNECT_RESULT_TRANSIENT . get_current_user_id(), $result, MINUTE_IN_SECONDS); wp_safe_redirect($this->get_settings_url()); exit; } /** * The Account ID was saved for the first time */ public function on_account_id_added($option, $value) { $this->on_account_id_changed($value); } /** * The Account ID was changed */ public function on_account_id_updated($old_value, $value) { $this->on_account_id_changed($value); } /** * Forget what was known about the old Account ID, and have the settings * page check the new one once when it next loads: whoever saved it, * through Connect or by hand, is installing the plugin now. */ private function on_account_id_changed($value) { delete_option(self::VERIFIED_OPTION); if ($this->is_account_id(trim((string) $value))) { set_transient(self::VERIFY_ON_LOAD_TRANSIENT, 1, 10 * MINUTE_IN_SECONDS); } else { delete_transient(self::VERIFY_ON_LOAD_TRANSIENT); } } /** * Whether the settings page should check verification by itself, once */ private function take_verify_on_load() { if (!get_transient(self::VERIFY_ON_LOAD_TRANSIENT)) { return false; } delete_transient(self::VERIFY_ON_LOAD_TRANSIENT); return $this->is_account_id($this->get_account_id()) && $this->can_connect(); } /** * Whether the dashboard has verified this site for the saved Account ID * * Remembered from the last check that said so, for this account and * domain only: changing either forgets it. */ private function is_verified() { $verified = get_option(self::VERIFIED_OPTION); return is_array($verified) && isset($verified['account'], $verified['domain']) && $verified['account'] === $this->get_account_id() && $verified['domain'] === $this->get_site_domain(); } /** * Ask the dashboard whether this site is verified for the saved Account ID * * A site still waiting for its tag is checked again by the dashboard * before it answers, so this is also what gets a newly connected site * verified. Sends the site domain and the Account ID, both of which are * public on the site itself. * * @return bool|WP_Error Verified or not, or why the question went unanswered. */ private function check_verification() { $account_id = $this->get_account_id(); $domain = $this->get_site_domain(); if (!$this->is_account_id($account_id) || !$this->is_public_domain($domain)) { return new WP_Error('ad_unblock_cannot_verify', 'This site cannot be verified.'); } // The dashboard loads this site's pages before answering: up to four // loads of 10 seconds each, then a query of up to 10 more. The wait // has to outlast that, or a slow site is told the check could not be // made when it was only still running. $response = wp_remote_post($this->get_app_url() . '/api/sites/verify', array( 'timeout' => 55, 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', ), 'body' => wp_json_encode(array( 'domain' => $domain, 'account_id' => $account_id, )), )); if (is_wp_error($response)) { return $response; } $data = json_decode(wp_remote_retrieve_body($response), true); if (200 !== wp_remote_retrieve_response_code($response) || !is_array($data) || !isset($data['verified']) || !is_bool($data['verified'])) { return new WP_Error('ad_unblock_verify_failed', 'Unexpected answer from the verification check.'); } if ($data['verified']) { update_option(self::VERIFIED_OPTION, array( 'account' => $account_id, 'domain' => $domain, 'time' => time(), ), false); } else { delete_option(self::VERIFIED_OPTION); } return $data['verified']; } /** * AJAX handler for "Check verification" */ public function ajax_check_verification() { check_ajax_referer('ad-unblock-admin-nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => 'Insufficient permissions.'), 403); } $verified = $this->check_verification(); if (is_wp_error($verified)) { wp_send_json_error(array('message' => 'The verification check did not complete.')); } wp_send_json_success(array('verified' => $verified)); } /** * Add settings link to plugin actions */ public function add_plugin_action_links($links) { $settings_link = '' . esc_html__('Settings', 'ad-unblock') . ''; array_unshift($links, $settings_link); return $links; } /** * Add additional links to plugin row meta */ public function add_plugin_row_meta($links, $file) { if (plugin_basename(__FILE__) === $file) { $row_meta = array( 'docs' => '' . esc_html__('Documentation', 'ad-unblock') . '', 'support' => '' . esc_html__('Support', 'ad-unblock') . '', ); return array_merge($links, $row_meta); } return $links; } } // Initialize the plugin Ad_Unblock::get_instance();