' . esc_html__('Settings', 'orewio') . ''); } return $links; } private static function state(): array { $value = get_option(self::OPTION, []); return is_array($value) ? $value : []; } private static function save(array $value): void { if (get_option(self::OPTION, null) === null) { add_option(self::OPTION, $value, '', false); } else { update_option(self::OPTION, $value, false); } } private static function site_url(): string { return trailingslashit(home_url('/')); } private static function request(string $path, array $body, ?string $credential = null) { $headers = ['Content-Type' => 'application/json', 'Accept' => 'application/json']; if ($credential !== null) { $headers['X-Orewio-Connection-Credential'] = $credential; } return wp_remote_post(self::ORIGIN . $path, [ 'timeout' => 8, 'redirection' => 0, 'sslverify' => true, 'headers' => $headers, 'body' => wp_json_encode($body), ]); } private static function valid_response($response): ?array { if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return null; } $data = json_decode(wp_remote_retrieve_body($response), true); return is_array($data) ? $data : null; } private static function revoke_grant(array $state): bool { if (empty($state['credential']) || empty($state['grant_id'])) return true; $response = self::request('/api/integrations/wordpress/' . rawurlencode($state['grant_id']) . '/revoke', ['siteUrl' => $state['site_url'] ?? self::site_url()], $state['credential']); return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 204; } private static function require_admin(string $action): void { if (!current_user_can('manage_options')) { wp_die(esc_html__('You cannot manage Orewio.', 'orewio')); } check_admin_referer('orewio_' . $action); } private static function redirect(string $notice): void { wp_safe_redirect(add_query_arg(['page' => 'orewio', 'orewio_notice' => $notice], admin_url('options-general.php'))); exit; } public static function connect(): void { self::require_admin('connect'); check_admin_referer('orewio_connect'); $prior = self::state(); if (!empty($prior['pending_revoke']) && is_array($prior['pending_revoke'])) { self::retry_pending_revoke(); if (!empty(self::state()['pending_revoke'])) self::redirect('old_disconnect_pending'); } $key = isset($_POST['orewio_connection_key']) && is_string($_POST['orewio_connection_key']) ? sanitize_text_field(wp_unslash($_POST['orewio_connection_key'])) : ''; if (!preg_match('/^[A-Za-z0-9_-]{43}$/D', $key)) { self::redirect('invalid_key'); } $response = self::valid_response(self::request('/api/integrations/wordpress/redeem', ['connectionKey' => $key, 'siteUrl' => self::site_url()])); unset($key); if ($response === null || !is_string($response['grantId'] ?? null) || !is_string($response['credential'] ?? null) || !is_string($response['publicKey'] ?? null) || !is_string($response['botName'] ?? null) || $response['botName'] === '' || !preg_match('/^[A-Za-z0-9_-]{43}$/D', $response['credential']) || !preg_match('/^[a-f0-9]{32}$/iD', $response['publicKey']) || !preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iD', $response['grantId'])) { self::redirect('connect_failed'); } $old = self::state(); self::save([ 'grant_id' => sanitize_text_field($response['grantId']), 'credential' => $response['credential'], 'public_key' => sanitize_text_field($response['publicKey']), 'bot_name' => sanitize_text_field($response['botName']), 'site_url' => self::site_url(), 'enabled' => false, 'status' => 'ACTIVE', 'checked_at' => time(), 'last_verified_at' => time(), ]); if (!empty($old['credential']) && !empty($old['grant_id'])) { if (!self::revoke_grant($old)) { $current = self::state(); $current['pending_revoke'] = $old; self::save($current); self::redirect('connected_old_pending'); } } self::redirect('connected'); } public static function enable(): void { self::require_admin('enable'); self::check(); $state = self::state(); if (!empty($state['credential']) && ($state['status'] ?? '') === 'ACTIVE' && empty($state['check_unavailable']) && ($state['site_url'] ?? '') === self::site_url()) { $state['enabled'] = true; self::save($state); self::redirect('enabled'); } self::redirect('not_active'); } public static function disable(): void { self::require_admin('disable'); $state = self::state(); $state['enabled'] = false; self::save($state); self::redirect('disabled'); } public static function disconnect(): void { self::require_admin('disconnect'); $state = self::state(); $state['enabled'] = false; $state['status'] = 'DISCONNECT_PENDING'; self::save($state); self::revoke_pending(); self::redirect(self::state() ? 'disconnect_pending' : 'disconnected'); } private static function revoke_pending(): void { self::retry_pending_revoke(); $state = self::state(); if (self::revoke_grant($state)) { if (!empty($state['pending_revoke'])) { self::save(['pending_revoke' => $state['pending_revoke'], 'status' => 'DISCONNECT_PENDING']); } else { delete_option(self::OPTION); } } } private static function retry_pending_revoke(): void { $state = self::state(); if (empty($state['pending_revoke']) || !is_array($state['pending_revoke'])) return; if (self::revoke_grant($state['pending_revoke'])) { unset($state['pending_revoke']); if (($state['status'] ?? '') === 'DISCONNECT_PENDING' && empty($state['credential'])) { delete_option(self::OPTION); } else { self::save($state); } } } public static function check_action(): void { self::require_admin('check'); self::check(); self::redirect('checked'); } public static function check(): void { self::retry_pending_revoke(); $state = self::state(); if (($state['status'] ?? '') === 'DISCONNECT_PENDING') { self::revoke_pending(); return; } if (empty($state['credential']) || empty($state['grant_id'])) return; $state['check_attempt_at'] = time(); $response = self::request('/api/integrations/wordpress/' . rawurlencode($state['grant_id']) . '/status', ['siteUrl' => self::site_url()], $state['credential']); if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 401) { $state['status'] = 'NEEDS_RECONNECTION'; $state['enabled'] = false; } else { $data = self::valid_response($response); if ($data !== null && isset($data['state'])) { $state['status'] = $data['state'] === 'ACTIVE' ? 'ACTIVE' : 'NEEDS_RECONNECTION'; if ($state['status'] !== 'ACTIVE') $state['enabled'] = false; if (!empty($data['botName']) && is_string($data['botName'])) { $state['bot_name'] = sanitize_text_field($data['botName']); } if (is_string($data['publicKey'] ?? null) && preg_match('/^[a-f0-9]{32}$/iD', $data['publicKey'])) { $state['public_key'] = $data['publicKey']; } } else { $state['check_unavailable'] = true; self::save($state); return; } } $state['check_unavailable'] = false; if (($state['status'] ?? '') === 'ACTIVE') $state['last_verified_at'] = time(); $state['checked_at'] = time(); self::save($state); } public static function enqueue(): void { $state = self::state(); if (empty($state['enabled']) || ($state['status'] ?? '') !== 'ACTIVE' || ($state['site_url'] ?? '') !== self::site_url() || !is_string($state['public_key'] ?? null) || !preg_match('/^[a-f0-9]{32}$/iD', $state['public_key']) || !is_string($state['credential'] ?? null) || $state['credential'] === '') return; wp_enqueue_script('orewio-widget', self::ORIGIN . '/public/widget.js', [], '0.1.7', true); } public static function script_tag(string $tag, string $handle, string $src): string { if ($handle !== 'orewio-widget') return $tag; $state = self::state(); if (!is_string($state['public_key'] ?? null) || !preg_match('/^[a-f0-9]{32}$/iD', $state['public_key'])) return ''; return wp_get_script_tag(['src' => esc_url($src), 'data-widget-id' => $state['public_key']]); } private static function form(string $action, string $label, bool $primary = false): void { echo '
'; echo ''; wp_nonce_field('orewio_' . $action); submit_button($label, $primary ? 'primary' : 'secondary', 'orewio_' . $action . '_submit', false); echo '
'; } private static function manage_url(array $state): string { $url = self::ORIGIN . '/app/integrations/wordpress'; $key = $state['public_key'] ?? ''; return is_string($key) && preg_match('/^[a-f0-9]{32}$/iD', $key) ? add_query_arg('bot', $key, $url) : ''; } private static function account_url(string $page): string { return add_query_arg('returnUrl', '/app/integrations/wordpress', self::ORIGIN . '/auth/' . $page); } private static function bot_display_name($name): string { if (!is_string($name) || $name === '') return __('Connected Bot', 'orewio'); return $name === 'Default workspace' ? __('Default widget', 'orewio') : $name; } private static function notice_message(string $notice): string { $messages = [ 'invalid_key' => __('Enter a valid WordPress Connection Key. Your existing connection was not changed.', 'orewio'), 'connect_failed' => __('Connection could not be completed. Your existing connection was not changed. The key may be expired or already used. Check Orewio and generate a new key before trying again.', 'orewio'), 'old_disconnect_pending' => __('The previous connection still needs to be disconnected. Your current Bot was not changed. Use Check connection to retry cleanup, or revoke the previous connection in Orewio.', 'orewio'), 'connected_old_pending' => __('New Bot connected; its widget is disabled. The previous connection has not been fully disconnected. Use Check connection to retry cleanup, or revoke the previous connection in Orewio.', 'orewio'), 'connected' => __('Bot connected. Review its details, then enable the widget when you are ready.', 'orewio'), 'enabled' => __('Widget enabled on this site.', 'orewio'), 'not_active' => __('The connection could not be verified. The widget remains disabled. Review the connection status below.', 'orewio'), 'disabled' => __('Widget disabled on this site.', 'orewio'), 'disconnect_pending' => __('Widget disabled. Remote disconnect is not complete. Retry later or revoke the site in Orewio.', 'orewio'), 'disconnected' => __('This website is disconnected from Orewio.', 'orewio'), 'checked' => __('Connection check completed. Review the current status below.', 'orewio'), ]; return $messages[$notice] ?? ''; } private static function admin_presentation(): void { echo ''; echo ''; } public static function page(): void { if (!current_user_can('manage_options')) return; $state = self::state(); if (!empty($state['credential']) && time() - (int) ($state['check_attempt_at'] ?? 0) > 300) { self::check(); $state = self::state(); } $connected = !empty($state['credential']); $pending = ($state['status'] ?? '') === 'DISCONNECT_PENDING'; $unavailable = !empty($state['check_unavailable']); $reconnect = $connected && !$pending && ($state['status'] ?? '') !== 'ACTIVE'; $enabled = !empty($state['enabled']); $noticeInput = filter_input(INPUT_GET, 'orewio_notice', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $notice = is_string($noticeInput) ? sanitize_key($noticeInput) : ''; echo '

' . esc_html__('Orewio', 'orewio') . '

'; self::admin_presentation(); $noticeMessage = self::notice_message($notice); if ($noticeMessage !== '') echo '

' . esc_html($noticeMessage) . '

'; echo '
'; if ($connected) { echo '

' . esc_html__('Connected Bot', 'orewio') . '

'; echo '

' . esc_html(self::bot_display_name($state['bot_name'] ?? '')) . '

'; echo '

' . esc_html($state['site_url'] ?? '') . '

'; $manageUrl = self::manage_url($state); if ($manageUrl !== '') { echo '' . esc_html__('Manage Bot in Orewio (opens in a new tab)', 'orewio') . ''; } else { echo '

Bot navigation is unavailable. Check the connection before managing this Bot.

'; } $connection = $pending ? 'Disconnect pending' : ($unavailable ? 'Check unavailable - last known state shown' : ($reconnect ? 'Reconnect required' : 'Verified')); echo '

Connection: ' . esc_html($connection) . '

Widget on this site: ' . ($enabled ? 'Enabled' : 'Disabled') . '

'; $verifiedAt = (int) ($state['last_verified_at'] ?? ((!$reconnect && !$pending) ? ($state['checked_at'] ?? 0) : 0)); $siteTimezone = wp_timezone_string(); if (preg_match('/^[+-][0-9]{2}:[0-9]{2}$/D', $siteTimezone)) $siteTimezone = 'UTC' . $siteTimezone; if ($verifiedAt > 0) echo '

Last verified: ' . esc_html(wp_date(get_option('date_format') . ' · ' . get_option('time_format'), $verifiedAt)) . ' (' . esc_html($siteTimezone) . ' site time)

'; } else { echo '

Add an AI assistant to your website

Orewio adds a chat assistant that answers visitors using information you provide. Create and manage this assistant (your Bot) in your Orewio account, then use this plugin to connect it to WordPress. Your Orewio account is separate from your WordPress login.

'; } echo '
'; if ($pending) { echo '
Widget disabled. Remote disconnect is not complete. Retry later, or revoke this site in Orewio.
'; self::form('disconnect', 'Retry disconnect', true); echo '
'; } else { if ($unavailable) echo '
The connection check is temporarily unavailable. The last known widget setting is retained. Try again before changing the connection.
'; if (!empty($state['pending_revoke'])) echo '
The previous connection has not been fully disconnected. Your current Bot is shown above. Use Check connection to retry cleanup before changing Bot again.
'; if ($reconnect && !$unavailable) echo '
Reconnect this Bot before enabling its widget. Generate a new Connection Key in Orewio.
'; if ($connected) { echo '
'; if ($unavailable) self::form('check', 'Try again', true); elseif ($reconnect) echo 'Reconnect Bot'; elseif (!$enabled) self::form('enable', 'Enable widget', true); echo 'View on website (opens in a new tab)'; if ($enabled) self::form('disable', 'Disable widget'); if (!$unavailable && !empty($state['pending_revoke'])) self::form('check', 'Check connection'); echo '
'; } else { echo ''; echo '

Keep this WordPress tab open while setting up Orewio. Already have a Connection Key? Go to Connection Key.

'; echo '
  1. Account

    Use Create Orewio account above, or Open Orewio if you already have an account. Verify your email if asked.

    In Orewio, select or create your Bot using the selector at the top of the sidebar. On mobile, open the menu first. In Sources, add the information your assistant should use to answer visitors.

  2. Connection Key

    Return to this WordPress tab and click Open Orewio above. This opens the WordPress connection page in Orewio. Check the Bot name, then click Generate Connection Key and Copy key. This private, one-time key tells the plugin which Bot to connect.

  3. Connect & Test

    Return to this WordPress tab: Settings → Orewio. Paste the key into WordPress Connection Key below and click Connect Bot.

    Check the Bot name, click Enable widget, then View on website. Open the chat and ask a question covered by the information you added.

This plugin never asks for your Orewio password.

'; } } echo '
'; if (!$pending && empty($state['pending_revoke'])) { echo '
' . ($connected ? 'Change Bot or reconnect' : 'Connect a Bot') . ''; if ($connected) echo '

A successful replacement leaves the new widget disabled. Review the new Bot, then explicitly enable it. A failed connection attempt keeps your existing connection.

'; if ($connected) echo '

In Orewio, select the Bot you want, then generate a fresh key in Integrations → WordPress.

Open Orewio (opens in a new tab)

'; echo '
'; wp_nonce_field('orewio_connect'); echo '

Use a fresh key. It is shown once in Orewio and expires after 24 hours.

'; submit_button($connected ? 'Connect new Bot' : 'Connect Bot', 'primary', 'orewio_connect_submit', false); if ($connected) echo ''; echo '
'; } echo '
Connection help'; if ($connected && !$pending && !$unavailable && empty($state['pending_revoke'])) self::form('check', 'Check connection'); echo '

Test your widget. Open your public website, check the launcher and send a question covered by your Bot’s knowledge.

Widget missing after a change? Clear your website’s full-page cache and open its public page again. Check whether script optimization or your site’s Content Security Policy blocks the widget.

Connection verified does not mean chat answers were tested. Answers depend on eligible knowledge, an active plan and available responses. Manage these in Orewio.

Connection Key selects one Bot. Do not share it. The plugin stores a limited site connection, never your Orewio password.

Use the connected Bot’s Orewio settings to edit content or appearance. Enabling this widget does not obtain visitor consent; review your privacy notice and consent obligations.

'; if ($connected && !$pending) { echo '
Disconnect

Disconnect this website? This disables its widget and revokes this site’s connection. Reconnecting requires a new Connection Key. Other websites and your Bot’s knowledge are not deleted. Cached pages may retain the loader until their cache is cleared.

'; self::form('disconnect', 'Disconnect website'); echo '
'; } echo '

'; } public static function privacy_content(): void { if (!function_exists('wp_add_privacy_policy_content')) return; $text = '

When the Orewio widget is enabled, visitors’ browsers load the chatbot from Orewio. ' . 'Those requests disclose the visitor IP address and browser request details to Orewio. ' . 'Visitor questions, feedback and optional contact details are sent directly to Orewio; ' . 'the plugin does not store those conversations in WordPress. The widget keeps its conversation ' . 'identifier in memory while the page is open. Review the Orewio Privacy Policy ' . 'and Terms for service details.

'; wp_add_privacy_policy_content('Orewio', wp_kses_post($text)); } } Orewio_WordPress::init(); register_activation_hook(__FILE__, ['Orewio_WordPress', 'activate']); register_deactivation_hook(__FILE__, ['Orewio_WordPress', 'deactivate']);