output_to_console('Frontend instance created'); } else { self::$instance->output_to_console('Frontend instance reused'); } return self::$instance; } public function __construct($role = null) { // get/set all settings $allSettings = $this->get_wuadblockguard_settings(); $this->settings = $allSettings; // get mode if ($role === null) { $this->output_to_console('Frontend Mode Enabled'); $this->runModeFrontend(); } else { $this->output_to_console('Demo Mode Enabled'); $this->mode = 'demo'; $this->role = $role; $this->runModeDemo(); } } private function runModeFrontend () { if ($this->isEnabled()) { // set the role $this->role = $this->getRole(); $this->output_to_console("Got role: {$this->role}"); // if we have an enabled user role overlay if ($this->isUserOverlayEnabled($this->role)) { $this->output_to_console(strtoupper($this->role) . ' role overlay is enabled'); // role overlay settings (also in allSettings) $roleSettings = $this->getUserGroupSettings($this->role); $this->output_to_console('roleSettings: ('.count($roleSettings).')'); // render the AdBlock $this->renderAdBlock(); } else { $this->output_to_console($this->role . ' is NOT Enabled'); } } else { $this->output_to_console('AdBlock Guard is DISABLED'); } } /* Skip checks for demo mode */ private function runModeDemo() { $this->output_to_console("Demo role: {$this->role}"); // role overlay settings (also in allSettings) $roleSettings = $this->getUserGroupSettings($this->role); $this->output_to_console($roleSettings); $AdBlock = new AdBlockExtended($this->isDebug()); $AdBlock->setRole($this->role); $AdBlock->setSettings($this->data); $AdBlock->setIsDemo(true); $AdBlock->initialize(); $this->script = $AdBlock->getLiveAdBlockSourceForAdminDemo(); // Render the JavaScript in the footer add_action('admin_footer', [$this, 'render_footer_content'], 999); } private function renderAdBlock() { if ($this->isRenderable()) { $this->output_to_console('renderAdBlock() is a go with isRenderable()'); $AdBlock = new AdBlockExtended($this->isDebug()); $AdBlock->setRole($this->role); $AdBlock->setSettings($this->data); $AdBlock->initialize(); $this->script = $AdBlock->getLatestAdBlockSource(); $this->output_to_console('AdBlock Overlay should be visible'); // Render the JavaScript in the footer add_action('wp_footer', [$this, 'render_footer_content'], 999); } else { $this->output_to_console('renderAdBlock() IS NOT isRenderable()'); } } public function outputDebug () { if (!WUADBLOCKGUARD_CACHING) { $this->output_to_console("\t" . 'Cache disabled: !WUADBLOCKGUARD_CACHING'); } else { $this->output_to_console("\t" . 'WP cache enabled'); } } public function render_footer_content() { if (!$this->isEnabled() && $this->mode === 'frontend') { $this->output_to_console('render_footer_content: AdBlock Guard is not enabled'); return; } if (!empty($this->script)) { /* * WordPress Reviewers: Safe Direct Output Justification * * The following script is output directly as it has been thoroughly sanitized and is safe. * * Note: WP Plugin Check may flag this as a potential security risk, but it is essential for the plugin's functionality. * Given these factors, direct output is justified and necessary for proper operation. * * *Important for Reviewers:* * * Enabling `AD_BLOCK_GUARD_DEBUG` to `true` in the main plugin file will allow you to review the code * without packing and obfuscation. * * Packing and obfuscation are necessary to prevent ad-block extensions from easily identifying and blocking * the features provided by this plugin. Without these measures, the purpose of this plugin would be defeated, * as ad-blockers could easily circumvent the protections it provides sitewide. * * Important Details: * * 1. All user input originates from the WordPress admin area (`is_admin()`) and is managed using Carbon Fields. * 2. Every input is properly sanitized and escaped before being used. * 3. This plugin does not process or utilize any front-end user input; all operations are strictly handled by the admin. * 4. The JavaScript being output here is statically defined and stored in the plugin’s source file at: * /plugins/ad-block-guard/src/js/code-wp-1.js * */ echo $this->script; } } // this queries wp directly for this setting (no cache) public function isEnabled() { // Retrieve the option from the WordPress database $enabled_value = get_option('_wuadblockguard_enable'); // Use the helper function to determine if it's enabled return $this->is_checkbox_checked($enabled_value); } // this queries wp directly for this setting (no cache) public function isDebug() { return WUADBLOCKGUARD_DEBUG; } public function is_checkbox_checked($value) { return $value === 'yes'; } public function getRole() { // Check if the user is logged in if (is_user_logged_in()) { // Get the current user object $user = wp_get_current_user(); // Get the user's roles $roles = $user->roles; // Return the first role if available if (!empty($roles)) { return $roles[0]; // Assuming the user has one primary role } } // Return 'guest' if the user is not logged in or no role found return 'guest'; } public function getUserGroupSettings($role) { // Get the settings array $settings = $this->get_wuadblockguard_settings(); // Check if usergroup_settings exists and is an array if (isset($settings['usergroup_settings']) && is_array($settings['usergroup_settings'])) { foreach ($settings['usergroup_settings'] as $group) { // Check if the usergroup matches the role provided if (isset($group['usergroup']) && $group['usergroup'] === $role) { // Simplify checkboxes $checkboxFields = ['overlay_enabled', 'allow_close', 'allow_scroll']; foreach ($checkboxFields as $field) { if (isset($group[$field])) { // Handle boolean, numeric, and string representations $group[$field] = in_array($group[$field], [true, 'yes', 1, '1'], true); } else { $group[$field] = false; } } // Simplify other fields except buttons foreach ($group as $key => $value) { if ($key !== 'buttons' && isset($value[0]['value'])) { $group[$key] = $value[0]['value']; } } // Simplify buttons if (isset($group['buttons']) && is_array($group['buttons'])) { foreach ($group['buttons'] as &$button) { if (isset($button['link'][0])) { $button['link'] = $button['link'][0]; } if (isset($button['background_color'][0]['value'])) { $button['background_color'] = $button['background_color'][0]['value']; } if (isset($button['foreground_color'][0]['value'])) { $button['foreground_color'] = $button['foreground_color'][0]['value']; } } } // Return the simplified group settings return $group; } } } return null; // Return null if no match found } public function getUserOverlaySettings($role) { // Get the specific user group settings return $this->getUserGroupSettings($role); } public function isUserOverlayEnabled($role) { // Get the specific user group settings $groupSettings = $this->getUserGroupSettings($role); // Debugging: Output groupSettings $this->output_to_console("Group Settings for role '{$role}':"); $this->output_to_console($groupSettings); // Check if the overlay is enabled if (isset($groupSettings['overlay_enabled']) && $groupSettings['overlay_enabled'] === true) { return true; } return false; } public function get_wuadblockguard_settings() { // Check if the data is already stored in $this->data if (!empty($this->data)) { $this->output_to_console("\t" . 'Retrieving from instance cache'); return $this->data; } // Attempt to retrieve settings from WP cache $settings = get_transient(CarbonFieldsSetup::CACHE_KEY); if ($settings && WUADBLOCKGUARD_CACHING) { $this->data = $settings; $this->output_to_console("\t" . 'Retrieving data from WP cache'); } else { // If cache is empty, fetch data from the database $options = [ 'enable', 'fast_detection', 'remote_detection', 'network_detection', 'usergroup_settings', 'hide_from_crawlers', 'prevent_masquerading', 'live_easylist', 'easylist_url', 'ignore_pages', 'debug', 'pro_license_key' ]; $settings = []; foreach ($options as $option) { $full_option_name = '_wuadblockguard_' . $option; $value = get_option($full_option_name); if ($option === 'usergroup_settings') { $unserialized_value = maybe_unserialize($value); $settings[$option] = is_array($unserialized_value) ? $unserialized_value : false; } elseif (in_array($option, ['easylist_url', 'pro_license_key'])) { $settings[$option] = $value; } else { $settings[$option] = $this->is_checkbox_checked($value); } } // Store the settings in WP cache set_transient(CarbonFieldsSetup::CACHE_KEY, $settings, 12 * HOUR_IN_SECONDS); // Store the settings in $this->data $this->data = $settings; // Log to console that the settings have been cached if (!$this->isDebug()) $this->output_to_console('Cache saved from WP'); } return $this->data; } public function isRenderable() { // Exclude special pages if (!$this->canRenderOnSpecialPages()) { $this->output_to_console('EXCLUDED by canRenderOnSpecialPages()'); return false; } // Exclude pages if (!$this->canRenderOnExcludedPages()) { $this->output_to_console('EXCLUDED by canRenderOnExcludedPages()'); return false; } // Exclude posts (categories/tags) if (!$this->canRenderOnExcludedPosts()) { $this->output_to_console('EXCLUDED by canRenderOnExcludedPosts()'); return false; } // Check if the current URL is in the ignored list if (!$this->canRenderOnIgnoredUrls()) { $this->output_to_console('EXCLUDED by canRenderOnIgnoredUrls()'); return false; } // Check if the WooCommerce exclusion logic allows rendering if (!$this->canRenderOnWooCommercePages()) { $this->output_to_console('EXCLUDED by canRenderOnWooCommercePages()'); return false; } // Additional conditions can be added here, e.g., checking for other types of pages or custom logic. // Default to rendering if none of the conditions block it return true; } private function getCurrentRelativePath() { // Parse the current URL $parsedUrl = wp_parse_url($_SERVER['REQUEST_URI']); $currentPath = isset($parsedUrl['path']) ? rtrim($parsedUrl['path'], '/') : '/'; return $currentPath; } private function isPathMatchingPattern($currentPath, $pattern) { // Escape special regex characters except for '*' $regex = '/^' . str_replace( ['\*', '/\*/'], // Replace '*' and '/*' for wildcard flexibility ['.*', '(.*\/)?'], // '*' matches anything; '/*' matches subdirectories preg_quote($pattern, '/') ) . '$/'; return preg_match($regex, $currentPath); } private function canRenderOnIgnoredUrls() { $ignoredUrls = get_option('_wuadblockguard_ignore_urls', ''); if (empty($ignoredUrls)) { return true; } // Normalize ignored patterns: trim, ensure leading slash, and remove trailing slash $urlPatterns = array_filter(array_map(function($line) { $trimmed = trim($line); if ($trimmed) { $normalized = strpos($trimmed, '/') === 0 ? $trimmed : '/' . $trimmed; return rtrim($normalized, '/'); // Remove trailing slash for consistency } return null; }, explode("\n", $ignoredUrls))); if (empty($urlPatterns)) { return true; } $currentPath = rtrim($this->getCurrentRelativePath(), '/'); // Ensure current path also has no trailing slash foreach ($urlPatterns as $pattern) { if ($this->isPathMatchingPattern($currentPath, $pattern)) { return false; } } return true; } private function canRenderOnExcludedPages() { if (get_option('_wuadblockguard_exclude_pages_check', 'no') !== 'yes') { return true; } $excludedPages = get_option('_wuadblockguard_exclude_pages', []); $excludedPageIds = array_filter(array_column($excludedPages, 'value'), 'is_numeric'); if (in_array(get_the_ID(), $excludedPageIds)) { return false; } return true; } private function canRenderOnExcludedPosts() { if (get_option('_wuadblockguard_exclude_posts', 'no') !== 'yes') { return true; } $excludedCategories = array_filter(array_column(get_option('_wuadblockguard_exclude_categories', []), 'value'), 'is_numeric'); $excludedTags = array_filter(array_column(get_option('_wuadblockguard_exclude_tags', []), 'value'), 'is_numeric'); $currentPostId = get_the_ID(); if (!$currentPostId || get_post_type($currentPostId) !== 'post') { return true; } $postCategories = wp_get_post_categories($currentPostId); $postTags = wp_get_post_tags($currentPostId, ['fields' => 'ids']); return !array_intersect($postCategories, $excludedCategories) && !array_intersect($postTags, $excludedTags); } private function canRenderOnWooCommercePages() { // Check if the exclusion option is enabled for WooCommerce pages $excludeWooCommerce = get_option('_wuadblockguard_exclude_woocommerce', 'no'); if ($excludeWooCommerce === 'yes') { // Get the selected WooCommerce pages to exclude $excludedWooCommercePages = get_option('_wuadblockguard_exclude_woocommerce_pages', []); // Check if the array is empty if (empty($excludedWooCommercePages)) { return true; // No pages excluded, allow rendering } // Iterate over the array to check the current page type foreach ($excludedWooCommercePages as $page) { if (isset($page['value']) && $this->isCurrentWooCommercePageTypeExcluded($page['value'])) { return false; // Block rendering if the current WooCommerce page type is excluded } } } // Allow rendering if no exclusions apply return true; } private function isCurrentWooCommercePageTypeExcluded($pageType) { switch ($pageType) { case 'is_shop': return is_shop(); case 'is_product_category': return is_product_category(); case 'is_product_tag': return is_product_tag(); case 'is_product': return is_product(); case 'is_cart': return is_cart(); case 'is_checkout': return is_checkout(); case 'is_account_page': return is_account_page(); case 'is_order_received_page': return is_order_received_page(); default: return false; } } private function canRenderOnSpecialPages() { // Check if the exclusion option for special pages is enabled $excludeSpecialPagesCheck = get_option('_wuadblockguard_exclude_special_pages_check', 'no'); if ($excludeSpecialPagesCheck === 'yes') { $excludedPages = get_option('_wuadblockguard_exclude_special_pages', []); if (!empty($excludedPages)) { foreach ($excludedPages as $excludedPage) { $pageType = isset($excludedPage['value']) ? $excludedPage['value'] : ''; if ($this->isCurrentPageTypeExcluded($pageType)) { return false; // Block rendering if the current page type is excluded } } } } return true; // Allow rendering if no exclusions apply } private function isCurrentPageTypeExcluded($pageType) { switch ($pageType) { case 'is_singular': return is_singular(); case 'is_page': return is_page(); case 'is_single': return is_single(); case 'is_front_page': // Exclude the homepage regardless of whether it's a static page or blog posts index return is_front_page() || is_home(); case 'is_home': return is_home(); case 'is_archive': return is_archive(); case 'is_category': return is_category(); case 'is_tag': return is_tag(); case 'is_tax': return is_tax(); case 'is_search': return is_search(); case 'is_404': return is_404(); case 'login_page': return $this->isLoginPage(); case 'registration_page': return $this->isRegistrationPage(); default: return false; } } private function isLoginPage() { return $GLOBALS['pagenow'] === 'wp-login.php'; } private function isRegistrationPage() { return isset($_GET['action']) && $_GET['action'] === 'register'; } public function output_to_console($data) { if (WUADBLOCKGUARD_CONSOLE_LOG) { echo ''; } } }