PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.25
MxChat – AI Chatbot & Content Generation for WordPress v3.2.25
3.2.25 3.2.24 3.2.23 3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 All 156 releases
mxchat-basic / includes / class-mxchat-public.php

class-mxchat-public.php in MxChat – AI Chatbot & Content Generation for WordPress 3.2.25, at includes/class-mxchat-public.php

1,165 lines 64.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH')) {
3 exit; // Exit if accessed directly
4 }
5
6 class MxChat_Public {
7 private $options;
8
9 // True once any FLOATING instance has rendered on this request via the
10 // shortcode (or the block wrapping it) — append_chatbot_to_body() then
11 // yields, so an explicit floating placement never doubles up with the
12 // Auto-Display instance (plan 95dd1e).
13 private static $floating_instance_rendered = false;
14
15 // Bot ids already placed on this page (plan 977cad), floating and inline
16 // alike. Two copies of one bot share every element id (chat-input-<bot>,
17 // send-button-<bot>, ...) and chat-script.js looks elements up by id, so
18 // the second copy's Send reads the FIRST copy's empty box and sends
19 // nothing. One copy of a bot per page: append_chatbot_to_body() stands
20 // down for a bot the content already shows, and a second explicit
21 // placement of the same bot renders an administrator-only note instead.
22 // Only page renders count: a render in wp-admin, admin-ajax, cron, REST,
23 // WP-CLI, a feed, or inside wp_head (a plugin building meta tags from the
24 // content) is not on the page and must not suppress the real one. Note
25 // that a block theme renders the body BEFORE wp_head (template-canvas
26 // builds the template first so blocks can enqueue), so "after wp_head"
27 // is not the test.
28 private static $rendered_bot_ids = array();
29
30 public function __construct() {
31 // Simply get the options without defining duplicated defaults
32 $this->options = get_option('mxchat_options', array());
33 add_shortcode('mxchat_chatbot', array($this, 'render_chatbot_shortcode'));
34 add_action('wp_footer', array($this, 'append_chatbot_to_body'));
35 }
36
37 /**
38 * UPDATED: Enhanced should_hide_chatbot method - only blocks auto-append, not shortcodes
39 */
40 private function should_hide_chatbot($context = 'auto') {
41 global $post;
42
43 if (!$post) {
44 return false;
45 }
46
47 // Only hide if it's the auto-append context (floating="yes" from global setting)
48 // Allow shortcodes to work regardless of this setting
49 if ($context === 'auto') {
50 // Check new visibility field first
51 $visibility = get_post_meta($post->ID, '_mxchat_page_visibility', true);
52 if ($visibility === 'hide') {
53 return true;
54 }
55
56 // Backward compat: check legacy field if new field not set
57 if (empty($visibility)) {
58 $hide_chatbot = get_post_meta($post->ID, '_mxchat_hide_chatbot', true);
59 if ($hide_chatbot === '1') {
60 return true;
61 }
62 }
63 }
64
65 return false;
66 }
67
68 /**
69 * UPDATED: Enhanced append_chatbot_to_body method with context
70 */
71 public function append_chatbot_to_body() {
72 // Only run on public pages
73 if (is_admin() || wp_doing_ajax()) {
74 return;
75 }
76
77 // Check if auto-append chatbot should be hidden on this page
78 if ($this->should_hide_chatbot('auto')) {
79 return; // Don't show auto-appended chatbot
80 }
81
82 // An explicit floating placement (shortcode or the 95dd1e block) already
83 // rendered during content — appending the auto instance would put two
84 // floating widgets on the page with colliding element ids. The explicit
85 // placement wins; content renders before wp_footer, so the flag is set
86 // by the time this runs.
87 if (self::$floating_instance_rendered) {
88 return;
89 }
90
91 // Get the bot that should be displayed using new logic
92 $bot_to_show = $this->get_display_bot();
93
94 // Don't show chatbot if determination is false
95 if ($bot_to_show === false) {
96 return;
97 }
98
99 // The bot is already on this page as an explicit placement (an inline
100 // shortcode or block in the content). A second, floating copy would share
101 // its element ids and could be opened but not send; the embedded one wins
102 // (plan 977cad). A page whose embedded chatbot is a DIFFERENT bot keeps
103 // both, their ids differ.
104 if (self::is_bot_on_page($bot_to_show)) {
105 return;
106 }
107
108 // Handle consent for display
109 $consent_category = 'marketing';
110 $has_consent = true;
111
112 if (
113 isset($this->options['complianz_toggle']) &&
114 $this->options['complianz_toggle'] === 'on' &&
115 function_exists('cmplz_has_consent')
116 ) {
117 $has_consent = cmplz_has_consent($consent_category);
118 }
119
120 // Display the appropriate chatbot (always floating for auto-append)
121 if ($bot_to_show && $bot_to_show !== 'default') {
122 // Show specific bot
123 echo do_shortcode('[mxchat_chatbot floating="yes" bot_id="' . esc_attr($bot_to_show) . '" has_consent="' . ($has_consent ? 'yes' : 'no') . '"]');
124 } else {
125 // Show default bot
126 echo do_shortcode('[mxchat_chatbot floating="yes" has_consent="' . ($has_consent ? 'yes' : 'no') . '"]');
127 }
128 }
129
130 /**
131 * Is this render on the page a visitor sees? (plan 977cad) False in
132 * wp-admin, admin-ajax, cron, REST, WP-CLI, a feed, and inside wp_head.
133 * Not "after wp_head": block themes render the body content first.
134 */
135 private static function is_page_render() {
136 if (is_admin() || wp_doing_ajax() || wp_doing_cron()
137 || (defined('REST_REQUEST') && REST_REQUEST)
138 || (defined('WP_CLI') && WP_CLI)) {
139 return false;
140 }
141 return !doing_action('wp_head') && !is_feed();
142 }
143
144 private static function record_bot_on_page($bot_id) {
145 if (!self::is_page_render()) {
146 return;
147 }
148 $bot_id = sanitize_key($bot_id);
149 if ($bot_id !== '' && !in_array($bot_id, self::$rendered_bot_ids, true)) {
150 self::$rendered_bot_ids[] = $bot_id;
151 }
152 }
153
154 /**
155 * Has a placement of this bot already rendered in the page body on this
156 * request? (plan 977cad)
157 */
158 public static function is_bot_on_page($bot_id) {
159 if (!self::is_page_render()) {
160 return false;
161 }
162 return in_array(sanitize_key($bot_id), self::$rendered_bot_ids, true);
163 }
164
165 /**
166 * What a second placement of an already-shown bot renders: nothing for
167 * visitors, one line for a logged-in administrator (plan 977cad).
168 */
169 private static function duplicate_placement_notice() {
170 if (!current_user_can('manage_options')) {
171 return '';
172 }
173 return '<p class="mxchat-placement-notice" data-nosnippet>'
174 . esc_html__('MxChat: this page already shows this chatbot, so a second copy of the same bot is not displayed. Only administrators see this note.', 'mxchat')
175 . '</p>';
176 }
177
178 private function mxchat_get_user_identifier() {
179 return sanitize_text_field($_SERVER['REMOTE_ADDR']);
180 }
181
182 /**
183 * UPDATED: Enhanced shortcode with context-aware hiding
184 */
185 public function render_chatbot_shortcode($atts) {
186 // Smart asset loading safety net (plan-915355): if the opt-in enqueue gate
187 // skipped assets on this request (shortcode invisible to has_shortcode —
188 // builder-stored content, template files, widget areas), force the FULL
189 // enqueue now, including the mxchatChat settings payload and the delayed
190 // loader wiring. The integrator method is idempotent, so this is a no-op
191 // when assets already went out at wp_enqueue_scripts time.
192 if (self::is_smart_asset_loading_enabled() && !wp_style_is('mxchat-chat-css', 'enqueued')) {
193 global $mxchat_integrator;
194 if (isset($mxchat_integrator) && is_object($mxchat_integrator)
195 && method_exists($mxchat_integrator, 'mxchat_enqueue_scripts_styles')) {
196 $mxchat_integrator->mxchat_enqueue_scripts_styles(true);
197 }
198 }
199
200 // UPDATED: Add bot_id parameter support and improve logic
201 $attributes = shortcode_atts(array(
202 'floating' => 'yes',
203 'has_consent' => 'yes',
204 'bot_id' => '' // Support for multi-bot functionality - empty means auto-detect
205 ), $atts);
206
207 // Determine which bot to use
208 $bot_id = sanitize_key($this->determine_bot_for_shortcode($attributes['bot_id']));
209
210 // A second placement of a bot already on this page is not rendered
211 // (plan 977cad, see $rendered_bot_ids): it could be opened but never
212 // sent. Administrators get a one-line note in its place so the
213 // duplicate is visible to the person who can remove it.
214 if (self::is_bot_on_page($bot_id)) {
215 return self::duplicate_placement_notice();
216 }
217 self::record_bot_on_page($bot_id);
218
219 // A floating shortcode always renders; what it does is suppress the LATER
220 // auto-append instance (see append_chatbot_to_body), so a page never gets
221 // two floating widgets. This replaced a dead empty branch here that
222 // documented the intent but never suppressed anything (plan 95dd1e).
223 if ($attributes['floating'] === 'yes') {
224 self::$floating_instance_rendered = true;
225 }
226
227 // Non-floating shortcodes (floating="no") should NEVER be blocked by the hide setting
228 // This allows embedded chatbots even when floating is hidden
229
230 $is_floating = $attributes['floating'] === 'yes';
231
232 // Rest of your existing shortcode rendering logic continues unchanged...
233 // [All the existing HTML generation code remains the same]
234
235 // Get bot-specific options if multi-bot add-on is active
236 $bot_options = $this->get_bot_options($bot_id);
237
238 // Use bot-specific options or fall back to default options
239 $current_options = !empty($bot_options) ? $bot_options : $this->options;
240
241 // [Rest of your existing rendering code stays exactly the same]
242 // Just remove the old should_hide_chatbot() check from the beginning
243
244 // Check for Complianz consent if the toggle is enabled
245 $initial_visibility = 'hidden';
246 $additional_class = '';
247
248 if (isset($current_options['complianz_toggle']) && $current_options['complianz_toggle'] === 'on') {
249 $additional_class = ' no-consent';
250 }
251 $visibility_class = $initial_visibility . $additional_class;
252
253 $theme_options = get_option('mxchat_theme_options', array());
254 $custom_send_image = isset($theme_options['custom_send_button_image']) ? esc_url($theme_options['custom_send_button_image']) : '';
255 $send_width = isset($theme_options['send_button_width']) ? intval($theme_options['send_button_width']) : 24;
256 $send_height = isset($theme_options['send_button_height']) ? intval($theme_options['send_button_height']) : 24;
257 $send_rotation = isset($theme_options['send_button_rotation']) ? intval($theme_options['send_button_rotation']) : 0;
258
259 // Check if an AI theme is active (global or bot-specific) - if so, skip inline color styles
260 $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
261 $bot_has_theme = isset($theme_options['bot_theme_assignments'][$bot_id]);
262 $skip_inline_colors = $ai_theme_active || $bot_has_theme;
263
264 // UPDATED: Use current_options instead of $this->options throughout
265 $bg_color = $current_options['chatbot_background_color'] ?? '#fff';
266 $user_message_bg_color = $current_options['user_message_bg_color'] ?? '#fff';
267 $user_message_font_color = $current_options['user_message_font_color'] ?? '#212121';
268 $bot_message_bg_color = $current_options['bot_message_bg_color'] ?? '#212121';
269 $bot_message_font_color = $current_options['bot_message_font_color'] ?? '#fff';
270 $top_bar_bg_color = $current_options['top_bar_bg_color'] ?? '#212121';
271 $send_button_font_color = $current_options['send_button_font_color'] ?? '#212121';
272 $intro_message = $current_options['intro_message'] ?? esc_html__('Hello! How can I assist you today?', 'mxchat');
273 $top_bar_title = $current_options['top_bar_title'] ?? esc_html__('MxChat: Basic', 'mxchat');
274 $chatbot_background_color = $current_options['chatbot_background_color'] ?? '#212121';
275 $icon_color = $current_options['icon_color'] ?? '#fff';
276 $chat_input_font_color = $current_options['chat_input_font_color'] ?? '#212121';
277 $close_button_color = $current_options['close_button_color'] ?? '#fff';
278 $chatbot_bg_color = $current_options['chatbot_bg_color'] ?? '#fff';
279 $pre_chat_message = isset($current_options['pre_chat_message']) ? sanitize_textarea_field(trim($current_options['pre_chat_message'])) : '';
280 $user_id = sanitize_key($this->mxchat_get_user_identifier());
281 $email_state = $this->determine_email_collection_state();
282 $show_email_form = $email_state['show_email_form'];
283 $user_email = $email_state['user_email'] ?? '';
284 $user_name = $email_state['user_name'] ?? '';
285 // Pre-chat dismissal now handled client-side via localStorage (zero server load)
286 $input_copy = isset($current_options['input_copy']) ? esc_attr($current_options['input_copy']) : esc_attr__('How can I assist?', 'mxchat');
287 $rate_limit_message = isset($current_options['rate_limit_message']) ? esc_attr($current_options['rate_limit_message']) : esc_attr__('Rate limit exceeded. Please try again later.', 'mxchat');
288 $mode_indicator_bg_color = $current_options['mode_indicator_bg_color'] ?? '#212121';
289 $mode_indicator_font_color = $current_options['mode_indicator_font_color'] ?? '#fff';
290 $quick_questions_toggle_color = $current_options['quick_questions_toggle_color'] ?? '#212121';
291
292 $privacy_toggle = isset($current_options['privacy_toggle']) && $current_options['privacy_toggle'] === 'on';
293 $privacy_text = isset($current_options['privacy_text']) ? wp_kses_post($current_options['privacy_text']) : wp_kses_post(__('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat'));
294
295 $popular_question_1 = isset($current_options['popular_question_1']) ? esc_html($current_options['popular_question_1']) : '';
296 $popular_question_2 = isset($current_options['popular_question_2']) ? esc_html($current_options['popular_question_2']) : '';
297 $popular_question_3 = isset($current_options['popular_question_3']) ? esc_html($current_options['popular_question_3']) : '';
298 $additional_questions = isset($current_options['additional_popular_questions']) ? $current_options['additional_popular_questions'] : [];
299 $custom_icon = isset($current_options['custom_icon']) ? esc_url($current_options['custom_icon']) : '';
300 $title_icon = isset($current_options['title_icon']) ? esc_url($current_options['title_icon']) : '';
301 // AI agent text - if explicitly set to empty string, hide the indicator entirely
302 $ai_agent_text = isset($current_options['ai_agent_text']) ? $current_options['ai_agent_text'] : __('AI Agent', 'mxchat');
303
304 $live_agent_message_bg_color = $current_options['live_agent_message_bg_color'] ?? '#212121';
305 $live_agent_message_font_color = $current_options['live_agent_message_font_color'] ?? '#fff';
306 $enable_email_block = isset($current_options['enable_email_block']) &&
307 ($current_options['enable_email_block'] === '1' || $current_options['enable_email_block'] === 'on');
308
309 // Add name field variables
310 $enable_name_field = isset($current_options['enable_name_field']) &&
311 ($current_options['enable_name_field'] === '1' || $current_options['enable_name_field'] === 'on');
312 $name_field_placeholder = isset($current_options['name_field_placeholder']) ?
313 esc_attr($current_options['name_field_placeholder']) :
314 esc_attr__('Enter your name', 'mxchat');
315
316 // Require Email Address (c0cfaf). Default ON — absent key means required,
317 // so existing installs render the same markup they always have.
318 $require_email_field = ($current_options['lead_capture_require_email_toggle'] ?? 'on') === 'on';
319
320 // Pre-fill the form from the profile when a signed-in visitor is being
321 // shown it (c0cfaf). Emitted ONLY for a logged-in request, so the markup a
322 // guest gets — the copy a page cache actually stores and re-serves — never
323 // carries anyone's address. WordPress already marks logged-in responses
324 // uncacheable, and such a page carries per-user data from other plugins
325 // regardless.
326 $prefill_email_attr = '';
327 $prefill_name_attr = '';
328 if (is_user_logged_in()) {
329 if ($user_email !== '') {
330 $prefill_email_attr = ' value="' . esc_attr($user_email) . '"';
331 }
332 if ($user_name !== '') {
333 $prefill_name_attr = ' value="' . esc_attr($user_name) . '"';
334 }
335 }
336
337 // Consent checkbox (b062c4). Default OFF — with the toggle off this block
338 // renders nothing and the form markup is byte-identical to before.
339 $enable_consent_checkbox = isset($current_options['enable_consent_checkbox']) &&
340 ($current_options['enable_consent_checkbox'] === '1' || $current_options['enable_consent_checkbox'] === 'on');
341 $consent_checkbox_required = isset($current_options['consent_checkbox_required']) &&
342 ($current_options['consent_checkbox_required'] === '1' || $current_options['consent_checkbox_required'] === 'on');
343 // Owner content, kses'd through the shared allowlist at render time as well
344 // as save time — the render is the security boundary the spec names.
345 $consent_checkbox_label = MxChat_Utils::sanitize_consent_label(
346 isset($current_options['consent_checkbox_label']) && $current_options['consent_checkbox_label'] !== ''
347 ? $current_options['consent_checkbox_label']
348 : __('I agree to the Privacy Policy.', 'mxchat')
349 );
350
351 ob_start();
352
353 // Check if floating attribute is set to 'yes' and wrap accordingly
354 if ($is_floating) {
355 echo '<div id="floating-chatbot-' . esc_attr($bot_id) . '" class="floating-chatbot ' . $initial_visibility . $additional_class . '">';
356 }
357
358 // Add bot_id to the chatbot wrapper as a data attribute
359 // data-nosnippet: keep the chat widget's UI copy (greeting, title, quick-question
360 // prompts, privacy notice) out of Google search snippets. This wrapper renders in both
361 // floating and inline/shortcode modes, so it covers all in-panel copy in one place.
362 echo '<div id="mxchat-chatbot-wrapper-' . esc_attr($bot_id) . '" class="mxchat-chatbot-wrapper" data-nosnippet data-bot-id="' . esc_attr($bot_id) . '">';
363
364 echo ' <div class="chatbot-top-bar" id="exit-chat-button-' . esc_attr($bot_id) . '"' . ($skip_inline_colors ? '' : ' style="background: ' . esc_attr($top_bar_bg_color) . ';"') . '>';
365 echo ' <div class="chatbot-title-container">';
366 echo ' <div class="chatbot-title-group">';
367 if (!empty($title_icon)) {
368 echo ' <img src="' . esc_url($title_icon) . '" alt="" class="chatbot-title-icon">';
369 }
370 echo ' <p class="chatbot-title"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($close_button_color) . ';"') . '>' . esc_html($top_bar_title) . '</p>';
371 echo ' </div>';
372 // Only show mode indicator if ai_agent_text is not empty
373 if (!empty(trim($ai_agent_text))) {
374 echo '<span class="chat-mode-indicator" id="chat-mode-indicator-' . esc_attr($bot_id) . '" data-ai-text="' . esc_attr($ai_agent_text) . '"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($mode_indicator_font_color) . '; background-color: ' . esc_attr($mode_indicator_bg_color) . ';"') . '>' . esc_html($ai_agent_text) . '</span>';
375 }
376 echo ' </div>';
377 // Overflow menu (3-dot) trigger + dropdown container.
378 // Sibling of .exit-chat, rendered to its left. JS hides the trigger
379 // if no menu items are enabled; outer click + Escape close the menu.
380 echo ' <div class="mxchat-header-menu-wrap" data-bot-id="' . esc_attr($bot_id) . '"' . ($skip_inline_colors ? '' : ' style="--mxchat-menu-bg: ' . esc_attr($bot_message_bg_color) . '; --mxchat-menu-fg: ' . esc_attr($bot_message_font_color) . ';"') . '>';
381 echo ' <button class="mxchat-header-btn mxchat-menu-trigger" type="button" aria-haspopup="menu" aria-expanded="false" aria-label="' . esc_attr__('More options', 'mxchat') . '"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($close_button_color) . ';"') . '>';
382 echo ' <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">';
383 echo ' <circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/>';
384 echo ' </svg>';
385 echo ' </button>';
386 echo ' <div class="mxchat-header-menu" role="menu" aria-hidden="true" hidden></div>';
387 echo ' </div>';
388 echo ' <button class="exit-chat" type="button" aria-label="' . esc_attr__('Close', 'mxchat') . '"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($close_button_color) . ';"') . '>';
389 echo ' <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" id="ic-close" aria-hidden="true">';
390 echo ' <line x1="6" y1="6" x2="18" y2="18"></line>';
391 echo ' <line x1="18" y1="6" x2="6" y2="18"></line>';
392 echo ' </svg>';
393 echo ' <span>' . esc_html__('Close', 'mxchat') . '</span>';
394 echo ' </button>';
395 echo ' </div>';
396
397 // 3b) Main chatbot container
398 echo ' <div id="mxchat-chatbot-' . esc_attr($bot_id) . '" class="mxchat-chatbot"' . ($skip_inline_colors ? '' : ' style="background-color: ' . esc_attr($chatbot_bg_color) . ';"') . '>';
399
400 if ($enable_email_block) {
401 echo '<div id="email-blocker-' . esc_attr($bot_id) . '" class="email-blocker" style="' . ($show_email_form ? '' : 'display: none;') . '">';
402 echo ' <div class="email-blocker-header">';
403
404 $header_html = isset($current_options['email_blocker_header_content'])
405 ? $current_options['email_blocker_header_content']
406 : '';
407 echo wp_kses_post($header_html);
408
409 echo ' </div>';
410 echo ' <form id="email-collection-form-' . esc_attr($bot_id) . '" class="email-collection-form" method="POST" action="">';
411
412 // Add name field if enabled
413 if ($enable_name_field) {
414 echo ' <label for="user-name-' . esc_attr($bot_id) . '" class="sr-only mxchat-name-label">' . esc_html__('Name', 'mxchat') . '</label>';
415 echo ' <input type="text" id="user-name-' . esc_attr($bot_id) . '" name="user_name" class="mxchat-name-input" required' . $prefill_name_attr . ' placeholder="' . $name_field_placeholder . '" />';
416 }
417
418 // The email field drops its required attribute when the owner
419 // has made it optional (c0cfaf). Like the consent checkbox,
420 // the attribute is UX only — the save endpoint re-enforces the
421 // rule server-side, so a direct POST cannot bypass it.
422 echo ' <label for="user-email-' . esc_attr($bot_id) . '" class="sr-only">' . esc_html__('Email Address', 'mxchat') . '</label>';
423 echo ' <input type="email" id="user-email-' . esc_attr($bot_id) . '" name="user_email" class="mxchat-email-input"' . ($require_email_field ? ' required' : '') . $prefill_email_attr . ' placeholder="' . ($require_email_field ? esc_attr__('Enter your email address', 'mxchat') : esc_attr__('Enter your email address (optional)', 'mxchat')) . '" />';
424
425 // Consent checkbox row (b062c4). The native required attribute
426 // is UX only — the save endpoint re-enforces it server-side.
427 // Clicking an anchor inside the label activates the link, not
428 // the checkbox (interactive descendants skip label activation).
429 if ($enable_consent_checkbox) {
430 echo ' <div class="mxchat-consent-row">';
431 echo ' <input type="checkbox" id="user-consent-' . esc_attr($bot_id) . '" name="user_consent" value="1" class="mxchat-consent-checkbox"' . ($consent_checkbox_required ? ' required' : '') . ' />';
432 echo ' <label for="user-consent-' . esc_attr($bot_id) . '" class="mxchat-consent-label">' . $consent_checkbox_label . '</label>';
433 echo ' </div>';
434 }
435
436 echo '<button type="submit" id="email-submit-button-' . esc_attr($bot_id) . '" class="email-submit-button">';
437 $button_text = isset($current_options['email_blocker_button_text'])
438 ? $current_options['email_blocker_button_text']
439 : esc_html__('Start Chat', 'mxchat');
440 echo esc_html($button_text);
441 echo '</button>';
442 echo ' </form>';
443 echo '</div>';
444 }
445
446 echo ' <div id="mxchat-init-loader-' . esc_attr($bot_id) . '" class="mxchat-init-loader" style="display:none;">';
447 echo ' <div class="mxchat-init-loader-dots">';
448 echo ' <span class="dot"></span><span class="dot"></span><span class="dot"></span>';
449 echo ' </div>';
450 echo ' </div>';
451
452 echo ' <div id="chat-container-' . esc_attr($bot_id) . '" class="chat-container" style="' . ($enable_email_block && $show_email_form ? 'display: none;' : '') . '">';
453 // role="log" + polite live region: new messages are announced to
454 // screen readers explicitly, so the arrival signal no longer rides
455 // the post-reply input autofocus (suppressed on touch — plan 03799f).
456 // additions-only + non-atomic, with aria-busy held on the streaming
457 // bubble until [DONE] (chat-script.js) so a streamed reply is
458 // announced once, complete — not per token (WCAG 4.1.3, plan 67f126).
459 echo ' <div id="chat-box-' . esc_attr($bot_id) . '" class="chat-box" role="log" aria-live="polite" aria-atomic="false" aria-relevant="additions text" aria-label="' . esc_attr__('Chat messages', 'mxchat') . '">';
460 // mxchat-intro-message marks the greeting bubble so nothing has to
461 // infer it from position (plan a1a79b). Only this element ever
462 // carries the class — reset and the {visitor_name} substitution
463 // both key off it, and both used to assume the greeting was still
464 // the first .bot-message in the box, which stops being true the
465 // moment chat persistence rehydrates the transcript.
466 echo ' <div class="bot-message mxchat-intro-message"' . ($skip_inline_colors ? '' : ' style="background: ' . esc_attr($bot_message_bg_color) . ';"') . '>';
467 echo ' <div dir="auto"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($bot_message_font_color) . ';"') . '>';
468 echo wp_kses_post($intro_message);
469 echo ' </div>';
470 echo ' </div>';
471 echo ' </div>'; // end #chat-box
472
473
474 // Replace the existing popular questions section with this:
475 echo ' <div id="mxchat-popular-questions-' . esc_attr($bot_id) . '" class="mxchat-popular-questions">';
476 echo ' <div class="mxchat-popular-questions-container">';
477
478 // Collapse button (down arrow) - shows when open, centered at top
479 echo ' <button class="questions-collapse-btn" aria-label="' . esc_attr__('Hide Quick Questions', 'mxchat') . '">';
480 echo ' <svg width="25" height="25" viewBox="0 0 24 24" fill="none"' . ($skip_inline_colors ? '' : ' stroke="' . esc_attr($quick_questions_toggle_color) . '"') . ' stroke-width="2">';
481 echo ' <polyline points="6,9 12,15 18,9"></polyline>';
482 echo ' </svg>';
483 echo ' </button>';
484
485 // Expand button (up arrow) - shows when collapsed
486 echo ' <button class="questions-toggle-btn" aria-label="' . esc_attr__('Show Quick Questions', 'mxchat') . '">';
487 echo ' <svg width="25" height="25" viewBox="0 0 24 24" fill="none"' . ($skip_inline_colors ? '' : ' stroke="' . esc_attr($quick_questions_toggle_color) . '"') . ' stroke-width="2">';
488 echo ' <polyline points="18,15 12,9 6,15"></polyline>';
489 echo ' </svg>';
490 echo ' </button>';
491
492 if (!empty($popular_question_1)) {
493 echo '<button class="mxchat-popular-question" dir="auto">' . esc_html($popular_question_1) . '</button>';
494 }
495 if (!empty($popular_question_2)) {
496 echo '<button class="mxchat-popular-question" dir="auto">' . esc_html($popular_question_2) . '</button>';
497 }
498 if (!empty($popular_question_3)) {
499 echo '<button class="mxchat-popular-question" dir="auto">' . esc_html($popular_question_3) . '</button>';
500 }
501
502 if (!empty($additional_questions) && is_array($additional_questions)) {
503 foreach ($additional_questions as $index => $question) {
504 if (!empty($question)) {
505 echo '<button class="mxchat-popular-question" dir="auto">' . esc_html($question) . '</button>';
506 }
507 }
508 }
509
510 echo ' </div>';
511 echo ' </div>';
512
513 echo ' <div id="input-container-' . esc_attr($bot_id) . '" class="input-container">';
514 // Max input length (plan a3fae2 part C) — global core setting, 0 = unlimited.
515 // Hard-caps typing/paste client-side; the chat handler enforces it server-side too.
516 $mxchat_max_input_length = isset($this->options['max_input_length']) ? intval($this->options['max_input_length']) : 0;
517 $mxchat_maxlength_attr = $mxchat_max_input_length > 0 ? ' maxlength="' . esc_attr($mxchat_max_input_length) . '"' : '';
518 // Visually-hidden label = the input's accessible name (WCAG 3.3.2,
519 // plan 67f126). The placeholder stays as visible prompt copy but
520 // cannot be the name — it vanishes on the first keystroke.
521 echo ' <label for="chat-input-' . esc_attr($bot_id) . '" class="sr-only">' . esc_html__('Type your message', 'mxchat') . '</label>';
522 echo ' <textarea id="chat-input-' . esc_attr($bot_id) . '" class="chat-input" dir="auto"' . $mxchat_maxlength_attr . ' placeholder="' . esc_attr($input_copy) . '"' . ($skip_inline_colors ? '' : ' style="color: ' . esc_attr($chat_input_font_color) . ';"') . '></textarea>';
523 // Language-neutral character counter (plan 7091a2). Numbers only — no
524 // translatable strings — so it reads correctly on every-language install.
525 // Only rendered when a cap is set; hidden until ~80% of the cap, then
526 // ramps neutral -> amber -> red. Decorative (aria-hidden); the textarea's
527 // maxlength carries the real semantics for assistive tech.
528 if ($mxchat_max_input_length > 0) {
529 echo ' <div id="mxchat-char-counter-' . esc_attr($bot_id) . '" class="mxchat-char-counter" aria-hidden="true"><span class="mxchat-char-counter-current">0</span><span class="mxchat-char-counter-sep">/</span><span class="mxchat-char-counter-max">' . esc_html($mxchat_max_input_length) . '</span></div>';
530 }
531 echo ' <button id="send-button-' . esc_attr($bot_id) . '" class="send-button" aria-label="' . esc_attr__('Send message', 'mxchat') . '">';
532 if (!empty($custom_send_image)) {
533 echo ' <img src="' . esc_url($custom_send_image) . '" alt="' . esc_attr__('Send', 'mxchat') . '" style="width: ' . intval($send_width) . 'px; height: ' . intval($send_height) . 'px; transform: rotate(' . intval($send_rotation) . 'deg);" />';
534 } else {
535 $send_svg_style = 'width: ' . intval($send_width) . 'px; height: ' . intval($send_height) . 'px; transform: rotate(' . intval($send_rotation) . 'deg);';
536 if (!$skip_inline_colors) {
537 $send_svg_style = 'fill: ' . esc_attr($send_button_font_color) . '; ' . $send_svg_style;
538 }
539 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="' . $send_svg_style . '">';
540 echo ' <path d="M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"></path>';
541 echo ' </svg>';
542 }
543 echo ' </button>';
544 echo ' </div>';
545
546 echo ' <div class="chat-toolbar">';
547
548 // PDF Upload Button - wrapped in conditional using current_options
549 $show_pdf_button = isset($current_options['show_pdf_upload_button']) ? $current_options['show_pdf_upload_button'] : 'on';
550 if ($show_pdf_button === 'on') {
551 echo ' <input type="file" id="pdf-upload-' . esc_attr($bot_id) . '" class="pdf-upload" accept=".pdf" style="display: none;">';
552 echo ' <button id="pdf-upload-btn-' . esc_attr($bot_id) . '" class="toolbar-btn pdf-upload-btn" title="' . esc_attr__('Upload PDF', 'mxchat') . '">';
553 echo ' <!-- Icon from Font Awesome Free: https://fontawesome.com/license/free -->';
554 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" stroke="currentColor">';
555 echo ' <path d="M64 464l48 0 0 48-48 0c-35.3 0-64-28.7-64-64L0 64C0 28.7 28.7 0 64 0L229.5 0c17 0 33.3 6.7 45.3 18.7l90.5 90.5c12 12 18.7 28.3 18.7 45.3L384 304l-48 0 0-144-80 0c-17.7 0-32-14.3-32-32l0-80L64 48c-8.8 0-16 7.2-16 16l0 384c0 8.8 7.2 16 16 16zM176 352l32 0c30.9 0 56 25.1 56 56s-25.1 56-56 56l-16 0 0 32c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-48 0-80c0-8.8 7.2-16 16-16zm32 80c13.3 0 24-10.7 24-24s-10.7-24-24-24l-16 0 0 48 16 0zm96-80l32 0c26.5 0 48 21.5 48 48l0 64c0 26.5-21.5 48-48 48l-32 0c-8.8 0-16-7.2-16-16l0-128c0-8.8 7.2-16 16-16zm32 128c8.8 0 16-7.2 16-16l0-64c0-8.8-7.2-16-16-16l-16 0 0 96 16 0zm80-112c0-8.8 7.2-16 16-16l48 0c8.8 0 16 7.2 16 16s-7.2 16-16 16l-32 0 0 32 32 0c8.8 0 16 7.2 16 16s-7.2 16-16 16l-32 0 0 48c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64 0-64z"></path>';
556 echo ' </svg>';
557 echo ' </button>';
558 }
559
560 // Word Upload Button - wrapped in conditional using current_options
561 $show_word_button = isset($current_options['show_word_upload_button']) ? $current_options['show_word_upload_button'] : 'on';
562 if ($show_word_button === 'on') {
563 echo ' <input type="file" id="word-upload-' . esc_attr($bot_id) . '" class="word-upload" accept=".docx" style="display: none;">';
564 echo ' <button id="word-upload-btn-' . esc_attr($bot_id) . '" class="toolbar-btn word-upload-btn" title="' . esc_attr__('Upload Word Document', 'mxchat') . '">';
565 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" stroke="currentColor">';
566 echo ' <path d="M48 448L48 64c0-8.8 7.2-16 16-16l160 0 0 80c0 17.7 14.3 32 32 32l80 0 0 288c0 8.8-7.2 16-16 16L64 464c-8.8 0-16-7.2-16-16zM64 0C28.7 0 0 28.7 0 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-293.5c0-17-6.7-33.3-18.7-45.3L274.7 18.7C262.7 6.7 246.5 0 229.5 0L64 0zm55 241.1c-3.8-12.7-17.2-19.9-29.9-16.1s-19.9 17.2-16.1 29.9l48 160c3 10.2 12.4 17.1 23 17.1s19.9-7 23-17.1l25-83.4 25 83.4c3 10.2 12.4 17.1 23 17.1s19.9-7 23-17.1l48-160c3.8-12.7-3.4-26.1-16.1-29.9s-26.1 3.4-29.9 16.1l-25 83.4-25-83.4c-3-10.2-12.4-17.1-23-17.1s-19.9 7-23 17.1l-25 83.4-25-83.4z"/></svg>';
567 echo ' </button>';
568 }
569
570 // File containers
571 echo ' <div id="active-pdf-container-' . esc_attr($bot_id) . '" class="active-pdf-container" style="display: none;">';
572 echo ' <span id="active-pdf-name-' . esc_attr($bot_id) . '" class="active-pdf-name"></span>';
573 echo ' <button id="remove-pdf-btn-' . esc_attr($bot_id) . '" class="remove-pdf-btn" title="' . esc_attr__('Remove PDF', 'mxchat') . '">';
574 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2">';
575 echo ' <line x1="18" y1="6" x2="6" y2="18"></line>';
576 echo ' <line x1="6" y1="6" x2="18" y2="18"></line>';
577 echo ' </svg>';
578 echo ' </button>';
579 echo ' </div>';
580
581 echo ' <div id="active-word-container-' . esc_attr($bot_id) . '" class="active-word-container" style="display: none;">';
582 echo ' <span id="active-word-name-' . esc_attr($bot_id) . '" class="active-word-name"></span>';
583 echo ' <button id="remove-word-btn-' . esc_attr($bot_id) . '" class="remove-word-btn" title="' . esc_attr__('Remove Word Document', 'mxchat') . '">';
584 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2">';
585 echo ' <line x1="18" y1="6" x2="6" y2="18"></line>';
586 echo ' <line x1="6" y1="6" x2="18" y2="18"></line>';
587 echo ' </svg>';
588 echo ' </button>';
589 echo ' </div>';
590
591 // Perplexity Button
592 if (apply_filters('mxchat_perplexity_should_show_logo', true)) {
593 echo ' <button id="perplexity-search-btn-' . esc_attr($bot_id) . '" class="toolbar-btn perplexity-search-btn" title="' . esc_attr__('Search with Perplexity', 'mxchat-perplexity') . '">';
594 echo ' <svg fill="currentColor" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg">';
595 echo ' <path d="M19.785 0v7.272H22.5V17.62h-2.935V24l-7.037-6.194v6.145h-1.091v-6.152L4.392 24v-6.465H1.5V7.188h2.884V0l7.053 6.494V.19h1.09v6.49L19.786 0zm-7.257 9.044v7.319l5.946 5.234V14.44l-5.946-5.397zm-1.099-.08l-5.946 5.398v7.235l5.946-5.234V8.965zm8.136 7.58h1.844V8.349H13.46l6.105 5.54v2.655zm-8.982-8.28H2.59v8.195h1.8v-2.576l6.192-5.62zM5.475 2.476v4.71h5.115l-5.115-4.71zm13.219 0l-5.115 4.71h5.115v-4.71z"></path>';
596 echo ' </svg>';
597 echo ' </button>';
598 }
599
600
601 // Image Analysis Button - hidden by default, controlled by MxChat Vision add-on
602 echo ' <input type="file" id="image-upload-' . esc_attr($bot_id) . '" class="image-upload" accept="image/*" style="display: none;" multiple>';
603 echo ' <button id="image-upload-btn-' . esc_attr($bot_id) . '" class="toolbar-btn image-upload-btn" title="' . esc_attr__('Upload Image for Analysis', 'mxchat') . '" style="display: none;">';
604 echo ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="fill: none !important;">';
605 echo ' <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z" style="fill: none !important;"/>';
606 echo ' <circle cx="12" cy="13" r="3" style="fill: none !important;"/>';
607 echo ' </svg>';
608 echo ' </button>';
609
610 // Toolbar items API (plan 65c9b6). Add-ons put their buttons here
611 // through the mxchat_chat_toolbar_items filter instead of polling
612 // the DOM after load. Only asked for when the toolbar is on: an item
613 // nobody can see is work nobody should do (the Woo cart badge used
614 // to fetch a count for a hidden toolbar on every page view).
615 if (isset($this->options['chat_toolbar_toggle']) && $this->options['chat_toolbar_toggle'] === 'on') {
616 echo self::render_toolbar_items($bot_id);
617 }
618
619 echo ' </div>';
620
621 echo ' <div class="chatbot-footer">';
622
623 // Output the privacy notice if enabled
624 if ($privacy_toggle && !empty($privacy_text)) {
625 echo '<p class="privacy-notice">' . $privacy_text . '</p>';
626 }
627
628 echo ' </div>';
629 echo ' </div>';
630 echo ' </div>';
631 echo '</div>';
632
633 if ($is_floating) {
634 echo '</div>';
635
636 if (!empty($pre_chat_message)) {
637 // Rendered hidden by default — JS checkPreChatDismissal() handles show/hide via localStorage
638 // data-nosnippet: the pre-chat teaser bubble is a sibling outside
639 // .mxchat-chatbot-wrapper, so it needs its own marker to stay out of snippets.
640 echo '<div id="pre-chat-message-' . esc_attr($bot_id) . '" class="pre-chat-message" data-nosnippet style="display:none;">';
641 echo nl2br(esc_html($pre_chat_message));
642 echo '<button class="close-pre-chat-message" aria-label="' . esc_attr__('Close', 'mxchat') . '">&times;</button>';
643 echo '</div>';
644 }
645
646 $is_initially_hidden = (strpos($visibility_class, 'hidden') !== false);
647 $aria_expanded = $is_initially_hidden ? 'false' : 'true';
648 echo '<div class="floating-chatbot-button ' . esc_attr($visibility_class) . '" id="floating-chatbot-button-' . esc_attr($bot_id) . '" role="button" tabindex="0" aria-label="' . esc_attr__('Open chat', 'mxchat') . '" aria-expanded="' . esc_attr($aria_expanded) . '" aria-controls="floating-chatbot-' . esc_attr($bot_id) . '"' . ($skip_inline_colors ? '' : ' style="background: ' . esc_attr($chatbot_background_color) . '; color: ' . esc_attr($send_button_font_color) . ';"') . '>';
649 echo '<div id="chat-notification-badge-' . esc_attr($bot_id) . '" class="chat-notification-badge" style="display: none; position: absolute; top: -8px; right: -8px; background-color: #ff4444; color: white; border-radius: 50%; padding: 4px 8px; font-size: 12px; font-weight: bold; z-index: 10001;">1</div>';
650
651 if (!empty($custom_icon)) {
652 echo '<img src="' . $custom_icon . '" alt="' . esc_attr__('Chatbot Icon', 'mxchat') . '" style="height: 48px; width: 48px; object-fit: contain;" />';
653 } else {
654 $widget_icon_style = 'height: 48px; width: 48px;';
655 if (!$skip_inline_colors) {
656 $widget_icon_style .= ' fill: ' . esc_attr($icon_color) . ';';
657 }
658 echo '<svg id="widget_icon_10" style="' . $widget_icon_style . '" viewBox="0 0 1120 1120" fill="none" xmlns="http://www.w3.org/2000/svg">';
659 echo ' <path fill-rule="evenodd" clip-rule="evenodd" d="M252 434C252 372.144 302.144 322 364 322H770C831.856 322 882 372.144 882 434V614.459L804.595 585.816C802.551 585.06 800.94 583.449 800.184 581.405L763.003 480.924C760.597 474.424 751.403 474.424 748.997 480.924L711.816 581.405C711.06 583.449 709.449 585.06 707.405 585.816L606.924 622.997C600.424 625.403 600.424 634.597 606.924 637.003L707.405 674.184C709.449 674.94 711.06 676.551 711.816 678.595L740.459 756H629.927C629.648 756.476 629.337 756.945 628.993 757.404L578.197 825.082C572.597 832.543 561.403 832.543 555.803 825.082L505.007 757.404C504.663 756.945 504.352 756.476 504.073 756H364C302.144 756 252 705.856 252 644V434ZM633.501 471.462C632.299 468.212 627.701 468.212 626.499 471.462L619.252 491.046C618.874 492.068 618.068 492.874 617.046 493.252L597.462 500.499C594.212 501.701 594.212 506.299 597.462 507.501L617.046 514.748C618.068 515.126 618.874 515.932 619.252 516.954L626.499 536.538C627.701 539.788 632.299 539.788 633.501 536.538L640.748 516.954C641.126 515.932 641.932 515.126 642.954 514.748L662.538 507.501C665.788 506.299 665.788 501.701 662.538 500.499L642.954 493.252C641.932 492.874 641.126 492.068 640.748 491.046L633.501 471.462Z" ></path>';
660 echo ' <path d="M771.545 755.99C832.175 755.17 881.17 706.175 881.99 645.545L804.595 674.184C802.551 674.94 800.94 676.551 800.184 678.595L771.545 755.99Z" ></path>';
661 echo '</svg>';
662 }
663 echo '</div>';
664 }
665
666 return ob_get_clean();
667 }
668
669 /**
670 * Render the add-on items of the chat toolbar (plan-mxchat-20260916-65c9b6).
671 *
672 * `mxchat_chat_toolbar_items` receives an empty array and the bot id and
673 * returns items shaped ['id' => 'woo-cart', 'html' => '<button …>…</button>',
674 * 'order' => 10]. Items are sorted by order (ties keep filter order), keyed
675 * by id so a later callback can replace an earlier one, and the html is run
676 * through wp_kses with the post allow-list plus the SVG shapes a toolbar
677 * icon needs (filterable via mxchat_chat_toolbar_items_allowed_html).
678 * Add-ons must not add the dropdowns / panels their button opens here —
679 * the toolbar sits inside an overflow-hidden widget; append those to body
680 * from JS on first use, the way the Woo cart does.
681 *
682 * @param string $bot_id
683 * @return string HTML, empty when no add-on contributed anything
684 */
685 public static function render_toolbar_items($bot_id) {
686 $items = apply_filters('mxchat_chat_toolbar_items', array(), $bot_id);
687 if (!is_array($items) || empty($items)) {
688 return '';
689 }
690
691 $clean = array();
692 $seq = 0;
693 foreach ($items as $key => $item) {
694 if (!is_array($item) || empty($item['html']) || !is_string($item['html'])) {
695 continue;
696 }
697 $id = isset($item['id']) ? sanitize_key($item['id']) : (is_string($key) ? sanitize_key($key) : '');
698 if ($id === '') {
699 continue;
700 }
701 $clean[$id] = array(
702 'html' => $item['html'],
703 'order' => isset($item['order']) ? (int) $item['order'] : 10,
704 'seq' => $seq++,
705 );
706 }
707 if (empty($clean)) {
708 return '';
709 }
710
711 uasort($clean, function ($a, $b) {
712 if ($a['order'] === $b['order']) {
713 return $a['seq'] <=> $b['seq'];
714 }
715 return $a['order'] <=> $b['order'];
716 });
717
718 $allowed = self::toolbar_items_allowed_html();
719 $out = '';
720 foreach ($clean as $id => $item) {
721 $html = trim(wp_kses($item['html'], $allowed));
722 if ($html === '') {
723 continue;
724 }
725 $out .= ' <!-- toolbar item: ' . esc_html($id) . ' -->' . "\n";
726 $out .= ' ' . $html . "\n";
727 }
728 return $out;
729 }
730
731 /**
732 * Allow-list for toolbar item markup: everything wp_kses_post allows (button,
733 * span, div, aria-* and data-* are in there) plus inline SVG icon shapes.
734 */
735 private static function toolbar_items_allowed_html() {
736 $allowed = wp_kses_allowed_html('post');
737 $shape = array(
738 'fill' => true,
739 'stroke' => true,
740 'stroke-width' => true,
741 'stroke-linecap' => true,
742 'stroke-linejoin' => true,
743 'transform' => true,
744 'style' => true,
745 'class' => true,
746 );
747 $allowed['svg'] = array_merge($shape, array(
748 'xmlns' => true,
749 'viewbox' => true,
750 'width' => true,
751 'height' => true,
752 'aria-hidden' => true,
753 'focusable' => true,
754 'role' => true,
755 ));
756 $allowed['path'] = array_merge($shape, array('d' => true));
757 $allowed['circle'] = array_merge($shape, array('cx' => true, 'cy' => true, 'r' => true));
758 $allowed['line'] = array_merge($shape, array('x1' => true, 'y1' => true, 'x2' => true, 'y2' => true));
759 $allowed['polyline'] = array_merge($shape, array('points' => true));
760 $allowed['polygon'] = array_merge($shape, array('points' => true));
761 $allowed['rect'] = array_merge($shape, array('x' => true, 'y' => true, 'width' => true, 'height' => true, 'rx' => true, 'ry' => true));
762 $allowed['g'] = $shape;
763 if (!isset($allowed['button'])) {
764 $allowed['button'] = array();
765 }
766 $allowed['button'] = array_merge($allowed['button'], array(
767 'type' => true,
768 'disabled' => true,
769 'aria-haspopup' => true,
770 'aria-pressed' => true,
771 ));
772 return apply_filters('mxchat_chat_toolbar_items_allowed_html', $allowed);
773 }
774
775 /**
776 * Get bot-specific options for multi-bot functionality
777 * Falls back to default options if bot_id is 'default' or multi-bot add-on is not active
778 */
779 private function get_bot_options($bot_id = 'default') {
780 // If default bot or multi-bot add-on not active, return empty (use default options)
781 if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
782 return array();
783 }
784
785 //Hook for multi-bot add-on to provide bot-specific options
786 $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
787
788 return is_array($bot_options) ? $bot_options : array();
789 }
790
791 /**
792 * Get bot-specific Pinecone configuration
793 * Used in the knowledge retrieval functions
794 */
795 private function get_bot_pinecone_config($bot_id = 'default') {
796 // If default bot or multi-bot add-on not active, use default Pinecone config
797 if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
798 $addon_options = get_option('mxchat_pinecone_addon_options', array());
799 return array(
800 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
801 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
802 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
803 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
804 );
805 }
806
807 // Hook for multi-bot add-on to provide bot-specific Pinecone config
808 $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
809
810 return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
811 }
812
813
814 private function determine_email_collection_state() {
815 // Logged-in users skip the email form, UNLESS the owner has turned on
816 // "Also Show for Logged-In Users" (c0cfaf). On a membership or LMS site
817 // every visitor is signed in, so the short-circuit meant lead capture —
818 // and the consent checkbox — never appeared at all.
819 //
820 // Deliberately no PII in this decision: the returned profile values are
821 // NOT rendered into the markup, because this page HTML is cacheable and
822 // a cached form carrying one user's address would serve it to the next
823 // visitor. Pre-fill travels on the nocache'd AJAX check instead
824 // (mxchat_check_email_provided). Both logged-in and guest requests render
825 // the same empty form, so the cached copy is correct for either.
826 if (is_user_logged_in()) {
827 $options = get_option('mxchat_options', array());
828 $show_for_logged_in = isset($options['lead_capture_logged_in_toggle'])
829 && $options['lead_capture_logged_in_toggle'] === 'on';
830
831 $current_user = wp_get_current_user();
832 return [
833 'show_email_form' => $show_for_logged_in,
834 'user_email' => $current_user->user_email,
835 'user_name' => $current_user->display_name ?: $current_user->first_name ?: ''
836 ];
837 }
838
839 // For guests, default to showing the email form.
840 // The session-based check happens client-side via AJAX since the
841 // session ID lives in the browser cookie/localStorage.
842 return [
843 'show_email_form' => true,
844 'user_email' => '',
845 'user_name' => ''
846 ];
847 }
848
849
850 /**
851 * NEW: Determine if and which chatbot should be displayed
852 */
853 private function get_display_bot() {
854 // Delegates to the static so the enqueue-time gate (smart asset loading,
855 // plan-915355) and this render-time decision share ONE code path and can
856 // never disagree. The static reads mxchat_options fresh — same row this
857 // instance loaded at construct.
858 return self::compute_display_bot();
859 }
860
861 /**
862 * Static single source of truth for the display decision (plan-915355).
863 * Combines the per-page meta box, the append_to_body global toggle, and the
864 * post-type include/exclude mode. Returns a bot id ('default' or specific)
865 * when the auto-append widget will render on the current request, false when
866 * it won't. Static (not a second instance) deliberately: MxChat_Public's
867 * constructor registers a wp_footer action, so constructing a throwaway
868 * instance would double-append the widget.
869 */
870 public static function compute_display_bot() {
871 // The Elementor builder canvas is not a chat surface (plan 95dd1e part 2):
872 // its preview iframe is a real front-end page load, so without this guard
873 // the Auto-Display instance renders LIVE inside the canvas — front-end
874 // chat scripts firing in the editor, able to start a session for the
875 // person editing. Returning false here suppresses both the wp_footer
876 // auto-append and the asset enqueue gate for preview requests only; the
877 // placement widget's own canvas rendering is a static placeholder anyway.
878 if (did_action('elementor/loaded')
879 && class_exists('\Elementor\Plugin')
880 && isset(\Elementor\Plugin::$instance->preview)
881 && \Elementor\Plugin::$instance->preview
882 && \Elementor\Plugin::$instance->preview->is_preview_mode()) {
883 return false;
884 }
885
886 $options = get_option('mxchat_options', array());
887 if (!is_array($options)) {
888 $options = array();
889 }
890
891 // Get page-specific settings from meta box
892 $page_setting = self::get_page_bot_setting();
893
894 $global_autoshow = isset($options['append_to_body']) && $options['append_to_body'] === 'on';
895 $global_default_bot = isset($options['default_bot']) ? $options['default_bot'] : 'default';
896
897 // If page specifically hides chatbot, don't show anything
898 if ($page_setting && $page_setting['action'] === 'hide') {
899 return false;
900 }
901
902 // If page specifies a specific bot, use that
903 if ($page_setting && $page_setting['action'] === 'show') {
904 return $page_setting['bot_id'];
905 }
906
907 // Page setting is 'global' or no page setting exists
908 // Check global auto-show setting
909 if ($global_autoshow) {
910 // Check post type visibility settings
911 if (!self::should_show_on_current_post_type()) {
912 return false;
913 }
914
915 // Global auto-show is enabled, return the default bot
916 return $global_default_bot;
917 }
918
919 // Global auto-show is disabled and no page-specific bot selected
920 // Don't show chatbot (user should use shortcodes)
921 return false;
922 }
923
924 /**
925 * Smart asset loading opt-in (plan-915355). Standalone option — deliberately
926 * NOT a mxchat_options key, so it can never be stripped by mxchat_sanitize().
927 * Default off: enqueue behavior is byte-identical to before until an owner
928 * turns the toggle on.
929 */
930 public static function is_smart_asset_loading_enabled() {
931 return get_option('mxchat_smart_asset_loading', 'off') === 'on';
932 }
933
934 /**
935 * Will the chat widget render on the current request? (plan-915355)
936 *
937 * True when the auto-append decision resolves to a bot, OR the singular
938 * post's content contains the [mxchat_chatbot] shortcode (first-chance
939 * detection so shortcode pages keep head-loaded CSS — no FOUC). Computed
940 * once per request and cached, so the wp_enqueue_scripts gate and any
941 * add-on consulting this later in the same request always get one answer.
942 *
943 * Filter `mxchat_should_load_assets` is the force-load escape hatch for
944 * headless/builder/custom-JS setups whose shortcode placement is invisible
945 * to has_shortcode (builder-stored content, template files, widget areas).
946 * Note the render-time safety net in render_chatbot_shortcode() still
947 * force-loads assets whenever the shortcode actually renders — the filter
948 * is only needed where even that net can't fire (e.g. markup assembled
949 * outside WP rendering).
950 */
951 public static function should_load_assets() {
952 static $cached = null;
953 if ($cached !== null) {
954 return $cached;
955 }
956
957 // Never gate admin/ajax requests — this decision is for front-end enqueues only.
958 if (is_admin()) {
959 $cached = true;
960 return $cached;
961 }
962
963 $display_bot = self::compute_display_bot();
964 $has_shortcode = false;
965
966 if ($display_bot === false && is_singular()) {
967 $post = get_post();
968 if ($post && has_shortcode((string) $post->post_content, 'mxchat_chatbot')) {
969 $has_shortcode = true;
970 }
971 // The mxchat/chatbot block (plan-95dd1e) stores a block comment, not
972 // shortcode text, so has_shortcode can't see it — first-chance detect
973 // it here for the same no-FOUC reason. The render-time safety net in
974 // render_chatbot_shortcode() still covers template/widget placements.
975 if ($post && !$has_shortcode && function_exists('has_block')
976 && has_block('mxchat/chatbot', $post)) {
977 $has_shortcode = true;
978 }
979 }
980
981 $should = ($display_bot !== false) || $has_shortcode;
982
983 $cached = (bool) apply_filters('mxchat_should_load_assets', $should, array(
984 'display_bot' => $display_bot,
985 'has_shortcode' => $has_shortcode,
986 'post_id' => get_the_ID(),
987 ));
988
989 return $cached;
990 }
991
992 /**
993 * Check if chatbot should be shown on the current post type
994 */
995 private static function should_show_on_current_post_type() {
996 $options = get_option('mxchat_options', array());
997 if (!is_array($options)) {
998 $options = array();
999 }
1000 // Get visibility settings
1001 $mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
1002 $list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
1003
1004 // Ensure list is an array
1005 if (!is_array($list)) {
1006 $list = array();
1007 }
1008
1009 // If mode is 'all', show on all post types
1010 if ($mode === 'all') {
1011 return true;
1012 }
1013
1014 // Get current post type
1015 $current_post_type = self::get_current_post_type();
1016
1017 // If we can't determine post type, default to showing
1018 if (empty($current_post_type)) {
1019 return true;
1020 }
1021
1022 // Check based on mode
1023 if ($mode === 'include') {
1024 // Only show on selected post types
1025 return in_array($current_post_type, $list);
1026 } elseif ($mode === 'exclude') {
1027 // Hide on selected post types
1028 return !in_array($current_post_type, $list);
1029 }
1030
1031 // Default to showing
1032 return true;
1033 }
1034
1035 /**
1036 * Get the current post type
1037 */
1038 private static function get_current_post_type() {
1039 // Try to get from queried object first
1040 $queried_object = get_queried_object();
1041
1042 if ($queried_object instanceof WP_Post) {
1043 return $queried_object->post_type;
1044 }
1045
1046 // Try get_post_type()
1047 $post_type = get_post_type();
1048 if ($post_type) {
1049 return $post_type;
1050 }
1051
1052 // Check if we're on an archive
1053 if (is_post_type_archive()) {
1054 return get_query_var('post_type');
1055 }
1056
1057 // Check common archive types
1058 if (is_home() || is_single()) {
1059 return 'post';
1060 }
1061
1062 if (is_page()) {
1063 return 'page';
1064 }
1065
1066 return '';
1067 }
1068
1069 /**
1070 * Get page-specific bot setting using new visibility field with backward compat
1071 */
1072 private static function get_page_bot_setting($post_id = null) {
1073 if (!$post_id) {
1074 $post_id = get_the_ID();
1075 }
1076
1077 if (!$post_id) {
1078 return null;
1079 }
1080
1081 // Check new visibility field first
1082 $visibility = get_post_meta($post_id, '_mxchat_page_visibility', true);
1083
1084 if ($visibility === 'hide') {
1085 return array('action' => 'hide');
1086 }
1087
1088 if ($visibility === 'show') {
1089 $selected_bot = get_post_meta($post_id, '_mxchat_selected_bot', true);
1090 $bot_id = !empty($selected_bot) ? $selected_bot : 'default';
1091 return array('action' => 'show', 'bot_id' => $bot_id);
1092 }
1093
1094 // Backward compat: check legacy hide checkbox if no new field set
1095 if (empty($visibility)) {
1096 $hide_chatbot = get_post_meta($post_id, '_mxchat_hide_chatbot', true);
1097 if ($hide_chatbot === '1') {
1098 return array('action' => 'hide');
1099 }
1100 }
1101
1102 // Check if specific bot is selected (legacy path)
1103 $selected_bot = get_post_meta($post_id, '_mxchat_selected_bot', true);
1104 if (!empty($selected_bot)) {
1105 return array('action' => 'show', 'bot_id' => $selected_bot);
1106 }
1107
1108 // Use global setting
1109 return array('action' => 'global');
1110 }
1111
1112 /**
1113 * NEW: Determine which bot to use for shortcode
1114 */
1115 private function determine_bot_for_shortcode($shortcode_bot_id) {
1116 // If bot_id explicitly provided in shortcode, use that
1117 if (!empty($shortcode_bot_id)) {
1118 return $shortcode_bot_id;
1119 }
1120
1121 // No bot_id in shortcode, check page setting
1122 $page_setting = self::get_page_bot_setting();
1123 if ($page_setting && $page_setting['action'] === 'show') {
1124 return $page_setting['bot_id'];
1125 }
1126
1127 // Fall back to default
1128 return 'default';
1129 }
1130
1131 /**
1132 * NEW: Helper to check if auto-append is enabled globally
1133 */
1134 private function is_auto_append_enabled() {
1135 return isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on';
1136 }
1137
1138 /**
1139 * UPDATED: Debug function with new context info
1140 */
1141
1142 /**
1143 * NEW: Helper method to get available bots (for admin notices, etc.)
1144 */
1145 private function get_available_bots() {
1146 $bots = array('default' => __('Default Bot', 'mxchat'));
1147
1148 // Check if multi-bot addon is active
1149 if (class_exists('MxChat_Multi_Bot_Manager')) {
1150 $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
1151 $available_bots = $multi_bot_manager->get_available_bots();
1152
1153 // Add the available bots
1154 foreach ($available_bots as $bot_id => $bot_name) {
1155 $bots[$bot_id] = $bot_name;
1156 }
1157 }
1158
1159 return $bots;
1160 }
1161
1162
1163
1164 }
1165 ?>