$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('
%s
', esc_html($look['welcome'])) : ''; return sprintf( '', esc_url($bot['origin'] . '/embed/' . $bot['slug']), esc_attr__('Chat', 'plapperbot'), $height, esc_attr($look['color']), esc_attr($look['text']), esc_html($look['name'] !== '' ? $look['name'] : __('Chat', 'plapperbot')), $welcome, esc_html(plapperbot_front_text(__('Start chat', 'plapperbot'), 'Start chat', 'Chat starten')), esc_html(plapperbot_front_text(__('The chat is loaded from plapperbot.de when you start it.', 'plapperbot'), 'The chat is loaded from plapperbot.de when you start it.', 'Der Chat wird beim Start von plapperbot.de geladen.')) ); } return sprintf( '
', esc_url($bot['origin'] . '/embed/' . $bot['slug']), esc_attr__('Chat', 'plapperbot'), $height ); } add_shortcode('plapperbot', 'plapperbot_render_inline'); add_action('init', function () { if (!function_exists('register_block_type')) { return; } wp_register_script( 'plapperbot-block', plugins_url('assets/block.js', __FILE__), array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n'), PLAPPERBOT_VERSION, true ); if (function_exists('wp_set_script_translations')) { // Übersetzungen kommen von translate.wordpress.org (keine Sprachdateien im Plugin) wp_set_script_translations('plapperbot-block', 'plapperbot'); } register_block_type('plapperbot/chat', array( 'editor_script' => 'plapperbot-block', 'render_callback' => function ($attributes) { return plapperbot_render_inline(array('height' => isset($attributes['height']) ? (int) $attributes['height'] : 600)); }, 'attributes' => array('height' => array('type' => 'number', 'default' => 600)), )); }); /* ------------------------------------------------------------------------- * Settings * ---------------------------------------------------------------------- */ add_action('admin_init', function () { register_setting('plapperbot_connect', PLAPPERBOT_OPTION, array( 'type' => 'string', 'default' => '', 'sanitize_callback' => function ($value) { $value = esc_url_raw(trim((string) $value)); if ($value !== '' && !plapperbot_parse_link($value)) { add_settings_error(PLAPPERBOT_OPTION, 'invalid', __('Please enter the chat link from your plapperbot account, e.g. https://www.plapperbot.de/c/your-company', 'plapperbot')); return get_option(PLAPPERBOT_OPTION, ''); } return $value; }, )); register_setting('plapperbot_connect', PLAPPERBOT_KEY_OPTION, array( 'type' => 'string', 'default' => '', 'sanitize_callback' => function ($value) { $value = trim(sanitize_text_field((string) $value)); if ($value !== '' && !preg_match('/^pb_[A-Za-z0-9_-]{8,64}$/', $value)) { add_settings_error(PLAPPERBOT_KEY_OPTION, 'invalid', __('The plugin key starts with “pb_”. You can copy it in your plapperbot account under Embed → WordPress.', 'plapperbot')); return get_option(PLAPPERBOT_KEY_OPTION, ''); } return $value; }, )); register_setting('plapperbot_display', PLAPPERBOT_DISPLAY_OPTION, array( 'type' => 'array', 'default' => array(), 'sanitize_callback' => function ($value) { $value = is_array($value) ? $value : array(); $pages = isset($value['pages']) ? array_filter(array_map('absint', (array) $value['pages'])) : array(); $types = isset($value['post_types']) ? array_map('sanitize_key', (array) $value['post_types']) : array(); return array( 'mode' => isset($value['mode']) && in_array($value['mode'], array('all', 'only', 'except'), true) ? $value['mode'] : 'all', 'pages' => array_values(array_unique($pages)), 'post_types' => array_values(array_intersect($types, array_keys(get_post_types(array('public' => true))))), 'device' => isset($value['device']) && in_array($value['device'], array('all', 'desktop', 'mobile'), true) ? $value['device'] : 'all', 'position' => isset($value['position']) && $value['position'] === 'left' ? 'left' : 'right', 'hide_admins' => !empty($value['hide_admins']), 'privacy' => !empty($value['privacy']), ); }, )); }); // After saving: refresh cached API data and clear the page cache (also when nothing changed) add_action('load-toplevel_page_plapperbot', function () { if (!empty($_GET['settings-updated'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only reads the WordPress redirect flag plapperbot_clear_remote_cache(); plapperbot_purge_caches(); } }); // Adopt a changed link ending (the old one keeps working, but the new one is cleaner) add_action('admin_post_plapperbot_update_slug', function () { if (!current_user_can('manage_options')) { wp_die(esc_html__('You are not allowed to do this.', 'plapperbot')); } check_admin_referer('plapperbot_update_slug'); $bot = plapperbot_bot(); $slug = isset($_POST['slug']) ? sanitize_title(wp_unslash($_POST['slug'])) : ''; if ($bot && $slug !== '') { update_option(PLAPPERBOT_OPTION, esc_url_raw($bot['origin'] . '/c/' . $slug)); plapperbot_clear_remote_cache(); } wp_safe_redirect(admin_url('admin.php?page=plapperbot&settings-updated=1')); exit; }); // Refresh button: fetch status and figures again add_action('admin_post_plapperbot_refresh', function () { if (!current_user_can('manage_options')) { wp_die(esc_html__('You are not allowed to do this.', 'plapperbot')); } check_admin_referer('plapperbot_refresh'); plapperbot_clear_remote_cache(); wp_safe_redirect(admin_url('admin.php?page=plapperbot')); exit; }); /* ------------------------------------------------------------------------- * Admin: menu, styles, settings page, dashboard widget * ---------------------------------------------------------------------- */ add_action('admin_menu', function () { add_menu_page( 'plapperbot', 'plapperbot', 'manage_options', 'plapperbot', 'plapperbot_settings_page', plugins_url('assets/icon-weiss.png', __FILE__), 81 ); }); add_action('admin_enqueue_scripts', function ($hook) { // Menu icon size on all admin pages, full styles only on our page and the dashboard wp_register_style('plapperbot-admin', plugins_url('assets/admin.css', __FILE__), array(), PLAPPERBOT_VERSION); wp_add_inline_style('admin-menu', '#adminmenu .toplevel_page_plapperbot .wp-menu-image img{width:20px;height:20px;padding:7px 0 0;opacity:1}'); if ($hook === 'toplevel_page_plapperbot' || $hook === 'index.php') { wp_enqueue_style('plapperbot-admin'); } }); add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) { array_unshift($links, '' . esc_html__('Settings', 'plapperbot') . ''); return $links; }); require_once __DIR__ . '/includes/admin-page.php'; require_once __DIR__ . '/includes/dashboard.php';