$origin, 'slug' => strtolower($m[1])); } /** Currently connected chatbot (origin + slug) or null. */ function plapperbot_bot() { return plapperbot_parse_link(get_option(PLAPPERBOT_OPTION, '')); } /** Display rules with defaults. */ function plapperbot_display() { $defaults = array( 'mode' => 'all', // all | only | except 'pages' => array(), // post IDs for "only" / "except" 'post_types' => array(), // empty = all 'device' => 'all', // all | desktop | mobile 'position' => 'right', // right | left 'hide_admins' => false, 'privacy' => true, // load nothing from plapperbot.de until a visitor opens the chat (on by default) ); $saved = get_option(PLAPPERBOT_DISPLAY_OPTION, array()); return wp_parse_args(is_array($saved) ? $saved : array(), $defaults); } /** Link with tracking parameters to plapperbot.de. */ function plapperbot_url($path = '/', $campaign = 'plugin-admin') { return add_query_arg( array('utm_source' => 'wordpress', 'utm_medium' => 'plugin', 'utm_campaign' => $campaign), PLAPPERBOT_SITE . $path ); } /** * Reads JSON from the plapperbot API and caches it briefly (transient). * * @return array|null Decoded response or null on error. */ function plapperbot_remote($path, $cache_key, $ttl, $headers = array()) { $cached = get_transient($cache_key); if (is_array($cached)) { return $cached; } $response = wp_remote_get(PLAPPERBOT_SITE . $path, array( 'timeout' => 6, 'headers' => array_merge(array('Accept' => 'application/json'), $headers), 'user-agent' => 'plapperbot-wordpress/' . PLAPPERBOT_VERSION, )); if (is_wp_error($response)) { return null; } $code = (int) wp_remote_retrieve_response_code($response); $data = json_decode(wp_remote_retrieve_body($response), true); if (!is_array($data)) { return null; } $data['_status'] = $code; // Errors only briefly, so a fix (e.g. a new key) shows up quickly set_transient($cache_key, $data, $code === 200 ? $ttl : MINUTE_IN_SECONDS); return $data; } /** Public chatbot data (name, logo, plan, availability). */ function plapperbot_remote_bot() { $bot = plapperbot_bot(); if (!$bot) { return null; } return plapperbot_remote('/api/public/bots/' . rawurlencode($bot['slug']), 'plapperbot_bot_' . md5($bot['slug']), 5 * MINUTE_IN_SECONDS); } /** Key figures of the last 30 days (requires the plugin key). */ function plapperbot_remote_stats() { $key = (string) get_option(PLAPPERBOT_KEY_OPTION, ''); if ($key === '') { return null; } return plapperbot_remote('/api/plugin/stats', 'plapperbot_stats_' . md5($key), 10 * MINUTE_IN_SECONDS, array('x-plapperbot-key' => $key)); } /** Plans and prices (public settings). */ function plapperbot_remote_plans() { return plapperbot_remote('/api/public/settings', 'plapperbot_plans', 12 * HOUR_IN_SECONDS); } /** Clears all cached API responses (after saving settings). */ function plapperbot_clear_remote_cache() { delete_transient('plapperbot_plans'); $bot = plapperbot_bot(); if ($bot) { delete_transient('plapperbot_bot_' . md5($bot['slug'])); } $key = (string) get_option(PLAPPERBOT_KEY_OPTION, ''); if ($key !== '') { delete_transient('plapperbot_stats_' . md5($key)); } } /** Human-readable plan name. */ function plapperbot_plan_label($plan, $tier) { switch ($plan) { case 'active': return $tier === 'pro' ? 'Pro' : 'Plus'; case 'free': return __('Free', 'plapperbot'); case 'trial': return __('Trial', 'plapperbot'); case 'inactive': return __('Paused', 'plapperbot'); } return ''; } /** Plan key for comparison with the plan cards: free | plus | pro | null */ function plapperbot_plan_key($plan, $tier) { if ($plan === 'free') { return 'free'; } if ($plan === 'active') { return $tier === 'pro' ? 'pro' : 'plus'; } return null; } /* ------------------------------------------------------------------------- * Page cache: clear after changes, otherwise caching plugins keep serving pages without the chat bubble * ---------------------------------------------------------------------- */ function plapperbot_purge_caches() { do_action('litespeed_purge_all'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- public hook of LiteSpeed Cache to clear the page cache. if (function_exists('rocket_clean_domain')) { rocket_clean_domain(); } if (function_exists('w3tc_flush_all')) { w3tc_flush_all(); } if (function_exists('wp_cache_clear_cache')) { wp_cache_clear_cache(); } if (function_exists('wpfc_clear_all_cache')) { wpfc_clear_all_cache(true); } if (class_exists('autoptimizeCache') && method_exists('autoptimizeCache', 'clearall')) { autoptimizeCache::clearall(); } if (function_exists('sg_cachepress_purge_cache')) { sg_cachepress_purge_cache(); } do_action('wphb_clear_page_cache'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- public hook of Hummingbird. do_action('cache_enabler_clear_complete_cache'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- public hook of Cache Enabler. do_action('breeze_clear_all_cache'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- public hook of Breeze. do_action('rt_nginx_helper_purge_all'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- public hook of Nginx Helper. if (function_exists('wp_cache_flush')) { wp_cache_flush(); } } foreach (array(PLAPPERBOT_OPTION, PLAPPERBOT_KEY_OPTION, PLAPPERBOT_DISPLAY_OPTION) as $plapperbot_option) { add_action('add_option_' . $plapperbot_option, 'plapperbot_purge_caches'); add_action('update_option_' . $plapperbot_option, 'plapperbot_purge_caches'); } unset($plapperbot_option); register_activation_hook(__FILE__, 'plapperbot_purge_caches'); // After a plugin update: clear the page cache once, so pages are rebuilt with the new version (e.g. privacy mode) add_action('init', function () { if (get_option('plapperbot_version') === PLAPPERBOT_VERSION) { return; } update_option('plapperbot_version', PLAPPERBOT_VERSION, true); if (plapperbot_bot()) { plapperbot_purge_caches(); } }); register_deactivation_hook(__FILE__, 'plapperbot_purge_caches'); /* ------------------------------------------------------------------------- * Front end: chat bubble according to the display rules * ---------------------------------------------------------------------- */ /** Does the current page contain the inline chat (shortcode or block)? Then no extra bubble. */ function plapperbot_page_has_inline_chat() { if (!is_singular()) { return false; } $post = get_post(); if (!$post) { return false; } return has_shortcode($post->post_content, 'plapperbot') || (function_exists('has_block') && has_block('plapperbot/chat', $post)); } /** Should the chat bubble appear on the current page? */ function plapperbot_should_show_bubble() { if (is_admin() || !plapperbot_bot()) { return false; } $display = plapperbot_display(); if (!empty($display['hide_admins']) && current_user_can('manage_options')) { return false; } if (plapperbot_page_has_inline_chat()) { return false; } $id = is_singular() ? (int) get_queried_object_id() : 0; $pages = array_map('intval', (array) $display['pages']); if ($display['mode'] === 'only' && !in_array($id, $pages, true)) { return false; } if ($display['mode'] === 'except' && $id && in_array($id, $pages, true)) { return false; } $types = (array) $display['post_types']; if ($types && is_singular() && !in_array(get_post_type(), $types, true)) { return false; } return (bool) apply_filters('plapperbot_show_bubble', true); } /** * Look of the chatbot for privacy mode (colour, button size, side, name, welcome), read by the WordPress server * and cached. The last good answer is kept, so the bubble still appears if plapperbot.de is briefly unreachable. * * @return array{color: string, text: string, size: int, side: string, name: string, welcome: string, available: bool} */ function plapperbot_bot_look() { $remote = plapperbot_remote_bot(); $saved = get_option('plapperbot_bot_look', array()); if (is_array($remote) && (int) ($remote['_status'] ?? 0) === 200) { $style = isset($remote['chatStyle']) && is_array($remote['chatStyle']) ? $remote['chatStyle'] : array(); $look = array( 'color' => isset($remote['color']) && preg_match('/^#[0-9a-f]{6}$/i', (string) $remote['color']) ? (string) $remote['color'] : '#111827', 'size' => array('compact' => 50, 'normal' => 60, 'large' => 70)[$style['button'] ?? 'normal'] ?? 60, 'side' => ($style['position'] ?? '') === 'left' ? 'left' : 'right', 'name' => (string) ($remote['name'] ?? ''), 'welcome' => (string) ($remote['welcomeMessage'] ?? ''), 'available' => !empty($remote['available']), ); if ($look !== $saved) { update_option('plapperbot_bot_look', $look, false); } } else { $look = is_array($saved) && $saved ? $saved : array('color' => '#111827', 'size' => 60, 'side' => 'right', 'name' => '', 'welcome' => '', 'available' => true); } // Text colour on the colour (same rule as widget.js) $hex = hexdec(substr($look['color'], 1)); $l = (0.299 * (($hex >> 16) & 255) + 0.587 * (($hex >> 8) & 255) + 0.114 * ($hex & 255)) / 255; $look['text'] = $l > 0.6 ? '#111827' : '#ffffff'; return $look; } /** * Visitor-facing text of privacy mode: translation from translate.wordpress.org; while none exists yet, * German sites get the German text instead of the English source. */ function plapperbot_front_text($translated, $english, $german) { $locale = function_exists('determine_locale') ? determine_locale() : get_locale(); return ($translated === $english && strpos((string) $locale, 'de') === 0) ? $german : $translated; } /** Privacy mode switched on in the display rules? */ function plapperbot_privacy_mode() { return !empty(plapperbot_display()['privacy']); } add_action('init', function () { // Local script for privacy mode (nothing is loaded from plapperbot.de before a click) wp_register_script('plapperbot-launcher', plugins_url('assets/launcher.js', __FILE__), array(), PLAPPERBOT_VERSION, array('in_footer' => true, 'strategy' => 'defer')); }); add_action('wp_enqueue_scripts', function () { if (!plapperbot_should_show_bubble()) { return; } if (plapperbot_privacy_mode()) { if (plapperbot_bot_look()['available']) { wp_enqueue_script('plapperbot-launcher'); add_action('wp_footer', 'plapperbot_print_launcher'); } return; } $bot = plapperbot_bot(); // External script of the plapperbot service (see readme: External services) wp_enqueue_script('plapperbot-widget', $bot['origin'] . '/widget.js', array(), PLAPPERBOT_VERSION, array('in_footer' => true, 'strategy' => 'defer')); }); /** Privacy mode: our own chat bubble; launcher.js loads widget.js only when it is clicked */ function plapperbot_print_launcher() { $bot = plapperbot_bot(); $display = plapperbot_display(); $look = plapperbot_bot_look(); $side = $display['position'] === 'left' ? 'left' : $look['side']; $size = (int) $look['size']; $style = sprintf( 'display:none;position:fixed;bottom:20px;%1$s:20px;z-index:2147483000;width:%2$dpx;height:%2$dpx;border-radius:999px;border:0;padding:0;cursor:pointer;align-items:center;justify-content:center;background:%3$s;color:%4$s;box-shadow:0 10px 30px -5px rgba(0,0,0,.35)', $side, $size, $look['color'], $look['text'] ); printf( '', esc_attr(plapperbot_front_text(__('Open chat', 'plapperbot'), 'Open chat', 'Chat öffnen')), esc_attr($bot['slug']), esc_attr($bot['origin']), esc_attr($display['position'] === 'left' ? 'left' : ''), esc_attr($display['device']), esc_attr($style) ); } // The widget reads its settings from data attributes on the script tag add_filter('script_loader_tag', function ($tag, $handle) { if ($handle !== 'plapperbot-widget') { return $tag; } $bot = plapperbot_bot(); $display = plapperbot_display(); $attrs = ' data-bot="' . esc_attr($bot['slug']) . '"'; if (in_array($display['device'], array('desktop', 'mobile'), true)) { $attrs .= ' data-device="' . esc_attr($display['device']) . '"'; } if ($display['position'] === 'left') { $attrs .= ' data-position="left"'; } if (strpos($tag, ' defer') === false) { $attrs .= ' defer'; } return str_replace(' src=', $attrs . ' src=', $tag); }, 10, 2); /* ------------------------------------------------------------------------- * Inline chat: shortcode [plapperbot height="600"] and block "plapperbot/chat" * ---------------------------------------------------------------------- */ function plapperbot_render_inline($atts = array()) { $bot = plapperbot_bot(); if (!$bot) { return current_user_can('edit_posts') ? '
' . esc_html__('plapperbot: please connect your chatbot first (WordPress menu “plapperbot”).', 'plapperbot') . '
' : ''; } $atts = shortcode_atts(array('height' => 600), $atts, 'plapperbot'); $height = max(320, min(1200, (int) $atts['height'])); // Privacy mode: preview card; the chat is loaded only after "Start chat" (launcher.js) if (plapperbot_privacy_mode()) { $look = plapperbot_bot_look(); wp_enqueue_script('plapperbot-launcher'); $welcome = $look['welcome'] !== '' ? sprintf('