'Homepage', 'product' => 'Products', 'collection' => 'Product archives', 'cart' => 'Cart', 'page' => 'Pages', 'blog' => 'Blog index', 'article' => 'Posts', 'search' => 'Search results', ]; private static $color_presets = [ 'Emerald' => '#087a57', 'Ocean' => '#2563eb', 'Violet' => '#7c3aed', 'Rose' => '#db2777', 'Amber' => '#f59e0b', 'Graphite' => '#1f2937', ]; public static function boot() { self::maybe_migrate_legacy_settings(); add_action('admin_menu', [__CLASS__, 'admin_menu']); add_action('admin_enqueue_scripts', [__CLASS__, 'admin_assets']); add_action('admin_post_aismart_content_chat_connect', [__CLASS__, 'connect_callback']); add_action('admin_post_aismart_content_chat_save', [__CLASS__, 'save_settings']); add_action('admin_post_aismart_content_chat_disconnect', [__CLASS__, 'disconnect']); add_action('admin_post_aismart_content_chat_refresh', [__CLASS__, 'refresh_connection']); add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_widget']); add_filter('wp_script_attributes', [__CLASS__, 'widget_script_attributes']); add_filter('plugin_action_links_' . plugin_basename(__FILE__), [__CLASS__, 'plugin_action_links']); add_filter('aismart_company_plugins', [__CLASS__, 'studio_plugin_manifest']); } public static function activate() { self::maybe_migrate_legacy_settings(); } private static function maybe_migrate_legacy_settings() { if (get_option(self::OPTION, null) !== null) { return; } $legacy_settings = get_option(self::LEGACY_OPTION, null); add_option(self::OPTION, is_array($legacy_settings) ? $legacy_settings : self::defaults(), '', false); } public static function defaults() { return [ 'enabled' => true, 'page_mode' => 'all', 'page_types' => array_keys(self::$page_types), 'position' => 'bottom-right', 'accent_color' => '#087a57', 'title' => 'Chat with us', 'greeting' => 'Hi! How can we help today?', 'access_token' => '', 'widget_key' => '', 'workspace_id' => 0, 'connected_site_url' => '', 'connected_at' => '', 'last_synced_at' => '', ]; } public static function settings() { $stored = get_option(self::OPTION, []); return wp_parse_args(is_array($stored) ? $stored : [], self::defaults()); } public static function connection() { $settings = self::settings(); return [ 'connected' => $settings['access_token'] !== '' && preg_match('/^[a-f0-9]{32}$/', $settings['widget_key']), 'widget_key' => $settings['widget_key'], 'workspace_id' => absint($settings['workspace_id']), 'site_url' => $settings['connected_site_url'], 'connected_at' => $settings['connected_at'], 'last_synced_at' => $settings['last_synced_at'], ]; } public static function installation_token() { $settings = self::settings(); return (string) $settings['access_token']; } public static function api_base() { $base = apply_filters('aismart_content_chat_api_base', self::API_BASE); return untrailingslashit(esc_url_raw((string) $base)); } /** * The origin (scheme://host[:port]) of the connected site. The AISmart Content Chat service serves a widget's public * configuration only to requests that carry this origin: a browser adds it by itself, a server request must. */ private static function site_origin($url) { $parts = wp_parse_url((string) ($url !== '' ? $url : home_url('/'))); if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { return ''; } return strtolower($parts['scheme']) . '://' . strtolower($parts['host']) . (isset($parts['port']) ? ':' . (int) $parts['port'] : ''); } /** * The operators visitors can see in the chat box (name, presence, photo), read from the same public widget * configuration the storefront widget loads. An array (empty when nobody is chosen), or null when the list could * not be read, so the admin never says "nobody" because of a failed request. Cached briefly and never fatal. */ public static function operators() { $connection = self::connection(); if (!$connection['connected']) { return []; } $cache_key = self::OPERATORS_CACHE . $connection['widget_key']; $cached = get_transient($cache_key); if (is_array($cached)) { return $cached; } if ($cached === 'failed') { return null; } $origin = self::site_origin((string) $connection['site_url']); $response = $origin === '' ? null : wp_remote_get(self::api_base() . '/api/webchat/widget/' . $connection['widget_key'] . '/config', [ 'timeout' => 4, 'redirection' => 0, 'sslverify' => true, 'headers' => ['Accept' => 'application/json', 'Origin' => $origin], ]); if ($response === null || is_wp_error($response) || (int) wp_remote_retrieve_response_code($response) !== 200) { set_transient($cache_key, 'failed', MINUTE_IN_SECONDS); return null; } $team = []; $body = json_decode((string) wp_remote_retrieve_body($response), true); $members = is_array($body) && isset($body['data']['settings']['team']) ? (array) $body['data']['settings']['team'] : []; foreach (array_slice($members, 0, 8) as $member) { if (!is_array($member) || !in_array($member['status'] ?? '', ['online', 'idle'], true)) { continue; } $name = sanitize_text_field((string) ($member['name'] ?? '')); if ($name === '') { continue; } $team[] = [ 'name' => function_exists('mb_substr') ? mb_substr($name, 0, 60) : substr($name, 0, 60), 'status' => $member['status'], 'avatar' => esc_url_raw((string) ($member['avatarUrl'] ?? ''), ['https']), ]; } set_transient($cache_key, $team, $team ? 5 * MINUTE_IN_SECONDS : MINUTE_IN_SECONDS); return $team; } private static function initials($name) { $letters = ''; foreach (array_slice(preg_split('/\s+/u', trim((string) $name)) ?: [], 0, 2) as $word) { $letters .= function_exists('mb_substr') ? mb_substr($word, 0, 1) : substr($word, 0, 1); } return function_exists('mb_strtoupper') ? mb_strtoupper($letters) : strtoupper($letters); } private static function time_ago($iso) { $time = $iso ? strtotime((string) $iso) : false; return $time ? sprintf('%s ago', human_time_diff($time, time())) : 'Not yet'; } private static function faces(array $team, $limit = 4) { $shown = array_slice($team, 0, $limit); $more = count($team) - count($shown); foreach ($shown as $index => $member) { $label = $member['name'] . ' · ' . ($member['status'] === 'idle' ? 'Away' : 'Online'); $classes = ($member['status'] === 'idle' ? 'is-idle' : 'is-online') . ($index < count($shown) - 1 ? ' no-dot' : ''); ?> 0) { echo ''; } } public static function api_request($method, $path, $payload = [], $authenticated = true) { $headers = ['Accept' => 'application/json']; if ($authenticated) { $token = self::installation_token(); if ($token === '') { return new WP_Error('aismart_content_chat_not_connected', 'Connect AISmart Content Chat before using this feature.'); } $headers['Authorization'] = 'Bearer ' . $token; } $args = [ 'method' => strtoupper((string) $method), 'timeout' => 20, 'redirection' => 0, 'sslverify' => true, 'headers' => $headers, ]; if ($payload !== []) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode($payload); } $response = wp_remote_request(self::api_base() . '/' . ltrim((string) $path, '/'), $args); if (is_wp_error($response)) { return $response; } $status = (int) wp_remote_retrieve_response_code($response); $body = json_decode((string) wp_remote_retrieve_body($response), true); if ($status < 200 || $status >= 300 || !is_array($body) || empty($body['success'])) { $message = is_array($body) && !empty($body['msg']) ? sanitize_text_field((string) $body['msg']) : 'The chat service returned an unexpected response.'; return new WP_Error('aismart_content_chat_api_error', $message, ['status' => $status]); } return isset($body['data']) && is_array($body['data']) ? $body['data'] : []; } public static function admin_menu() { add_options_page( 'AISmart Content Chat', 'AISmart Content Chat', 'manage_options', 'aismart-content-chat', [__CLASS__, 'chat_page'] ); add_submenu_page('options-general.php', 'Plugin Hub', 'Plugin Hub', 'manage_options', 'aismart-content-chat-hub', [__CLASS__, 'hub_page']); add_submenu_page('options-general.php', 'Lead Capture', 'Lead Capture', 'manage_options', 'aismart-content-chat-leads', [__CLASS__, 'lead_page']); add_submenu_page('options-general.php', 'Site Automations', 'Site Automations', 'manage_options', 'aismart-content-chat-automations', [__CLASS__, 'automations_page']); } public static function admin_assets($hook) { if (strpos((string) $hook, 'aismart-content-chat') === false) { return; } wp_enqueue_style( 'aismart-content-chat-admin', plugins_url('assets/admin.css', __FILE__), [], self::VERSION ); wp_enqueue_script( 'aismart-content-chat-admin', plugins_url('assets/admin.js', __FILE__), [], self::VERSION, true ); } private static function assert_admin() { if (!current_user_can('manage_options')) { wp_die(esc_html__('You are not allowed to manage AISmart Content Chat.', 'aismart-content-chat')); } } private static function notice_redirect($notice, $error = '') { $args = [ 'page' => 'aismart-content-chat', 'tw_notice' => sanitize_key($notice), 'tw_notice_nonce' => wp_create_nonce('aismart_content_chat_notice'), ]; if ($error !== '') { set_transient('aismart_content_chat_notice_' . get_current_user_id(), sanitize_text_field($error), 60); } wp_safe_redirect(add_query_arg($args, admin_url('options-general.php'))); exit; } private static function connect_url() { $transient = self::CONNECT_STATE . get_current_user_id(); $state = (string) get_transient($transient); if ($state === '') { $state = wp_generate_password(48, false, false); set_transient($transient, $state, 10 * MINUTE_IN_SECONDS); } return add_query_arg([ 'page' => 'marketplace', 'collection' => 'wordpress', 'wordpress_site' => untrailingslashit(home_url('/')), 'wordpress_return' => admin_url('admin-post.php'), 'wordpress_state' => $state, ], self::api_base() . '/user'); } public static function connect_callback() { self::assert_admin(); $expected = (string) get_transient(self::CONNECT_STATE . get_current_user_id()); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The external authorization callback is verified against a one-time, user-bound state token below. $state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The authorization code is accepted only with the verified one-time state token. $code = isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : ''; if ($expected === '' || $state === '' || !hash_equals($expected, $state) || $code === '') { self::notice_redirect('error', 'The WordPress connection request expired or was invalid.'); } delete_transient(self::CONNECT_STATE . get_current_user_id()); $settings = self::settings(); $result = self::api_request('POST', 'api/integrations/webchat/wordpress/exchange', [ 'code' => $code, 'siteUrl' => untrailingslashit(home_url('/')), 'name' => sanitize_text_field(get_bloginfo('name')) . ' chat', 'settings' => self::remote_settings($settings), ], false); if (is_wp_error($result)) { self::notice_redirect('error', $result->get_error_message()); } $widget = isset($result['widget']) && is_array($result['widget']) ? $result['widget'] : []; $settings['access_token'] = sanitize_text_field((string) ($result['accessToken'] ?? '')); $settings['widget_key'] = sanitize_key((string) ($widget['widgetKey'] ?? '')); $settings['workspace_id'] = absint($result['workspaceId'] ?? 0); $settings['connected_site_url'] = esc_url_raw((string) ($result['siteUrl'] ?? home_url('/'))); $settings['connected_at'] = gmdate('c'); $settings['last_synced_at'] = gmdate('c'); self::merge_remote_widget($settings, $widget); update_option(self::OPTION, $settings, false); do_action('aismart_content_chat_connected', self::connection()); self::notice_redirect('connected'); } private static function posted_settings(array $request) { $page_type_input = isset($request['page_types']) && is_array($request['page_types']) ? $request['page_types'] : []; $page_types = []; foreach ($page_type_input as $page_type) { if (!is_scalar($page_type)) { continue; } $page_type = sanitize_key((string) $page_type); if (isset(self::$page_types[$page_type])) { $page_types[] = $page_type; } } $page_types = array_values(array_unique($page_types)); $page_mode = isset($request['page_mode']) && is_scalar($request['page_mode']) ? sanitize_key((string) $request['page_mode']) : ''; $position = isset($request['position']) && is_scalar($request['position']) ? sanitize_key((string) $request['position']) : ''; $accent = isset($request['accent_color']) && is_scalar($request['accent_color']) ? sanitize_hex_color((string) $request['accent_color']) : ''; $title = isset($request['title']) && is_scalar($request['title']) ? sanitize_text_field((string) $request['title']) : 'Chat with us'; $greeting = isset($request['greeting']) && is_scalar($request['greeting']) ? sanitize_textarea_field((string) $request['greeting']) : 'Hi! How can we help today?'; return [ 'enabled' => isset($request['enabled']), 'page_mode' => $page_mode === 'selected' ? 'selected' : 'all', 'page_types' => $page_types !== [] ? $page_types : array_keys(self::$page_types), 'position' => $position === 'bottom-left' ? 'bottom-left' : 'bottom-right', 'accent_color' => $accent ?: '#087a57', 'title' => $title, 'greeting' => $greeting, ]; } private static function remote_settings($settings) { return [ 'enabled' => !empty($settings['enabled']), 'pageMode' => $settings['page_mode'] === 'selected' ? 'selected' : 'all', 'pageTypes' => array_values((array) $settings['page_types']), 'position' => $settings['position'], 'accentColor' => $settings['accent_color'], 'title' => $settings['title'], 'greeting' => $settings['greeting'], ]; } private static function merge_remote_widget(&$settings, $widget) { if (!is_array($widget)) { return; } $remote = isset($widget['settings']) && is_array($widget['settings']) ? $widget['settings'] : []; $settings['widget_key'] = sanitize_key((string) ($widget['widgetKey'] ?? $settings['widget_key'])); $settings['enabled'] = !empty($remote['enabled']); $settings['page_mode'] = ($remote['pageMode'] ?? '') === 'selected' ? 'selected' : 'all'; $settings['page_types'] = array_values(array_intersect(array_keys(self::$page_types), (array) ($remote['pageTypes'] ?? []))); $settings['position'] = ($remote['position'] ?? '') === 'bottom-left' ? 'bottom-left' : 'bottom-right'; $settings['accent_color'] = sanitize_hex_color($remote['accentColor'] ?? '') ?: '#087a57'; $settings['title'] = sanitize_text_field((string) ($remote['title'] ?? $settings['title'])); $settings['greeting'] = sanitize_textarea_field((string) ($remote['greeting'] ?? $settings['greeting'])); $settings['last_synced_at'] = gmdate('c'); } public static function save_settings() { self::assert_admin(); check_admin_referer('aismart_content_chat_save'); $request = wp_unslash($_POST); $settings = array_merge(self::settings(), self::posted_settings(is_array($request) ? $request : [])); if (self::connection()['connected']) { $result = self::api_request('PUT', 'api/integrations/webchat/wordpress/installation', [ 'name' => sanitize_text_field(get_bloginfo('name')) . ' chat', 'settings' => self::remote_settings($settings), ]); if (is_wp_error($result)) { self::notice_redirect('error', $result->get_error_message()); } self::merge_remote_widget($settings, $result['widget'] ?? []); } update_option(self::OPTION, $settings, false); self::notice_redirect('saved'); } public static function refresh_connection() { self::assert_admin(); check_admin_referer('aismart_content_chat_refresh'); $result = self::api_request('GET', 'api/integrations/webchat/wordpress/installation'); if (is_wp_error($result)) { self::notice_redirect('error', $result->get_error_message()); } $settings = self::settings(); self::merge_remote_widget($settings, $result['widget'] ?? []); update_option(self::OPTION, $settings, false); delete_transient(self::OPERATORS_CACHE . $settings['widget_key']); self::notice_redirect('refreshed'); } public static function disconnect() { self::assert_admin(); check_admin_referer('aismart_content_chat_disconnect'); $result = self::api_request('DELETE', 'api/integrations/webchat/wordpress/installation'); if (is_wp_error($result)) { self::notice_redirect('error', $result->get_error_message()); } $settings = array_merge(self::settings(), [ 'access_token' => '', 'widget_key' => '', 'workspace_id' => 0, 'connected_site_url' => '', 'connected_at' => '', 'last_synced_at' => '', ]); update_option(self::OPTION, $settings, false); do_action('aismart_content_chat_disconnected'); self::notice_redirect('disconnected'); } public static function enqueue_widget() { $settings = self::settings(); if (empty($settings['enabled']) || !preg_match('/^[a-f0-9]{32}$/', (string) $settings['widget_key'])) { return; } wp_enqueue_script( 'aismart-content-chat-widget', self::api_base() . '/telewhats-webchat-widget.js?v=20261030-wporg-1', [], self::VERSION, true ); wp_script_add_data('aismart-content-chat-widget', 'strategy', 'async'); } private static function current_page_type() { if (function_exists('is_cart') && is_cart()) { return 'cart'; } if (function_exists('is_product') && is_product()) { return 'product'; } if ((function_exists('is_shop') && is_shop()) || (function_exists('is_product_taxonomy') && is_product_taxonomy())) { return 'collection'; } if (is_search()) { return 'search'; } if (is_front_page()) { return 'index'; } if (is_home()) { return 'blog'; } if (is_single()) { return 'article'; } return 'page'; } public static function widget_script_attributes($attributes) { if (($attributes['id'] ?? '') !== 'aismart-content-chat-widget-js') { return $attributes; } $settings = self::settings(); $commerce_enabled = defined('AISMART_CONTENT_COMMERCE_PLUGIN') && class_exists('WooCommerce'); $attributes['data-widget'] = (string) $settings['widget_key']; $attributes['data-page-type'] = self::current_page_type(); $attributes['data-commerce-url'] = $commerce_enabled ? admin_url('admin-ajax.php') : ''; $attributes['data-commerce-nonce'] = $commerce_enabled ? wp_create_nonce('telewhats_wc_storefront') : ''; return $attributes; } public static function plugin_action_links($links) { array_unshift($links, 'Settings'); return $links; } public static function studio_plugin_manifest($plugins) { $plugins = is_array($plugins) ? $plugins : []; $plugins['aismart-content-chat'] = [ 'name' => 'AISmart Content Chat', 'version' => self::VERSION, 'connected' => self::connection()['connected'], 'settings_url' => admin_url('options-general.php?page=aismart-content-chat'), ]; return $plugins; } private static function page_header($title, $description) { $connection = self::connection(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only compared with the fixed page slugs below to mark the current tab. $current = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; $pages = [ 'aismart-content-chat' => 'Chat Widget', 'aismart-content-chat-hub' => 'Plugin Hub', 'aismart-content-chat-leads' => 'Lead Capture', 'aismart-content-chat-automations' => 'Site Automations', ]; ?>

AISmart Content · AI Chat Hub

'WordPress is connected and its chat widget is ready.', 'saved' => 'Chat settings saved to WordPress and the chat service.', 'refreshed' => 'The latest widget settings were loaded from the chat service.', 'disconnected' => 'WordPress was disconnected and its storefront widget was paused.', ]; if ($notice === 'error') { $message = (string) get_transient('aismart_content_chat_notice_' . get_current_user_id()); delete_transient('aismart_content_chat_notice_' . get_current_user_id()); echo '

' . esc_html($message ?: 'The chat service could not complete that request.') . '

'; } elseif (isset($messages[$notice])) { echo '

' . esc_html($messages[$notice]) . '

'; } } private static function connection_section() { $connection = self::connection(); $host = $connection['connected'] ? (string) wp_parse_url((string) $connection['site_url'], PHP_URL_HOST) : ''; ?>
Workspace connection

Connect AISmart Content Chat
What visitors see

Storefront

Widget settings

$preset_hex) : ?>
Launcher position
Page visibility
$label) : ?>
Connect AISmart Content Chat before publishing settings.

AISmart Content Chat owns the one WordPress widget. Commerce extensions reuse that connection and never create another widget.

Open
Native chat form

Name and email capture

The widget collects a visitor name and optional email before messages enter the WordPress workspace conversation queue.

Available
Advanced forms

Chat forms

Build qualification fields, consent steps, routing rules, and follow-up actions in AISmart Content Chat.

Open Lead Forms
Conversation source

WordPress chat events

Incoming widget messages are tagged as native webchat and assigned to this site’s AISmart Content workspace.

Workflow builder

Automations

Create replies, assignments, labels, and timed follow-up from the AISmart Content automation workspace.

Open Automations