plugin_name = $plugin_name; } public function get_table_name($key) { global $wpdb; $map = array( 'journeys' => $wpdb->prefix . 'daau_journeys', 'steps' => $wpdb->prefix . 'daau_journey_steps', 'rules' => $wpdb->prefix . 'daau_targeting_rules', 'experiments' => $wpdb->prefix . 'daau_experiments', 'variants' => $wpdb->prefix . 'daau_variants', 'events' => $wpdb->prefix . 'daau_recovery_events', ); return isset($map[$key]) ? $map[$key] : ''; } public function maybe_install() { if (! $this->is_pro_enabled()) { return; } $schema = get_option(self::SCHEMA_OPTION, ''); if ($schema !== self::SCHEMA_VERSION || ! $this->all_tables_exist()) { $this->install_schema(); } $this->maybe_seed_default_journey(); } public function install_schema() { if (! $this->is_pro_enabled()) { return; } global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $charset_collate = $wpdb->get_charset_collate(); $journeys = $this->get_table_name('journeys'); $steps = $this->get_table_name('steps'); $rules = $this->get_table_name('rules'); $experiments = $this->get_table_name('experiments'); $variants = $this->get_table_name('variants'); $events = $this->get_table_name('events'); $sql_journeys = "CREATE TABLE {$journeys} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, slug VARCHAR(64) NOT NULL, name VARCHAR(120) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'active', is_default TINYINT(1) NOT NULL DEFAULT 0, config_json LONGTEXT NULL, created_at_utc DATETIME NOT NULL, updated_at_utc DATETIME NOT NULL, PRIMARY KEY (id), UNIQUE KEY slug (slug), KEY status_default (status,is_default) ) {$charset_collate};"; $sql_steps = "CREATE TABLE {$steps} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, journey_id BIGINT(20) UNSIGNED NOT NULL, step_order INT(11) NOT NULL DEFAULT 1, step_key VARCHAR(64) NOT NULL, step_type VARCHAR(24) NOT NULL DEFAULT 'soft', content_html LONGTEXT NOT NULL, style_json LONGTEXT NULL, behavior_json LONGTEXT NULL, trigger_type VARCHAR(24) NOT NULL DEFAULT 'immediate', delay_ms INT(11) NOT NULL DEFAULT 0, stop_condition VARCHAR(24) NOT NULL DEFAULT 'none', created_at_utc DATETIME NOT NULL, updated_at_utc DATETIME NOT NULL, PRIMARY KEY (id), KEY journey_order (journey_id,step_order), KEY journey_type (journey_id,step_type) ) {$charset_collate};"; $sql_rules = "CREATE TABLE {$rules} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, journey_id BIGINT(20) UNSIGNED NOT NULL, rule_type VARCHAR(32) NOT NULL, operator_type VARCHAR(16) NOT NULL DEFAULT 'equals', rule_value VARCHAR(255) NOT NULL, enabled TINYINT(1) NOT NULL DEFAULT 1, created_at_utc DATETIME NOT NULL, updated_at_utc DATETIME NOT NULL, PRIMARY KEY (id), KEY journey_enabled (journey_id,enabled), KEY journey_rule (journey_id,rule_type) ) {$charset_collate};"; $sql_experiments = "CREATE TABLE {$experiments} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, journey_id BIGINT(20) UNSIGNED NOT NULL, name VARCHAR(120) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'active', allocation TINYINT(3) UNSIGNED NOT NULL DEFAULT 100, created_at_utc DATETIME NOT NULL, updated_at_utc DATETIME NOT NULL, PRIMARY KEY (id), KEY journey_status (journey_id,status) ) {$charset_collate};"; $sql_variants = "CREATE TABLE {$variants} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, experiment_id BIGINT(20) UNSIGNED NOT NULL, step_id BIGINT(20) UNSIGNED NULL, name VARCHAR(120) NOT NULL, weight INT(11) NOT NULL DEFAULT 100, content_html LONGTEXT NULL, style_json LONGTEXT NULL, metadata_json LONGTEXT NULL, created_at_utc DATETIME NOT NULL, updated_at_utc DATETIME NOT NULL, PRIMARY KEY (id), KEY experiment_weight (experiment_id,weight), KEY experiment_step (experiment_id,step_id) ) {$charset_collate};"; $sql_events = "CREATE TABLE {$events} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, event_time_utc DATETIME NOT NULL, event_date DATE NOT NULL, visit_id VARCHAR(64) NOT NULL, visitor_hash CHAR(64) NOT NULL, session_index INT(11) UNSIGNED NOT NULL DEFAULT 1, journey_id BIGINT(20) UNSIGNED NULL, step_id BIGINT(20) UNSIGNED NULL, variant_id BIGINT(20) UNSIGNED NULL, event_type VARCHAR(32) NOT NULL, trigger_type VARCHAR(32) NOT NULL DEFAULT '', outcome_type VARCHAR(32) NOT NULL DEFAULT '', adblock_status VARCHAR(12) NOT NULL DEFAULT 'unknown', page_path VARCHAR(255) NOT NULL DEFAULT '/', device_type VARCHAR(20) NOT NULL DEFAULT 'other', browser_family VARCHAR(40) NOT NULL DEFAULT 'other', extra_json LONGTEXT NULL, PRIMARY KEY (id), KEY date_type (event_date,event_type), KEY journey_date (journey_id,event_date), KEY variant_date (variant_id,event_date), KEY visit_event (visit_id,event_type), KEY outcome_date (outcome_type,event_date), KEY path_date (page_path(191),event_date) ) {$charset_collate};"; dbDelta($sql_journeys); dbDelta($sql_steps); dbDelta($sql_rules); dbDelta($sql_experiments); dbDelta($sql_variants); dbDelta($sql_events); update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION); } public function cleanup_old_events() { if (! $this->is_pro_enabled()) { return; } global $wpdb; $table = $this->get_table_name('events'); if (! $this->table_exists($table)) { return; } $retention_days = max(1, absint(apply_filters('daau_recovery_retention_days', self::RETENTION_DAYS))); $days_to_subtract = max(0, $retention_days - 1); $cutoff = gmdate('Y-m-d', strtotime("-{$days_to_subtract} days", current_time('timestamp', true))); $wpdb->query($wpdb->prepare('DELETE FROM %i WHERE event_date < %s', $table, $cutoff)); } public function register_rest_routes() { if (! $this->is_pro_enabled()) { return; } register_rest_route('adunblocker/v1', '/journeys', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'rest_get_journeys'), 'permission_callback' => array($this, 'can_manage_options'), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'rest_save_journey'), 'permission_callback' => array($this, 'can_manage_options'), ), )); register_rest_route('adunblocker/v1', '/journeys/(?P\\d+)', array( array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array($this, 'rest_delete_journey'), 'permission_callback' => array($this, 'can_manage_options'), ), )); register_rest_route('adunblocker/v1', '/evaluate', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'rest_evaluate'), 'permission_callback' => '__return_true', ), )); register_rest_route('adunblocker/v1', '/event', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'rest_track_event'), 'permission_callback' => '__return_true', ), )); register_rest_route('adunblocker/v1', '/reports/funnel', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'rest_report_funnel'), 'permission_callback' => array($this, 'can_manage_options'), ), )); register_rest_route('adunblocker/v1', '/settings', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'rest_get_settings'), 'permission_callback' => array($this, 'can_manage_options'), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'rest_save_settings'), 'permission_callback' => array($this, 'can_manage_options'), ), )); register_rest_route('adunblocker/v1', '/recommendation', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'rest_get_recommendation'), 'permission_callback' => array($this, 'can_manage_options'), ), )); } public function rest_get_journeys() { return rest_ensure_response(array( 'journeys' => $this->get_all_journeys(true), )); } public function rest_save_journey(WP_REST_Request $request) { $journey = $request->get_json_params(); if (! is_array($journey)) { $journey = $request->get_params(); } $prepared = $this->sanitize_journey_payload($journey); if (is_wp_error($prepared)) { return $prepared; } $saved_id = $this->upsert_journey($prepared); if (is_wp_error($saved_id)) { return $saved_id; } return rest_ensure_response(array( 'journey' => $this->get_journey_by_id($saved_id, true), )); } public function rest_delete_journey(WP_REST_Request $request) { global $wpdb; $id = absint($request->get_param('id')); if ($id <= 0) { return new WP_Error('invalid_journey', esc_html__('Invalid journey id.', 'adunblocker'), array('status' => 400)); } $journeys = $this->get_table_name('journeys'); $steps = $this->get_table_name('steps'); $rules = $this->get_table_name('rules'); $experiments = $this->get_table_name('experiments'); $variants = $this->get_table_name('variants'); $experiment_ids = $wpdb->get_col($wpdb->prepare('SELECT id FROM %i WHERE journey_id = %d', $experiments, $id)); if (! empty($experiment_ids)) { foreach ($experiment_ids as $experiment_id) { $wpdb->delete($variants, array('experiment_id' => absint($experiment_id)), array('%d')); } } $wpdb->delete($experiments, array('journey_id' => $id), array('%d')); $wpdb->delete($steps, array('journey_id' => $id), array('%d')); $wpdb->delete($rules, array('journey_id' => $id), array('%d')); $wpdb->delete($journeys, array('id' => $id), array('%d')); $this->maybe_seed_default_journey(); return rest_ensure_response(array('deleted' => true)); } public function rest_evaluate(WP_REST_Request $request) { $nonce_check = $this->verify_public_nonce($request); if (is_wp_error($nonce_check)) { return $nonce_check; } $params = $request->get_json_params(); if (! is_array($params)) { $params = $request->get_params(); } $context = $this->build_context($params); $visitor_id = isset($params['visitor_id']) ? sanitize_text_field($params['visitor_id']) : ''; if (! preg_match('/^[A-Za-z0-9._-]{8,128}$/', $visitor_id)) { $visitor_id = wp_generate_password(24, false, false); } $journey = $this->evaluate_journey($context, $visitor_id); if (empty($journey)) { return rest_ensure_response(array('journey' => null)); } return rest_ensure_response(array('journey' => $journey)); } public function rest_track_event(WP_REST_Request $request) { $nonce_check = $this->verify_public_nonce($request); if (is_wp_error($nonce_check)) { return $nonce_check; } $params = $request->get_json_params(); if (! is_array($params)) { $params = $request->get_params(); } $payload = $this->sanitize_event_payload($params); if (is_wp_error($payload)) { return $payload; } $result = $this->insert_recovery_event($payload); if (is_wp_error($result)) { return $result; } $this->dispatch_offer_adapters($payload); return rest_ensure_response(array('recorded' => true)); } public function rest_report_funnel(WP_REST_Request $request) { $range = absint($request->get_param('range')); if (! in_array($range, array(7, 30, 90), true)) { $range = 30; } $report = $this->get_funnel_report($range); return rest_ensure_response($report); } public function rest_get_settings() { return rest_ensure_response(array('settings' => $this->get_settings())); } public function rest_save_settings(WP_REST_Request $request) { $params = $request->get_json_params(); if (! is_array($params)) { $params = $request->get_params(); } $settings = $this->sanitize_settings_payload($params); update_option(self::SETTINGS_OPTION, $settings); return rest_ensure_response(array('settings' => $settings)); } public function rest_get_recommendation(WP_REST_Request $request) { $params = $request->get_json_params(); if (! is_array($params)) { $params = $request->get_params(); } $settings = $this->get_settings(); $endpoint = $settings['optimization_service_url']; if (empty($endpoint)) { return new WP_Error('missing_service_url', esc_html__('Optimization service URL is not configured.', 'adunblocker'), array('status' => 400)); } $payload = array( 'journey_id' => isset($params['journey_id']) ? absint($params['journey_id']) : 0, 'window_days' => isset($params['window_days']) ? max(1, absint($params['window_days'])) : 30, 'features' => isset($params['features']) && is_array($params['features']) ? $params['features'] : array(), ); $response = wp_remote_post($endpoint, array( 'timeout' => 8, 'headers' => array('Content-Type' => 'application/json'), 'body' => wp_json_encode($payload), )); if (is_wp_error($response)) { return new WP_Error('service_failed', esc_html__('Unable to reach optimization service.', 'adunblocker'), array('status' => 502)); } $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if ($code >= 400 || ! is_array($data)) { return new WP_Error('service_invalid', esc_html__('Optimization service returned an invalid response.', 'adunblocker'), array('status' => 502)); } return rest_ensure_response(array('recommendation' => $data)); } public function can_manage_options() { $cap = (is_multisite() && is_network_admin()) ? 'manage_network_options' : 'manage_options'; return current_user_can($cap); } public function get_runtime_payload($page_path = '') { if (! $this->is_pro_enabled()) { return null; } $context = $this->build_context(array( 'page_path' => $page_path, )); $journey = $this->evaluate_journey($context, ''); return array( 'rest_url' => esc_url_raw(rest_url('adunblocker/v1/')), 'nonce' => wp_create_nonce('daau-recovery-public'), 'features' => $this->get_settings(), 'current_journey' => $journey, ); } public function get_protect_template() { if (! $this->is_pro_enabled()) { return null; } $settings = $this->get_settings(); if (empty($settings['protect_mode'])) { return null; } $journey = $this->evaluate_journey($this->build_context(array()), ''); if (empty($journey) || empty($journey['steps'])) { return null; } $hard_step = null; foreach ($journey['steps'] as $step) { if (isset($step['step_type']) && $step['step_type'] === 'hard') { $hard_step = $step; } } if (empty($hard_step)) { $hard_step = end($journey['steps']); } if (empty($hard_step)) { return null; } $style = isset($hard_step['style']) && is_array($hard_step['style']) ? $hard_step['style'] : array(); return array( 'content' => isset($hard_step['content_html']) ? $hard_step['content_html'] : '', 'overlay_color' => isset($style['overlay-color']) ? $style['overlay-color'] : 'rgba(0,0,0,0.92)', 'bg_color' => isset($style['bg-color']) ? $style['bg-color'] : '#ffffff', 'text_color' => isset($style['text-color']) ? $style['text-color'] : '#111111', ); } private function get_settings() { $defaults = array( 'protect_mode' => 0, 'proxy_enabled' => 0, 'proxy_base_url' => '', 'optimization_service_url' => '', 'allowlist_instructions' => '', 'mailchimp_webhook_url' => '', 'kit_webhook_url' => '', 'subscription_url' => '', 'bounce_seconds' => 12, 'webhook_url' => '', ); $current = get_option(self::SETTINGS_OPTION, array()); if (! is_array($current)) { $current = array(); } return wp_parse_args($current, $defaults); } private function is_pro_enabled() { if (defined('DAAU_PRO_ACTIVE') && DAAU_PRO_ACTIVE) { return true; } return (bool) apply_filters('daau_stats_is_pro', false); } private function sanitize_settings_payload($payload) { $current = $this->get_settings(); $current['protect_mode'] = ! empty($payload['protect_mode']) ? 1 : 0; $current['proxy_enabled'] = ! empty($payload['proxy_enabled']) ? 1 : 0; $current['proxy_base_url'] = esc_url_raw(isset($payload['proxy_base_url']) ? $payload['proxy_base_url'] : ''); $current['optimization_service_url'] = esc_url_raw(isset($payload['optimization_service_url']) ? $payload['optimization_service_url'] : ''); $current['allowlist_instructions'] = wp_kses_post(isset($payload['allowlist_instructions']) ? $payload['allowlist_instructions'] : ''); $current['mailchimp_webhook_url'] = esc_url_raw(isset($payload['mailchimp_webhook_url']) ? $payload['mailchimp_webhook_url'] : ''); $current['kit_webhook_url'] = esc_url_raw(isset($payload['kit_webhook_url']) ? $payload['kit_webhook_url'] : ''); $current['subscription_url'] = esc_url_raw(isset($payload['subscription_url']) ? $payload['subscription_url'] : ''); $current['webhook_url'] = esc_url_raw(isset($payload['webhook_url']) ? $payload['webhook_url'] : ''); $current['bounce_seconds'] = max(5, min(60, absint(isset($payload['bounce_seconds']) ? $payload['bounce_seconds'] : 12))); return $current; } private function verify_public_nonce(WP_REST_Request $request) { $nonce = $request->get_param('nonce'); if (empty($nonce)) { $nonce = $request->get_header('x-daau-nonce'); } if (! wp_verify_nonce($nonce, 'daau-recovery-public')) { return new WP_Error('invalid_nonce', esc_html__('Invalid recovery nonce.', 'adunblocker'), array('status' => 403)); } return true; } private function sanitize_journey_payload($journey) { $id = isset($journey['id']) ? absint($journey['id']) : 0; $name = isset($journey['name']) ? sanitize_text_field($journey['name']) : ''; if ($name === '') { return new WP_Error('missing_name', esc_html__('Journey name is required.', 'adunblocker'), array('status' => 400)); } $slug = isset($journey['slug']) ? sanitize_title($journey['slug']) : sanitize_title($name); $status = isset($journey['status']) ? sanitize_key($journey['status']) : 'active'; if (! in_array($status, array('active', 'paused'), true)) { $status = 'active'; } $is_default = ! empty($journey['is_default']) ? 1 : 0; $config_json = isset($journey['config']) ? wp_json_encode($journey['config']) : null; $steps = array(); $raw_steps = isset($journey['steps']) && is_array($journey['steps']) ? $journey['steps'] : array(); foreach ($raw_steps as $index => $step) { $step_key = isset($step['step_key']) ? sanitize_key($step['step_key']) : 'step_' . ($index + 1); $step_type = isset($step['step_type']) ? sanitize_key($step['step_type']) : 'soft'; if (! in_array($step_type, array('soft', 'strong', 'hard'), true)) { $step_type = 'soft'; } $trigger = isset($step['trigger_type']) ? sanitize_key($step['trigger_type']) : 'immediate'; if (! in_array($trigger, array('immediate', 'scroll_depth', 'exit_intent', 'inactivity', 'repeat_session'), true)) { $trigger = 'immediate'; } $stop = isset($step['stop_condition']) ? sanitize_key($step['stop_condition']) : 'none'; if (! in_array($stop, array('none', 'on_dismiss', 'on_recover'), true)) { $stop = 'none'; } $content_html = isset($step['content_html']) ? wp_kses_post($step['content_html']) : ''; $style_json = isset($step['style']) && is_array($step['style']) ? wp_json_encode($step['style']) : null; $behavior_json = isset($step['behavior']) && is_array($step['behavior']) ? wp_json_encode($step['behavior']) : null; $steps[] = array( 'id' => isset($step['id']) ? absint($step['id']) : 0, 'step_order' => $index + 1, 'step_key' => $step_key, 'step_type' => $step_type, 'content_html' => $content_html, 'style_json' => $style_json, 'behavior_json' => $behavior_json, 'trigger_type' => $trigger, 'delay_ms' => max(0, absint(isset($step['delay_ms']) ? $step['delay_ms'] : 0)), 'stop_condition' => $stop, ); } if (empty($steps)) { return new WP_Error('missing_steps', esc_html__('At least one journey step is required.', 'adunblocker'), array('status' => 400)); } $rules = array(); $raw_rules = isset($journey['rules']) && is_array($journey['rules']) ? $journey['rules'] : array(); foreach ($raw_rules as $rule) { $type = isset($rule['rule_type']) ? sanitize_key($rule['rule_type']) : ''; if ($type === '') { continue; } $rules[] = array( 'rule_type' => $type, 'operator_type' => isset($rule['operator_type']) ? sanitize_key($rule['operator_type']) : 'equals', 'rule_value' => sanitize_text_field(isset($rule['rule_value']) ? $rule['rule_value'] : ''), 'enabled' => ! empty($rule['enabled']) ? 1 : 0, ); } $experiments = array(); $raw_experiments = isset($journey['experiments']) && is_array($journey['experiments']) ? $journey['experiments'] : array(); foreach ($raw_experiments as $experiment) { $experiment_name = sanitize_text_field(isset($experiment['name']) ? $experiment['name'] : 'Experiment'); $experiment_status = sanitize_key(isset($experiment['status']) ? $experiment['status'] : 'active'); if (! in_array($experiment_status, array('active', 'paused'), true)) { $experiment_status = 'active'; } $variants = array(); $raw_variants = isset($experiment['variants']) && is_array($experiment['variants']) ? $experiment['variants'] : array(); foreach ($raw_variants as $variant) { $variants[] = array( 'name' => sanitize_text_field(isset($variant['name']) ? $variant['name'] : 'Variant'), 'step_id' => isset($variant['step_id']) ? absint($variant['step_id']) : 0, 'weight' => max(1, absint(isset($variant['weight']) ? $variant['weight'] : 100)), 'content_html' => isset($variant['content_html']) ? wp_kses_post($variant['content_html']) : '', 'style_json' => isset($variant['style']) && is_array($variant['style']) ? wp_json_encode($variant['style']) : null, 'metadata_json' => isset($variant['metadata']) && is_array($variant['metadata']) ? wp_json_encode($variant['metadata']) : null, ); } $experiments[] = array( 'name' => $experiment_name, 'status' => $experiment_status, 'allocation' => max(1, min(100, absint(isset($experiment['allocation']) ? $experiment['allocation'] : 100))), 'variants' => $variants, ); } return array( 'id' => $id, 'slug' => $slug, 'name' => $name, 'status' => $status, 'is_default' => $is_default, 'config_json' => $config_json, 'steps' => $steps, 'rules' => $rules, 'experiments' => $experiments, ); } private function upsert_journey($journey) { global $wpdb; $journeys = $this->get_table_name('journeys'); $steps = $this->get_table_name('steps'); $rules = $this->get_table_name('rules'); $experiments = $this->get_table_name('experiments'); $variants = $this->get_table_name('variants'); $now = gmdate('Y-m-d H:i:s'); if (! empty($journey['is_default'])) { $wpdb->query($wpdb->prepare('UPDATE %i SET is_default = 0', $journeys)); } if (! empty($journey['id'])) { $journey_id = absint($journey['id']); $wpdb->update( $journeys, array( 'slug' => $journey['slug'], 'name' => $journey['name'], 'status' => $journey['status'], 'is_default' => $journey['is_default'], 'config_json' => $journey['config_json'], 'updated_at_utc' => $now, ), array('id' => $journey_id), array('%s', '%s', '%s', '%d', '%s', '%s'), array('%d') ); } else { $wpdb->insert( $journeys, array( 'slug' => $journey['slug'], 'name' => $journey['name'], 'status' => $journey['status'], 'is_default' => $journey['is_default'], 'config_json' => $journey['config_json'], 'created_at_utc' => $now, 'updated_at_utc' => $now, ), array('%s', '%s', '%s', '%d', '%s', '%s', '%s') ); $journey_id = absint($wpdb->insert_id); } if ($journey_id <= 0) { return new WP_Error('save_failed', esc_html__('Unable to save journey.', 'adunblocker'), array('status' => 500)); } $experiment_ids = $wpdb->get_col($wpdb->prepare('SELECT id FROM %i WHERE journey_id = %d', $experiments, $journey_id)); if (! empty($experiment_ids)) { foreach ($experiment_ids as $experiment_id) { $wpdb->delete($variants, array('experiment_id' => absint($experiment_id)), array('%d')); } } $wpdb->delete($steps, array('journey_id' => $journey_id), array('%d')); $wpdb->delete($rules, array('journey_id' => $journey_id), array('%d')); $wpdb->delete($experiments, array('journey_id' => $journey_id), array('%d')); $step_id_map = array(); foreach ($journey['steps'] as $step) { $wpdb->insert( $steps, array( 'journey_id' => $journey_id, 'step_order' => $step['step_order'], 'step_key' => $step['step_key'], 'step_type' => $step['step_type'], 'content_html' => $step['content_html'], 'style_json' => $step['style_json'], 'behavior_json' => $step['behavior_json'], 'trigger_type' => $step['trigger_type'], 'delay_ms' => $step['delay_ms'], 'stop_condition' => $step['stop_condition'], 'created_at_utc' => $now, 'updated_at_utc' => $now, ), array('%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s') ); $inserted_id = absint($wpdb->insert_id); if (! empty($step['id'])) { $step_id_map[$step['id']] = $inserted_id; } $step_id_map[$step['step_order']] = $inserted_id; } foreach ($journey['rules'] as $rule) { $wpdb->insert( $rules, array( 'journey_id' => $journey_id, 'rule_type' => $rule['rule_type'], 'operator_type' => $rule['operator_type'], 'rule_value' => $rule['rule_value'], 'enabled' => $rule['enabled'], 'created_at_utc' => $now, 'updated_at_utc' => $now, ), array('%d', '%s', '%s', '%s', '%d', '%s', '%s') ); } foreach ($journey['experiments'] as $experiment) { $wpdb->insert( $experiments, array( 'journey_id' => $journey_id, 'name' => $experiment['name'], 'status' => $experiment['status'], 'allocation' => $experiment['allocation'], 'created_at_utc' => $now, 'updated_at_utc' => $now, ), array('%d', '%s', '%s', '%d', '%s', '%s') ); $experiment_id = absint($wpdb->insert_id); foreach ($experiment['variants'] as $variant) { $variant_step_id = ! empty($variant['step_id']) && isset($step_id_map[$variant['step_id']]) ? $step_id_map[$variant['step_id']] : 0; $wpdb->insert( $variants, array( 'experiment_id' => $experiment_id, 'step_id' => $variant_step_id > 0 ? $variant_step_id : null, 'name' => $variant['name'], 'weight' => $variant['weight'], 'content_html' => $variant['content_html'], 'style_json' => $variant['style_json'], 'metadata_json' => $variant['metadata_json'], 'created_at_utc' => $now, 'updated_at_utc' => $now, ), array('%d', '%d', '%s', '%d', '%s', '%s', '%s', '%s', '%s') ); } } return $journey_id; } private function evaluate_journey($context, $visitor_id) { $journeys = $this->get_all_journeys(true); if (empty($journeys)) { return null; } $selected = null; foreach ($journeys as $journey) { if ($journey['status'] !== 'active') { continue; } if ($this->matches_rules($journey['rules'], $context)) { $selected = $journey; break; } } if (empty($selected)) { foreach ($journeys as $journey) { if ($journey['status'] === 'active') { $selected = $journey; break; } } } if (empty($selected)) { return null; } $selected_variant = null; if (! empty($selected['experiments'])) { $experiment = $selected['experiments'][0]; if ($experiment['status'] === 'active' && ! empty($experiment['variants'])) { $selected_variant = $this->select_variant($experiment, $visitor_id); } } if (! empty($selected_variant)) { foreach ($selected['steps'] as &$step) { $matches_step = empty($selected_variant['step_id']) || absint($selected_variant['step_id']) === absint($step['id']); if (! $matches_step) { continue; } if (! empty($selected_variant['content_html'])) { $step['content_html'] = $selected_variant['content_html']; } if (! empty($selected_variant['style'])) { $step['style'] = array_merge($step['style'], $selected_variant['style']); } $step['variant_id'] = $selected_variant['id']; } unset($step); } $settings = $this->get_settings(); $selected['features'] = array( 'protect_mode' => ! empty($settings['protect_mode']), 'proxy_enabled' => ! empty($settings['proxy_enabled']), 'proxy_base_url' => $settings['proxy_base_url'], 'subscription_url' => $settings['subscription_url'], 'allowlist_instructions' => $settings['allowlist_instructions'], 'bounce_seconds' => $settings['bounce_seconds'], ); $selected['selected_variant'] = $selected_variant; return $selected; } private function select_variant($experiment, $visitor_id) { $variants = $experiment['variants']; $total_weight = 0; foreach ($variants as $variant) { $total_weight += max(1, absint($variant['weight'])); } if ($total_weight <= 0) { return $variants[0]; } $seed = $visitor_id !== '' ? $visitor_id : wp_generate_password(12, false, false); $hash = hash('sha256', $seed . '|' . $experiment['id']); $bucket = hexdec(substr($hash, 0, 8)) % $total_weight; $cumulative = 0; foreach ($variants as $variant) { $cumulative += max(1, absint($variant['weight'])); if ($bucket < $cumulative) { return $variant; } } return $variants[0]; } private function matches_rules($rules, $context) { if (empty($rules)) { return true; } foreach ($rules as $rule) { if (empty($rule['enabled'])) { continue; } if (! $this->rule_matches($rule, $context)) { return false; } } return true; } private function rule_matches($rule, $context) { $type = $rule['rule_type']; $operator = isset($rule['operator_type']) ? $rule['operator_type'] : 'equals'; $value = isset($rule['rule_value']) ? $rule['rule_value'] : ''; switch ($type) { case 'url_pattern': $path = isset($context['page_path']) ? $context['page_path'] : '/'; if ($operator === 'contains') { return strpos($path, $value) !== false; } if ($operator === 'not_contains') { return strpos($path, $value) === false; } if ($operator === 'regex') { return @preg_match('/' . $value . '/i', $path) === 1; } return $path === $value; case 'device': $current_device = isset($context['device_type']) ? $context['device_type'] : 'other'; return $operator === 'not_equals' ? $current_device !== $value : $current_device === $value; case 'browser': $current_browser = isset($context['browser_family']) ? $context['browser_family'] : 'other'; return $operator === 'not_equals' ? $current_browser !== $value : $current_browser === $value; case 'visit_count': $visit_count = isset($context['session_index']) ? absint($context['session_index']) : 1; $target = absint($value); if ($operator === 'gte') { return $visit_count >= $target; } if ($operator === 'lte') { return $visit_count <= $target; } return $visit_count === $target; case 'logged_in': $is_logged_in = ! empty($context['is_logged_in']) ? 1 : 0; $rule_bool = absint($value) > 0 ? 1 : 0; return $is_logged_in === $rule_bool; } return true; } private function build_context($params) { $path = isset($params['page_path']) ? $params['page_path'] : '/'; $path = $this->normalize_page_path($path); $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : ''; if (isset($params['user_agent'])) { $user_agent = sanitize_text_field($params['user_agent']); } return array( 'page_path' => $path, 'device_type' => $this->detect_device_type($user_agent), 'browser_family' => $this->detect_browser_family($user_agent), 'session_index' => isset($params['session_index']) ? max(1, absint($params['session_index'])) : 1, 'is_logged_in' => is_user_logged_in(), ); } private function sanitize_event_payload($payload) { $visit_id = isset($payload['visit_id']) ? sanitize_text_field($payload['visit_id']) : ''; if (! preg_match('/^[A-Za-z0-9._-]{8,64}$/', $visit_id)) { return new WP_Error('invalid_visit_id', esc_html__('Invalid visit id.', 'adunblocker'), array('status' => 400)); } $visitor_id = isset($payload['visitor_id']) ? sanitize_text_field($payload['visitor_id']) : ''; if (! preg_match('/^[A-Za-z0-9._-]{8,128}$/', $visitor_id)) { return new WP_Error('invalid_visitor_id', esc_html__('Invalid visitor id.', 'adunblocker'), array('status' => 400)); } $event_type = isset($payload['event_type']) ? sanitize_key($payload['event_type']) : ''; if ($event_type === '') { return new WP_Error('invalid_event', esc_html__('Event type is required.', 'adunblocker'), array('status' => 400)); } $outcome_type = isset($payload['outcome_type']) ? sanitize_key($payload['outcome_type']) : ''; $adblock_status = isset($payload['adblock_status']) ? sanitize_key($payload['adblock_status']) : 'unknown'; if (! in_array($adblock_status, array('blocked', 'unblocked', 'unknown'), true)) { $adblock_status = 'unknown'; } $extra = isset($payload['extra']) && is_array($payload['extra']) ? $payload['extra'] : array(); if (isset($payload['email'])) { $email = sanitize_email($payload['email']); if ($email !== '') { $extra['email'] = $email; } } return array( 'visit_id' => substr($visit_id, 0, 64), 'visitor_hash' => hash('sha256', $visitor_id . '|' . wp_salt('auth')), 'session_index' => max(1, absint(isset($payload['session_index']) ? $payload['session_index'] : 1)), 'journey_id' => absint(isset($payload['journey_id']) ? $payload['journey_id'] : 0), 'step_id' => absint(isset($payload['step_id']) ? $payload['step_id'] : 0), 'variant_id' => absint(isset($payload['variant_id']) ? $payload['variant_id'] : 0), 'event_type' => $event_type, 'trigger_type' => sanitize_key(isset($payload['trigger_type']) ? $payload['trigger_type'] : ''), 'outcome_type' => $outcome_type, 'adblock_status' => $adblock_status, 'page_path' => substr($this->normalize_page_path(isset($payload['page_path']) ? $payload['page_path'] : '/'), 0, 255), 'device_type' => sanitize_key(isset($payload['device_type']) ? $payload['device_type'] : 'other'), 'browser_family' => sanitize_key(isset($payload['browser_family']) ? $payload['browser_family'] : 'other'), 'extra_json' => ! empty($extra) ? wp_json_encode($extra) : null, ); } private function insert_recovery_event($payload) { global $wpdb; $table = $this->get_table_name('events'); if (! $this->table_exists($table)) { return new WP_Error('missing_table', esc_html__('Recovery event table does not exist.', 'adunblocker'), array('status' => 500)); } $inserted = $wpdb->insert( $table, array( 'event_time_utc' => gmdate('Y-m-d H:i:s'), 'event_date' => gmdate('Y-m-d'), 'visit_id' => $payload['visit_id'], 'visitor_hash' => $payload['visitor_hash'], 'session_index' => $payload['session_index'], 'journey_id' => $payload['journey_id'] > 0 ? $payload['journey_id'] : null, 'step_id' => $payload['step_id'] > 0 ? $payload['step_id'] : null, 'variant_id' => $payload['variant_id'] > 0 ? $payload['variant_id'] : null, 'event_type' => $payload['event_type'], 'trigger_type' => $payload['trigger_type'], 'outcome_type' => $payload['outcome_type'], 'adblock_status' => $payload['adblock_status'], 'page_path' => $payload['page_path'], 'device_type' => $payload['device_type'], 'browser_family' => $payload['browser_family'], 'extra_json' => $payload['extra_json'], ), array('%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ); if ($inserted === false) { return new WP_Error('insert_failed', esc_html__('Unable to record recovery event.', 'adunblocker'), array('status' => 500)); } return true; } private function dispatch_offer_adapters($payload) { if (empty($payload['outcome_type'])) { return; } $settings = $this->get_settings(); $extra = ! empty($payload['extra_json']) ? json_decode($payload['extra_json'], true) : array(); if (! is_array($extra)) { $extra = array(); } $email = isset($extra['email']) ? sanitize_email($extra['email']) : ''; if ($payload['outcome_type'] === 'email_capture' && $email !== '') { $this->dispatch_email_adapter($settings['mailchimp_webhook_url'], $email, 'mailchimp'); $this->dispatch_email_adapter($settings['kit_webhook_url'], $email, 'kit'); } if (! empty($settings['webhook_url'])) { wp_remote_post($settings['webhook_url'], array( 'timeout' => 4, 'headers' => array('Content-Type' => 'application/json'), 'body' => wp_json_encode(array( 'plugin' => 'adunblocker', 'event_type' => $payload['event_type'], 'outcome_type' => $payload['outcome_type'], 'journey_id' => $payload['journey_id'], 'step_id' => $payload['step_id'], 'variant_id' => $payload['variant_id'], 'event_time_utc' => gmdate('c'), )), )); } } private function dispatch_email_adapter($url, $email, $provider) { if (empty($url) || empty($email)) { return; } wp_remote_post($url, array( 'timeout' => 4, 'headers' => array('Content-Type' => 'application/json'), 'body' => wp_json_encode(array( 'email' => $email, 'provider' => $provider, 'source' => 'adunblocker', )), )); } private function get_funnel_report($range) { global $wpdb; $table = $this->get_table_name('events'); $since = gmdate('Y-m-d', strtotime('-' . max(0, $range - 1) . ' days', current_time('timestamp', true))); if (! $this->table_exists($table)) { return array( 'cards' => array( 'detected' => 0, 'shown' => 0, 'dismissed' => 0, 'recovered' => 0, 'bounce_surrogate' => 0, 'recovery_rate' => 0, ), 'variant_leaderboard' => array(), ); } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT event_type, COUNT(*) AS total FROM %i WHERE event_date >= %s GROUP BY event_type", $table, $since ), ARRAY_A ); $counts = array( 'detection' => 0, 'step_shown' => 0, 'dismissed' => 0, 'recovered' => 0, 'bounce_surrogate' => 0, ); foreach ($rows as $row) { $event = $row['event_type']; if (isset($counts[$event])) { $counts[$event] = (int) $row['total']; } } $recovery_rate = $counts['step_shown'] > 0 ? round(($counts['recovered'] / $counts['step_shown']) * 100, 2) : 0; $variants = $this->get_table_name('variants'); $leaderboard = $wpdb->get_results( $wpdb->prepare( "SELECT e.variant_id, COALESCE(v.name, 'Variant') AS variant_name, SUM(CASE WHEN e.event_type = 'step_shown' THEN 1 ELSE 0 END) AS shown, SUM(CASE WHEN e.event_type = 'recovered' THEN 1 ELSE 0 END) AS recovered, SUM(CASE WHEN e.event_type = 'dismissed' THEN 1 ELSE 0 END) AS dismissed FROM %i e LEFT JOIN %i v ON v.id = e.variant_id WHERE e.event_date >= %s AND e.variant_id IS NOT NULL GROUP BY e.variant_id, v.name ORDER BY recovered DESC, shown DESC LIMIT 10", $table, $variants, $since ), ARRAY_A ); foreach ($leaderboard as &$item) { $shown = (int) $item['shown']; $recovered = (int) $item['recovered']; $item['recovery_rate'] = $shown > 0 ? round(($recovered / $shown) * 100, 2) : 0; } unset($item); return array( 'cards' => array( 'detected' => $counts['detection'], 'shown' => $counts['step_shown'], 'dismissed' => $counts['dismissed'], 'recovered' => $counts['recovered'], 'bounce_surrogate' => $counts['bounce_surrogate'], 'recovery_rate' => $recovery_rate, ), 'variant_leaderboard' => $leaderboard, ); } private function get_all_journeys($with_children = false) { global $wpdb; $table = $this->get_table_name('journeys'); if (! $this->table_exists($table)) { return array(); } $rows = $wpdb->get_results($wpdb->prepare('SELECT * FROM %i ORDER BY is_default DESC, id ASC', $table), ARRAY_A); if (! $with_children) { return $rows; } $journeys = array(); foreach ($rows as $row) { $journeys[] = $this->hydrate_journey_row($row); } return $journeys; } private function get_journey_by_id($id, $with_children = false) { global $wpdb; $table = $this->get_table_name('journeys'); $row = $wpdb->get_row($wpdb->prepare('SELECT * FROM %i WHERE id = %d', $table, absint($id)), ARRAY_A); if (! $row) { return null; } if (! $with_children) { return $row; } return $this->hydrate_journey_row($row); } private function hydrate_journey_row($row) { global $wpdb; $journey_id = absint($row['id']); $steps_table = $this->get_table_name('steps'); $rules_table = $this->get_table_name('rules'); $experiments_table = $this->get_table_name('experiments'); $variants_table = $this->get_table_name('variants'); $steps = $wpdb->get_results( $wpdb->prepare('SELECT * FROM %i WHERE journey_id = %d ORDER BY step_order ASC', $steps_table, $journey_id), ARRAY_A ); foreach ($steps as &$step) { $step['style'] = $this->decode_json_field($step['style_json']); $step['behavior'] = $this->decode_json_field($step['behavior_json']); unset($step['style_json'], $step['behavior_json'], $step['created_at_utc'], $step['updated_at_utc']); } unset($step); $rules = $wpdb->get_results( $wpdb->prepare('SELECT * FROM %i WHERE journey_id = %d ORDER BY id ASC', $rules_table, $journey_id), ARRAY_A ); foreach ($rules as &$rule) { $rule['enabled'] = absint($rule['enabled']) === 1; unset($rule['created_at_utc'], $rule['updated_at_utc']); } unset($rule); $experiments = $wpdb->get_results( $wpdb->prepare('SELECT * FROM %i WHERE journey_id = %d ORDER BY id ASC', $experiments_table, $journey_id), ARRAY_A ); foreach ($experiments as &$experiment) { $experiment['variants'] = $wpdb->get_results( $wpdb->prepare('SELECT * FROM %i WHERE experiment_id = %d ORDER BY id ASC', $variants_table, $experiment['id']), ARRAY_A ); foreach ($experiment['variants'] as &$variant) { $variant['style'] = $this->decode_json_field($variant['style_json']); $variant['metadata'] = $this->decode_json_field($variant['metadata_json']); unset($variant['style_json'], $variant['metadata_json'], $variant['created_at_utc'], $variant['updated_at_utc']); } unset($variant); unset($experiment['created_at_utc'], $experiment['updated_at_utc']); } unset($experiment); return array( 'id' => $journey_id, 'slug' => $row['slug'], 'name' => $row['name'], 'status' => $row['status'], 'is_default' => absint($row['is_default']) === 1, 'config' => $this->decode_json_field($row['config_json']), 'steps' => $steps, 'rules' => $rules, 'experiments' => $experiments, ); } private function maybe_seed_default_journey() { global $wpdb; $table = $this->get_table_name('journeys'); if (! $this->table_exists($table)) { return; } $count = (int) $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM %i', $table)); if ($count > 0) { return; } $options = get_option($this->plugin_name . '-options', array()); $content = isset($options[$this->plugin_name . '-content']) ? wp_kses_post($options[$this->plugin_name . '-content']) : '

Adblock Detected

Please allow ads to support this site.

'; $overlay = isset($options[$this->plugin_name . '-overlay-color']) ? sanitize_text_field($options[$this->plugin_name . '-overlay-color']) : '#000000'; $bg = isset($options[$this->plugin_name . '-bg-color']) ? sanitize_text_field($options[$this->plugin_name . '-bg-color']) : '#ffffff'; $text = isset($options[$this->plugin_name . '-text-color']) ? sanitize_text_field($options[$this->plugin_name . '-text-color']) : '#111111'; $delay = isset($options[$this->plugin_name . '-delay']) ? max(0, absint($options[$this->plugin_name . '-delay'])) : 5000; $type = isset($options[$this->plugin_name . '-type']) ? sanitize_key($options[$this->plugin_name . '-type']) : 'strict'; $journey_payload = array( 'name' => 'Default Recovery Journey', 'slug' => 'default-recovery-journey', 'status' => 'active', 'is_default' => 1, 'steps' => array( array( 'step_key' => 'soft_ask', 'step_type' => 'soft', 'trigger_type' => 'immediate', 'delay_ms' => 0, 'stop_condition' => 'none', 'content_html' => $content, 'style' => array( 'overlay-color' => $overlay, 'bg-color' => $bg, 'text-color' => $text, ), 'behavior' => array( 'mode' => $type, 'delay' => $delay, ), ), array( 'step_key' => 'strong_ask', 'step_type' => 'strong', 'trigger_type' => 'inactivity', 'delay_ms' => 6000, 'stop_condition' => 'on_dismiss', 'content_html' => '

Support independent publishing

Ads keep this content free. Please allow ads for this site.

', 'style' => array( 'overlay-color' => 'rgba(0,0,0,0.92)', 'bg-color' => '#ffffff', 'text-color' => '#111111', ), 'behavior' => array( 'mode' => 'dismissible', ), ), array( 'step_key' => 'hard_wall', 'step_type' => 'hard', 'trigger_type' => 'repeat_session', 'delay_ms' => 0, 'stop_condition' => 'on_recover', 'content_html' => '

Ad access required

To continue, please disable your ad blocker for this site.

', 'style' => array( 'overlay-color' => 'rgba(0,0,0,0.95)', 'bg-color' => '#ffffff', 'text-color' => '#111111', ), 'behavior' => array( 'mode' => 'strict', ), ), ), 'rules' => array(), 'experiments' => array( array( 'name' => 'Default Message Test', 'status' => 'active', 'allocation' => 100, 'variants' => array( array( 'name' => 'Control', 'weight' => 60, 'content_html' => $content, ), array( 'name' => 'Value Message', 'weight' => 40, 'content_html' => '

Support this website

Disable your ad blocker to keep our content free and sustainable.

', ), ), ), ), ); $sanitized = $this->sanitize_journey_payload($journey_payload); if (! is_wp_error($sanitized)) { $this->upsert_journey($sanitized); } } private function all_tables_exist() { $tables = array( $this->get_table_name('journeys'), $this->get_table_name('steps'), $this->get_table_name('rules'), $this->get_table_name('experiments'), $this->get_table_name('variants'), $this->get_table_name('events'), ); foreach ($tables as $table) { if (! $this->table_exists($table)) { return false; } } return true; } private function table_exists($table) { global $wpdb; if (empty($table)) { return false; } $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))); return $found === $table; } private function decode_json_field($value) { if (empty($value)) { return array(); } $decoded = json_decode($value, true); if (! is_array($decoded)) { return array(); } return $decoded; } private function normalize_page_path($path) { $path = trim((string) $path); if ($path === '') { return '/'; } $parsed = wp_parse_url($path, PHP_URL_PATH); if ($parsed === false || $parsed === null) { $parsed = $path; } $parsed = sanitize_text_field($parsed); if ($parsed === '') { return '/'; } if ($parsed[0] !== '/') { $parsed = '/' . $parsed; } return $parsed; } private function detect_device_type($user_agent) { $ua = strtolower((string) $user_agent); if ($ua === '') { return 'other'; } if (preg_match('/ipad|tablet/', $ua)) { return 'tablet'; } if (preg_match('/mobile|iphone|android/', $ua)) { return 'mobile'; } return 'desktop'; } private function detect_browser_family($user_agent) { $ua = strtolower((string) $user_agent); if ($ua === '') { return 'other'; } if (strpos($ua, 'edg/') !== false) { return 'edge'; } if (strpos($ua, 'opr/') !== false || strpos($ua, 'opera') !== false) { return 'opera'; } if (strpos($ua, 'chrome/') !== false) { return 'chrome'; } if (strpos($ua, 'safari/') !== false && strpos($ua, 'chrome/') === false) { return 'safari'; } if (strpos($ua, 'firefox/') !== false) { return 'firefox'; } if (strpos($ua, 'msie') !== false || strpos($ua, 'trident/') !== false) { return 'ie'; } return 'other'; } }