'sanitize_text_field',
'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__('Verification Code', '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_custom_api_endpoint',
esc_html__('API Endpoint', 'ad-unblock'),
array($this, 'render_custom_api_endpoint_field'),
'ad_unblock',
'ad_unblock_section_main'
);
}
/**
* 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_cache_status(); ?>
';
echo '' . esc_html__('Configure your Ad Unblock integration settings below.', 'ad-unblock') . '
';
echo '';
}
/**
* Render verification code field
*/
public function render_verification_code_field()
{
$verification_code = get_option('ad_unblock_verification_code', '');
?>
'yes',
'url_patterns' => '',
'categories' => array(),
'tags' => array(),
));
?>
get_cache_status();
?>
✓
⚠
⚠
✓
(server time)
(s remaining)
'yes',
'url_patterns' => '',
'categories' => array(),
'tags' => array(),
));
// 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;
}
$patterns = explode("\n", $page_rules['url_patterns']);
foreach ($patterns as $pattern) {
$pattern = trim($pattern);
if (empty($pattern)) {
continue;
}
// Convert wildcard pattern to regex
$regex = str_replace(
array('\*', '/'),
array('.*', '\/'),
preg_quote($pattern, '/')
);
if (preg_match('/^' . $regex . '/i', $current_url)) {
return true;
}
}
}
// Check categories and tags
if (is_singular()) {
global $post;
// 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;
}
}
}
}
// 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']) &&
(time() - $cached_data['timestamp']) < self::CACHE_DURATION;
}
/**
* 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;
}
/**
* 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;
}
/**
* Fetch script sources from API
*/
private function fetch_script_sources_from_api()
{
$api_endpoint = $this->get_api_endpoint();
$response = wp_remote_get($api_endpoint, 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()
);
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,
'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";
// Enqueue the single script
wp_enqueue_script(
'ad-unblock-script',
esc_url($script_url),
array(),
null,
array('strategy' => 'async')
);
}
/**
* 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'),
'cache_status' => $this->get_cache_status()
));
}
/**
* 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);
}
/**
* AJAX handler to clear script cache
*/
public function ajax_clear_cache()
{
check_ajax_referer('ad-unblock-admin-nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => 'Insufficient permissions.'));
}
$this->clear_script_cache();
wp_send_json_success(array(
'message' => 'Cache cleared successfully.',
'cache_status' => $this->get_cache_status()
));
}
/**
* AJAX handler to get current cache status
*/
public function ajax_get_cache_status()
{
check_ajax_referer('ad-unblock-admin-nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => 'Insufficient permissions.'));
}
wp_send_json_success(array(
'cache_status' => $this->get_cache_status()
));
}
/**
* Clear the script cache
*/
public function clear_script_cache()
{
$cache_key = 'ad_unblock_script_sources_' . get_current_blog_id();
$error_cache_key = $cache_key . '_error';
delete_transient($cache_key);
delete_transient($error_cache_key);
}
/**
* 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
);
}
/**
* 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();