connections = $connections ?? new ConnectionManager(); } public function register(): void { $this->registerAdminPostHandlers(); $this->registerPageHooks(); } public function registerAdminPostHandlers(): void { add_action('admin_post_aivie_wc_save_settings', [$this, 'handleSave']); add_action('wp_ajax_aivie_wc_test_connection', [$this, 'handleAjaxTestConnection']); add_action('admin_post_aivie_wc_oauth_start', [$this, 'handleOAuthStart']); add_action('admin_post_nopriv_aivie_wc_oauth_start', [$this, 'redirectUnauthenticatedAdminPost']); add_action('admin_post_aivie_wc_oauth_callback', [$this, 'handleOAuthCallback']); add_action('admin_post_nopriv_aivie_wc_oauth_callback', [$this, 'redirectUnauthenticatedAdminPost']); } public function registerPageHooks(): void { add_action('admin_menu', [$this, 'addMenuPage']); add_action('admin_init', [$this, 'registerSettings']); add_action('admin_notices', [$this, 'renderAuthErrorNotice']); add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']); } public function addMenuPage(): void { add_submenu_page( 'woocommerce', __('Aivie Settings', 'aivie-for-woocommerce'), __('Aivie', 'aivie-for-woocommerce'), 'manage_woocommerce', self::PAGE_SLUG, [$this, 'renderPage'] ); } public function registerSettings(): void { // Settings are handled manually via admin_post to support password masking. } public function enqueueAssets(string $hook): void { if (! str_contains($hook, self::PAGE_SLUG)) { return; } wp_enqueue_style('woocommerce_admin_styles'); wp_enqueue_script('wc-enhanced-select'); wp_enqueue_style( 'aivie-wc-admin', AIVIE_WC_URL . 'assets/admin.css', [], AIVIE_WC_VERSION ); wp_enqueue_script( 'aivie-wc-admin', AIVIE_WC_URL . 'assets/admin.js', ['jquery'], AIVIE_WC_VERSION, true ); wp_localize_script('aivie-wc-admin', 'aivieWcAdmin', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aivie_wc_test_connection_ajax'), 'i18n' => [ 'testing' => __('Testing...', 'aivie-for-woocommerce'), 'testSuccess' => __('Connection successful!', 'aivie-for-woocommerce'), 'testFailed' => __('Connection test failed. Check URL and OAuth connection.', 'aivie-for-woocommerce'), 'testError' => __('Could not test connection right now.', 'aivie-for-woocommerce'), ], ]); } public function handleSave(): void { if (! current_user_can('manage_woocommerce')) { wp_die(esc_html__('Insufficient permissions.', 'aivie-for-woocommerce')); } check_admin_referer(self::NONCE_ACTION, self::NONCE_FIELD); $fields = [ Options::ENABLED => 'bool', Options::BASE_URL => 'url', Options::CLIENT_ID => 'text', Options::SYNC_ON_ORDER_CREATED => 'bool', Options::SYNC_ON_PAYMENT_COMPLETE => 'bool', Options::SYNC_FAILED_ORDERS => 'bool', Options::CONTACT_TAGS => 'text', Options::CONTACT_ACTIONS_NEW_ORDER_ONLY => 'bool', Options::USE_TRACKING_CONTACT_ID => 'bool', Options::TRACKING_CONTACT_COOKIE => 'text', Options::SOURCE => 'text', Options::SOURCE_TYPE => 'text', Options::TIMEOUT => 'int', Options::INCLUDE_PRIVATE_META => 'bool', Options::INCLUDE_ORDER_ITEM_META => 'bool', Options::MAX_META_VALUE_LENGTH => 'int', Options::DEBUG_LOGGING => 'bool', ]; foreach ($fields as $key => $type) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Value is sanitized by field type below. $raw = isset($_POST[$key]) ? wp_unslash($_POST[$key]) : null; switch ($type) { case 'bool': update_option($key, (bool) $raw); break; case 'url': update_option($key, esc_url_raw((string) $raw)); break; case 'int': update_option($key, absint($raw)); break; default: update_option($key, sanitize_text_field((string) $raw)); } } // Handle statuses array. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Status array values are sanitized below. $rawStatuses = isset($_POST[Options::SYNC_ORDER_STATUSES]) ? wp_unslash($_POST[Options::SYNC_ORDER_STATUSES]) : []; $statuses = is_array($rawStatuses) ? array_map('sanitize_text_field', $rawStatuses) : []; update_option(Options::SYNC_ORDER_STATUSES, $statuses); foreach ([Options::CONTACT_SEGMENTS, Options::CONTACT_CAMPAIGNS] as $optionKey) { if (! isset($_POST[$optionKey . '_submitted'])) { continue; } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ID array values are converted with absint below. $rawIds = isset($_POST[$optionKey]) ? wp_unslash($_POST[$optionKey]) : []; $ids = is_array($rawIds) ? array_values(array_unique(array_filter(array_map('absint', $rawIds)))) : []; update_option($optionKey, $ids); } // Handle tax treatment mapping (WooCommerce tax rate ID => Aivie tax treatment). // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Map values are whitelisted below. $rawMap = isset($_POST[Options::TAX_TREATMENT_MAP]) ? wp_unslash($_POST[Options::TAX_TREATMENT_MAP]) : []; $taxTreatmentMap = []; if (is_array($rawMap)) { foreach ($rawMap as $rateId => $treatment) { $treatment = sanitize_text_field((string) $treatment); $taxTreatmentMap[absint($rateId)] = TaxTreatments::isValid($treatment) ? $treatment : TaxTreatments::DEFAULT; } } update_option(Options::TAX_TREATMENT_MAP, $taxTreatmentMap); $this->saveOrderItemFieldMappings(); if (isset($_POST['aivie_wc_refresh_order_item_fields'])) { delete_transient('aivie_wc_order_item_field_targets'); } // Handle password fields — only update if a new non-empty value is submitted. $this->maybeUpdateSecret( Options::CLIENT_SECRET, isset($_POST[Options::CLIENT_SECRET]) ? sanitize_text_field(wp_unslash($_POST[Options::CLIENT_SECRET])) : '' ); Logger::info('Aivie for WooCommerce settings saved.', [ 'enabled' => Options::isEnabled(), 'debug_logging' => Options::getBool(Options::DEBUG_LOGGING), 'sync_on_payment_complete' => Options::getBool(Options::SYNC_ON_PAYMENT_COMPLETE), 'sync_failed_orders' => Options::getBool(Options::SYNC_FAILED_ORDERS), 'sync_on_order_created' => Options::getBool(Options::SYNC_ON_ORDER_CREATED), ]); wp_safe_redirect(add_query_arg(['page' => self::PAGE_SLUG, 'updated' => '1'], admin_url('admin.php'))); exit; } private function maybeUpdateSecret(string $optionKey, mixed $value): void { $value = (string) $value; if ('' !== $value && str_repeat('*', strlen($value)) !== $value) { update_option($optionKey, $value); } } private function saveOrderItemFieldMappings(): void { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is checked in handleSave() before this helper is called. if (! isset($_POST[Options::ORDER_ITEM_FIELD_MAPPINGS . '_submitted'])) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is checked in handleSave(); mapping rows are sanitized field-by-field below. $rawRows = isset($_POST[Options::ORDER_ITEM_FIELD_MAPPINGS]) ? wp_unslash($_POST[Options::ORDER_ITEM_FIELD_MAPPINGS]) : []; $rows = []; if (is_array($rawRows)) { foreach ($rawRows as $row) { if (! is_array($row)) { continue; } $sourceKey = sanitize_text_field((string) ($row['source_key'] ?? '')); $target = sanitize_text_field((string) ($row['target'] ?? '')); $transform = sanitize_text_field((string) ($row['transform'] ?? '')); if ('' === $sourceKey || '' === $target || '' === $transform) { continue; } if (! OrderItemFieldMapper::isValidTarget($target) || ! OrderItemFieldMapper::isValidTransform($transform)) { continue; } $rows[] = [ 'source_key' => $sourceKey, 'target' => $target, 'transform' => $transform, 'enabled' => ! empty($row['enabled']), ]; } } update_option(Options::ORDER_ITEM_FIELD_MAPPINGS, $rows); } public function handleAjaxTestConnection(): void { if (! current_user_can('manage_woocommerce')) { wp_send_json_error([ 'message' => __('Insufficient permissions.', 'aivie-for-woocommerce'), ], 403); } check_ajax_referer('aivie_wc_test_connection_ajax', 'nonce'); $baseUrl = esc_url_raw((string) wp_unslash($_POST[Options::BASE_URL] ?? Options::getBaseUrl())); $clientId = sanitize_text_field((string) wp_unslash($_POST[Options::CLIENT_ID] ?? Options::getClientId())); $clientSecret = sanitize_text_field((string) wp_unslash($_POST[Options::CLIENT_SECRET] ?? '')); $timeoutRaw = absint($_POST[Options::TIMEOUT] ?? Options::getInt(Options::TIMEOUT)); $timeout = $timeoutRaw > 0 ? $timeoutRaw : 15; if (preg_match('/^\*+$/', $clientSecret)) { $clientSecret = Options::getClientSecret(); } Logger::debug('Testing Aivie connection from settings page.', [ 'base_url' => $baseUrl, 'has_client_id' => '' !== $clientId, 'has_secret' => '' !== $clientSecret, 'timeout' => $timeout, ]); $overrides = [ Options::BASE_URL => $baseUrl, Options::CLIENT_ID => $clientId, Options::CLIENT_SECRET => $clientSecret, Options::TIMEOUT => $timeout, ]; $filters = []; foreach ($overrides as $key => $value) { $hook = "pre_option_{$key}"; $callback = static fn () => $value; $filters[] = [$hook, $callback]; add_filter($hook, $callback); } $connections = new ConnectionManager(); if (! $connections->isConfigured()) { foreach ($filters as $filter) { remove_filter($filter[0], $filter[1]); } Logger::error('Connection test failed because no shared or fallback connection is configured.', [ 'base_url' => $baseUrl, ]); wp_send_json_error([ 'message' => __('Connect Aivie Marketing Automation or configure the legacy OAuth fallback first.', 'aivie-for-woocommerce'), ]); return; } $client = new AivieClient(); $response = $client->testConnection(); foreach ($filters as $filter) { remove_filter($filter[0], $filter[1]); } $ok = $response->success && isset($response->body['status'], $response->body['authenticated']) && 'ok' === $response->body['status'] && true === $response->body['authenticated']; if ($ok) { Logger::info('Connection test succeeded.', [ 'base_url' => $connections->baseUrl(), 'http_code' => $response->httpCode, ]); wp_send_json_success([ 'message' => __('Connection successful!', 'aivie-for-woocommerce'), ]); } $message = $response->getSafeMessage(); if ('' === $message) { if ($response->isAuthError()) { $message = __('Authentication failed. Please reconnect to Aivie via OAuth.', 'aivie-for-woocommerce'); } elseif (0 === $response->httpCode) { $message = __('Could not reach the Aivie server. Check the URL and timeout settings.', 'aivie-for-woocommerce'); } else { // translators: %d is the HTTP status code $message = sprintf(__('Server returned HTTP %d. Check your Aivie URL.', 'aivie-for-woocommerce'), $response->httpCode); } } Logger::error('Connection test failed.', [ 'base_url' => $connections->baseUrl(), 'http_code' => $response->httpCode, 'message' => $message, ]); wp_send_json_error(['message' => $message]); } public function handleOAuthStart(): void { if (! current_user_can('manage_woocommerce')) { wp_die(esc_html__('Insufficient permissions.', 'aivie-for-woocommerce')); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth start nonce is verified immediately below. $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce'] ?? '')); if (! wp_verify_nonce($nonce, 'aivie_wc_oauth_start')) { Logger::error('OAuth start failed because the nonce was invalid.'); wp_safe_redirect(add_query_arg(['page' => self::PAGE_SLUG, 'aivie_oauth_error' => 'invalid_nonce'], admin_url('admin.php'))); exit; } $baseUrl = Options::getBaseUrl(); $clientId = Options::getClientId(); if ('' === $baseUrl || '' === $clientId) { Logger::error('OAuth start failed because configuration is incomplete.', [ 'has_base_url' => '' !== $baseUrl, 'has_client_id' => '' !== $clientId, ]); wp_safe_redirect(add_query_arg(['page' => self::PAGE_SLUG, 'aivie_oauth_error' => 'missing_config'], admin_url('admin.php'))); exit; } $state = wp_generate_password(32, false); $callbackUrl = admin_url('admin-post.php?action=aivie_wc_oauth_callback'); set_transient("aivie_wc_oauth_state_{$state}", '1', 10 * MINUTE_IN_SECONDS); $authorizeUrl = add_query_arg([ 'response_type' => 'code', 'client_id' => rawurlencode($clientId), 'redirect_uri' => rawurlencode($callbackUrl), 'state' => rawurlencode($state), ], rtrim($baseUrl, '/') . '/oauth/v2/authorize'); Logger::info('Starting Aivie OAuth authorization.', [ 'base_url' => $baseUrl, 'callback_url' => $callbackUrl, ]); $this->redirectToOAuthAuthorizeUrl($authorizeUrl); exit; } public function redirectUnauthenticatedAdminPost(): void { wp_safe_redirect(wp_login_url(admin_url('admin.php?page=' . self::PAGE_SLUG))); exit; } private function redirectToOAuthAuthorizeUrl(string $authorizeUrl): void { $host = wp_parse_url($authorizeUrl, PHP_URL_HOST); if (! is_string($host) || '' === $host) { $this->oauthError('invalid_authorize_url'); return; } $allowOAuthHost = static function (array $hosts) use ($host): array { $hosts[] = $host; return array_unique($hosts); }; add_filter('allowed_redirect_hosts', $allowOAuthHost); wp_safe_redirect($authorizeUrl); remove_filter('allowed_redirect_hosts', $allowOAuthHost); } public function handleOAuthCallback(): void { if (! current_user_can('manage_woocommerce')) { wp_die(esc_html__('Insufficient permissions.', 'aivie-for-woocommerce')); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback is validated with the state token below. $state = sanitize_text_field(wp_unslash($_GET['state'] ?? '')); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback is validated with the state token below. $code = sanitize_text_field(wp_unslash($_GET['code'] ?? '')); if ('' === $state || '' === $code) { Logger::error('OAuth callback failed because the response was incomplete.', [ 'has_state' => '' !== $state, 'has_code' => '' !== $code, ]); $this->oauthError('invalid_response'); return; } $transientKey = "aivie_wc_oauth_state_{$state}"; if (! get_transient($transientKey)) { Logger::error('OAuth callback failed because the state token is invalid.'); $this->oauthError('invalid_state'); return; } delete_transient($transientKey); $callbackUrl = admin_url('admin-post.php?action=aivie_wc_oauth_callback'); $response = wp_remote_post(rtrim(Options::getBaseUrl(), '/') . '/oauth/v2/token', [ 'timeout' => Options::getInt(Options::TIMEOUT) ?: 15, 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'body' => [ 'grant_type' => 'authorization_code', 'client_id' => Options::getClientId(), 'client_secret' => Options::getClientSecret(), 'redirect_uri' => $callbackUrl, 'code' => $code, ], ]); if (is_wp_error($response)) { Logger::error('OAuth token request failed.', [ 'message' => $response->get_error_message(), ]); $this->oauthError('token_request_failed'); return; } $data = json_decode(wp_remote_retrieve_body($response), true); if (empty($data['access_token'])) { Logger::error('OAuth token response did not include an access token.', [ 'http_code' => wp_remote_retrieve_response_code($response), ]); $this->oauthError('no_access_token'); return; } Options::storeBearerToken($data['access_token'], $data['refresh_token'] ?? ''); Logger::info('OAuth connection completed successfully.', [ 'base_url' => Options::getBaseUrl(), 'has_refresh_token' => ! empty($data['refresh_token']), ]); wp_safe_redirect(add_query_arg(['page' => self::PAGE_SLUG, 'aivie_oauth_success' => '1'], admin_url('admin.php'))); exit; } private function oauthError(string $code): void { Logger::error('OAuth connection failed.', [ 'code' => $code, ]); set_transient('aivie_wc_last_auth_error', sprintf( /* translators: error code */ __('OAuth connection failed: %s. Please try reconnecting.', 'aivie-for-woocommerce'), $code ), HOUR_IN_SECONDS); wp_safe_redirect(add_query_arg(['page' => self::PAGE_SLUG, 'aivie_oauth_error' => $code], admin_url('admin.php'))); exit; } public function renderAuthErrorNotice(): void { $screen = get_current_screen(); if (! $screen || ! str_contains((string) $screen->id, self::PAGE_SLUG)) { return; } $error = get_transient('aivie_wc_last_auth_error'); if (! $error) { return; } echo '
' . esc_html($error) . '
' . esc_html__('No WooCommerce tax rates found. Configure tax rates under WooCommerce > Settings > Tax first.', 'aivie-for-woocommerce') . '
'; return; } $savedMap = Options::getTaxTreatmentMap(); $treatments = TaxTreatments::options(); $classLabels = $this->getTaxClassLabels(); ?>| tax_rate_name ?? '')); ?> | tax_rate ?? 0), 4, '.', ''), '0'), '.')); ?> |
renderDetectedOrderItemMetaSamples($sampleMap); ?>
| > |
|
' . esc_html__('No recent order item meta was detected. Create or sync an order with item meta first, then reload this page.', 'aivie-for-woocommerce') . '
'; return; } $preview = array_slice($samples, 0, 20, true); ?> |
' . esc_html__('No published items found or the list could not be loaded from Aivie.', 'aivie-for-woocommerce') . '
'; return; } ?> , custom: array