Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/supportcandy/class-wpsc-installation.php
+++ b/supportcandy/class-wpsc-installation.php
@@ -1861,7 +1861,7 @@
$upload_dir = wp_upload_dir();
$filepath = $upload_dir['basedir'] . '/wpsc';
if ( ! file_exists( $filepath ) ) {
- mkdir( $filepath, 0755, true );
+ wp_mkdir_p( $filepath );
}
// Dashboard cards.
@@ -2088,6 +2088,10 @@
'popup-delay' => 10,
'popup-display-limit' => 3,
'custom-prompt' => '',
+ 'widget-position' => 'right',
+ 'visibility-mode' => 'all',
+ 'visibility-pages' => array(),
+ 'visibility-types' => array(),
)
);
@@ -2920,6 +2924,10 @@
'popup-delay' => 10,
'popup-display-limit' => 3,
'custom-prompt' => '',
+ 'widget-position' => 'right',
+ 'visibility-mode' => 'all',
+ 'visibility-pages' => array(),
+ 'visibility-types' => array(),
)
);
}
@@ -3124,6 +3132,24 @@
}
}
+ if ( version_compare( self::$current_version, '3.5.7', '<' ) ) {
+
+ // chatbot widget position and page visibility.
+ $chatbot = get_option( 'wpsc-ps-acb-chatbot-settings' );
+ if ( is_array( $chatbot ) ) {
+ $chatbot = array_merge(
+ array(
+ 'widget-position' => 'right',
+ 'visibility-mode' => 'all',
+ 'visibility-pages' => array(),
+ 'visibility-types' => array(),
+ ),
+ $chatbot
+ );
+ update_option( 'wpsc-ps-acb-chatbot-settings', $chatbot );
+ }
+ }
+
update_option( 'wpsc-string-translation', $string_translations );
self::set_upgrade_complete();
}
--- a/supportcandy/framework/class-wpsc-framework.php
+++ b/supportcandy/framework/class-wpsc-framework.php
@@ -419,6 +419,7 @@
$localizations['translations']['req_fields_missing'] = esc_attr__( 'Required fields missing!', 'supportcandy' );
$localizations['translations']['confirm'] = esc_attr__( 'Are you sure?', 'supportcandy' );
$localizations['translations']['something_wrong'] = esc_attr__( 'Something went wrong!', 'supportcandy' );
+ $localizations['translations']['upload_in_progress'] = esc_attr__( 'Please wait until the attached files finish uploading.', 'supportcandy' );
$localizations['translations']['view_more'] = esc_attr__( 'View more!', 'supportcandy' );
$localizations['translations']['view_less'] = esc_attr__( 'View less!', 'supportcandy' );
$localizations['translations']['warning_message'] = html_entity_decode( esc_attr__( 'There is unposted text in the reply area. Are you sure you want to discard and proceed?', 'supportcandy' ), ENT_QUOTES );
--- a/supportcandy/global-functions.php
+++ b/supportcandy/global-functions.php
@@ -6,6 +6,10 @@
* @package SupportCandy
*/
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly!
+}
+
/**
* Perform outside scope translations within plugin or addons
*
--- a/supportcandy/includes/EDD_SL_Plugin_Updater.php
+++ b/supportcandy/includes/EDD_SL_Plugin_Updater.php
@@ -5,6 +5,13 @@
exit;
}
+/*
+ * Every SupportCandy add-on bundles an identical copy of this file and loads it only when the class below is not
+ * already available, so the declaration must be conditional to avoid a "cannot redeclare class" fatal error.
+ * Keep all copies at the same version.
+ */
+if ( ! class_exists( 'WPSC_EDD_SL_Plugin_Updater' ) ) :
+
/**
* Allows plugins to use their own update API.
*
@@ -640,3 +647,5 @@
}
}
+
+endif;
--- a/supportcandy/includes/admin/agent-settings/class-wpsc-agent-settings.php
+++ b/supportcandy/includes/admin/agent-settings/class-wpsc-agent-settings.php
@@ -303,7 +303,9 @@
$agent->reset_unresolved_count();
}
- do_action( 'after_set_add_agent', $agent );
+ // Hook renamed in 3.5.7 (added wpsc_ prefix). Callbacks on the old name keep working.
+ do_action_deprecated( 'after_set_add_agent', array( $agent ), '3.5.7', 'wpsc_after_set_add_agent' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Legacy hook name kept for backward compatibility.
+ do_action( 'wpsc_after_set_add_agent', $agent );
wp_die();
}
--- a/supportcandy/includes/admin/ai-assistant/admin/class-wpsc-ps-ai-functions.php
+++ b/supportcandy/includes/admin/ai-assistant/admin/class-wpsc-ps-ai-functions.php
@@ -706,7 +706,7 @@
if ( isset( $settings['allow_internal_file'] ) && $settings['allow_internal_file'] ) {
$copied = copy( $tmp_name, $file_path );
}
- if ( ! $copied && ! move_uploaded_file( $tmp_name, $file_path ) ) {
+ if ( ! $copied && ! move_uploaded_file( $tmp_name, $file_path ) ) { // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- file already validated via is_uploaded_file(), size, extension and MIME allow-list; wp_handle_upload() would rename it and alter training-record naming.
continue;
}
@@ -932,6 +932,7 @@
$user_id = get_current_user_id();
wp_set_current_user( 0 );
+ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core REST filter, applied on purpose to run the response pipeline; its name is fixed by core.
$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( rest_do_request( $request ) ), rest_get_server(), $request );
$data = rest_get_server()->response_to_data( $response, false );
wp_set_current_user( $user_id );
--- a/supportcandy/includes/admin/ai-assistant/admin/common/class-wpsc-ps-ai-openai.php
+++ b/supportcandy/includes/admin/ai-assistant/admin/common/class-wpsc-ps-ai-openai.php
@@ -184,6 +184,44 @@
}
/**
+ * Output token budget for a given attempt.
+ *
+ * A response cut off by max_output_tokens is retried with more room: the stored Max Tokens
+ * setting is the budget for the first attempt, and later attempts double it each time (capped at
+ * the setting's own upper limit). The setting itself is never changed.
+ *
+ * @param int $max_tokens Configured Max Tokens.
+ * @param int $attempt Attempt number, starting at 1.
+ * @return int
+ */
+ public static function retry_max_tokens( int $max_tokens, int $attempt ): int {
+
+ if ( $attempt <= 1 ) {
+ return $max_tokens;
+ }
+
+ return (int) min( max( $max_tokens, 16384 ), $max_tokens * ( 2 ** ( $attempt - 1 ) ) );
+ }
+
+ /**
+ * Whether the API returned a 200 response that was cut off before it finished (status
+ * "incomplete", e.g. reason "max_output_tokens"). Such a response has no usable answer, so it must
+ * not be treated as a genuine "nothing found" or as a valid reply.
+ *
+ * @param array|WP_Error $response Response from wp_remote_post().
+ * @return bool
+ */
+ public static function is_incomplete_response( $response ): bool {
+
+ if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
+ return false;
+ }
+
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+ return is_array( $body ) && ( $body['status'] ?? '' ) === 'incomplete';
+ }
+
+ /**
* Determine if the response from the API is retryable based on status code or error.
*
* @param array $response The response from the API.
--- a/supportcandy/includes/admin/ai-assistant/admin/index.php
+++ b/supportcandy/includes/admin/ai-assistant/admin/index.php
@@ -1,46 +1,49 @@
<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly!
+}
// Load provider interface first so implementation classes can be parsed safely.
-$provider_interface_file = __DIR__ . '/interfaces/class-wpsc-ps-ait-provider-interfaces.php';
-if ( file_exists( $provider_interface_file ) ) {
- include_once $provider_interface_file;
+$wpsc_provider_interface_file = __DIR__ . '/interfaces/class-wpsc-ps-ait-provider-interfaces.php';
+if ( file_exists( $wpsc_provider_interface_file ) ) {
+ include_once $wpsc_provider_interface_file;
}
// Load remaining interface-related classes.
-foreach ( glob( __DIR__ . '/interfaces/*.php' ) as $filename ) {
- if ( $filename === $provider_interface_file ) {
+foreach ( glob( __DIR__ . '/interfaces/*.php' ) as $wpsc_file ) {
+ if ( $wpsc_file === $wpsc_provider_interface_file ) {
continue;
}
- include_once $filename;
+ include_once $wpsc_file;
}
// Load AI training.
-foreach ( glob( __DIR__ . '/ai-training/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/ai-training/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
-$ai_settings = get_option( 'wpsc-ps-ai-assistant-settings', array() );
+$wpsc_ai_settings = get_option( 'wpsc-ps-ai-assistant-settings', array() );
// Load auto draft, polish reply & ticket summary only when the AI assistant is enabled.
-if ( ! empty( $ai_settings['status'] ) && '1' === $ai_settings['status'] ) {
+if ( ! empty( $wpsc_ai_settings['status'] ) && '1' === $wpsc_ai_settings['status'] ) {
// Load auto draft.
- foreach ( glob( __DIR__ . '/auto-draft/*.php' ) as $filename ) {
- include_once $filename;
+ foreach ( glob( __DIR__ . '/auto-draft/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load polish reply.
- foreach ( glob( __DIR__ . '/polish-reply/*.php' ) as $filename ) {
- include_once $filename;
+ foreach ( glob( __DIR__ . '/polish-reply/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
}
// Load AI assistant settings.
-foreach ( glob( __DIR__ . '/settings/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/settings/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load common classes.
-foreach ( glob( __DIR__ . '/common/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/common/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
--- a/supportcandy/includes/admin/ai-assistant/admin/settings/class-wpsc-ps-ai-setting-general.php
+++ b/supportcandy/includes/admin/ai-assistant/admin/settings/class-wpsc-ps-ai-setting-general.php
@@ -69,7 +69,7 @@
<div class="label-container">
<label for="wpsc-ai-max-tokens"><?php esc_attr_e( 'Max Tokens', 'supportcandy' ); ?></label>
</div>
- <p class="wpsc-input-desc"><?php esc_attr_e( 'Upper limit on the length of each AI response, sent to the provider with every request. Enter a value between 500 and 16384.', 'supportcandy' ); ?></p>
+ <p class="wpsc-input-desc"><?php esc_attr_e( 'Upper limit on the length of each AI response, sent to the provider with every request. Enter a value between 500 and 16384. A value that is too low does not just shorten answers: a response that runs out of room is cut off before it is finished, and the chatbot may then fail to answer or report that it cannot find information it actually has. Long answers such as product lists often need 1000 or more, so raise this if you see failed or incomplete replies.', 'supportcandy' ); ?></p>
<input type="number" id="wpsc-ai-max-tokens" value="<?php echo esc_attr( $ai_settings['max-tokens'] ); ?>" name="wpsc-ai-max-tokens" placeholder="<?php esc_attr_e( 'Enter the maximum number of tokens', 'supportcandy' ); ?> "/>
</div>
--- a/supportcandy/includes/admin/ai-assistant/index.php
+++ b/supportcandy/includes/admin/ai-assistant/index.php
@@ -1,10 +1,13 @@
<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly!
+}
-foreach ( glob( __DIR__ . '/admin/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/admin/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load models.
-foreach ( glob( __DIR__ . '/models/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/models/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
--- a/supportcandy/includes/admin/ai-assistant/models/class-wpsc-ps-ai-logs.php
+++ b/supportcandy/includes/admin/ai-assistant/models/class-wpsc-ps-ai-logs.php
@@ -372,7 +372,7 @@
* Get where for find method
*
* @param array $filter - user filter.
- * @return array
+ * @return string
*/
private static function get_where( $filter ) {
--- a/supportcandy/includes/admin/ai-assistant/models/class-wpsc-rag-training-file.php
+++ b/supportcandy/includes/admin/ai-assistant/models/class-wpsc-rag-training-file.php
@@ -487,7 +487,7 @@
* Get where for find method
*
* @param array $filter - user filter.
- * @return array
+ * @return string
*/
private static function get_where( $filter ) {
$where = array( '1=1' );
--- a/supportcandy/includes/admin/ai-chatbot/controller/class-wpsc-acb-chats.php
+++ b/supportcandy/includes/admin/ai-chatbot/controller/class-wpsc-acb-chats.php
@@ -22,6 +22,59 @@
public static $session_uuid = '';
/**
+ * "Current Page" system-prompt block for the message being handled (see
+ * build_page_context()). Built per request, never cached, because the
+ * customer can browse to another page while the same chat stays open.
+ *
+ * @var string
+ */
+ private static $page_context = '';
+
+ /**
+ * Characters of page text put in the prompt every turn. Longer pages are cut here and the rest is
+ * reachable on demand through the read_current_page tool, so token use stays low on every other turn.
+ */
+ const PAGE_SUMMARY_CHARS = 1500;
+
+ /**
+ * Most characters of a page's content ever processed, however long the post is.
+ */
+ const PAGE_MAX_CHARS = 200000;
+
+ /**
+ * ID of the page being viewed when its text was cut to PAGE_SUMMARY_CHARS (0 otherwise). The
+ * read_current_page tool is only offered while this is set and only ever reads this post.
+ *
+ * @var int
+ */
+ public static $truncated_page_id = 0;
+
+ /**
+ * ID of the public post the customer is viewing, whether or not its text was cut (0 when the page is
+ * not a single public post). Lets a failed knowledge-base search fall back to the page's own text.
+ *
+ * @var int
+ */
+ public static $page_post_id = 0;
+
+ /**
+ * The "Current Page" detail lines for this request (title, price, stock...), searched together with the
+ * page text when the knowledge base has no answer.
+ *
+ * @var string
+ */
+ public static $page_facts = '';
+
+ /**
+ * Passages of the viewed page that match the customer's current message (see find_page_excerpt()), or ''.
+ * Sent to the model next to that message for this turn only - the page text in the system prompt alone
+ * was not enough for the model to use it once a tool had come back empty.
+ *
+ * @var string
+ */
+ private static $page_excerpt = '';
+
+ /**
* Hard cap on tool-executing rounds within a single agentic turn, so a
* tool-call/observe loop can't run away. One additional forced,
* tool-free synthesis call is always allowed after this cap is hit.
@@ -159,6 +212,14 @@
WPSC_ACB_Cookies::set_session_cookie( 'wpsc_acb_session_id', self::$session_uuid );
}
+ // What the customer is looking at right now, so the assistant can answer about "this page/product".
+ self::$page_context = self::build_page_context(
+ isset( $_POST['page_url'] ) ? esc_url_raw( wp_unslash( $_POST['page_url'] ) ) : '',
+ isset( $_POST['page_title'] ) ? sanitize_text_field( wp_unslash( $_POST['page_title'] ) ) : ''
+ );
+
+ self::$page_excerpt = self::find_page_excerpt( $message );
+
// Get AI response based on the user message.
$ai_response = self::get_ai_response( $message );
@@ -647,13 +708,18 @@
$provider = WPSC_AIBOT_Provider_Factory::get_current_provider( $ai_settings['provider'] );
- $system_prompt = self::get_system_prompt() . self::get_known_user_context();
+ $system_prompt = self::get_system_prompt() . self::get_known_user_context() . self::$page_context;
$conversation_history = self::get_conversation_history();
$tools = self::get_chatbot_function_tools();
- $response = self::run_agentic_tool_loop( $provider, $ai_settings, $message, $system_prompt, $conversation_history, $tools );
+ // For the model only (never stored, never used to detect the customer's language): the customer's message plus,
+ // when the page they are viewing has text that matches it, that text - so a question the page answers is
+ // answered from it directly, whichever tool the model would otherwise have tried first.
+ $model_message = '' === self::$page_excerpt ? $message : $message . "nn[Text from the page the customer is viewing that matches their question - an approved source; answer from it when it answers the question: " . self::$page_excerpt . ']';
+
+ $response = self::run_agentic_tool_loop( $provider, $ai_settings, $message, $system_prompt, $conversation_history, $tools, $model_message );
$assistant_message = '';
if ( ! empty( $response['response'] ) && is_string( $response['response'] ) ) {
@@ -893,14 +959,23 @@
* @param string $system_prompt System prompt (including known-user context).
* @param array $conversation_history Conversation history.
* @param array $tools Tool definitions for the provider.
+ * @param string $model_message The customer message as sent to the model (the message plus any matching page text); defaults to $message.
* @return array
*/
- private static function run_agentic_tool_loop( $provider, $ai_settings, $message, $system_prompt, $conversation_history, $tools ) {
+ private static function run_agentic_tool_loop( $provider, $ai_settings, $message, $system_prompt, $conversation_history, $tools, $model_message = '' ) {
+
+ if ( '' === $model_message ) {
+ $model_message = $message;
+ }
$loop_started_at = microtime( true );
$total_tokens = 0;
$tool_call_counts = array();
$tool_last_results = array();
+
+ // Results of read-only tool calls already made this turn, keyed by tool name + arguments - see the
+ // repeated-call check in the loop below.
+ $tool_results_by_call = array();
$tool_context = array();
$force_final = false;
@@ -941,7 +1016,7 @@
// fact, even though it wasn't retrieved from a knowledge-base
// lookup), then grow it with each search_knowledge_base result and
// this turn's own message.
- $grounding_corpus = ' ' . $message;
+ $grounding_corpus = ' ' . $message . ' ' . self::$page_context . ' ' . self::$page_excerpt;
foreach ( $conversation_history as $history_entry ) {
if ( in_array( $history_entry['role'] ?? '', array( 'assistant', 'user' ), true ) && is_string( $history_entry['content'] ?? null ) ) {
$grounding_corpus .= ' ' . $history_entry['content'];
@@ -974,7 +1049,7 @@
// check ever gets a chance to run.
$tool_context['max_retries'] = 1;
- $response = $provider->wpsc_get_chat_response( $ai_settings, $message, $system_prompt, $conversation_history, $tools, $tool_context );
+ $response = $provider->wpsc_get_chat_response( $ai_settings, $model_message, $system_prompt, $conversation_history, $tools, $tool_context );
if ( ! is_array( $response ) ) {
$response = array( 'success' => false );
@@ -1013,7 +1088,7 @@
break;
}
- $retry_message = self::build_empty_completion_retry_message( $message, $tool_activity_log );
+ $retry_message = self::build_empty_completion_retry_message( $model_message, $tool_activity_log );
$retry_context = array(
'tool_choice' => 'none',
'max_retries' => 1,
@@ -1135,7 +1210,7 @@
// the detail rather than retrieving it. Never let
// that reach the customer.
$final_text = self::localize_safe_reply( $provider, $ai_settings, $message, $conversation_history, esc_html__( "I'm sorry, I don't have that specific detail confirmed, and I don't want to give you inaccurate information. Would you like me to create a support ticket so our team can follow up with the exact details?", 'supportcandy' ), $total_tokens );
- } elseif ( 1 === count( $tool_call_counts ) && isset( $tool_call_counts['search_knowledge_base'] ) && ! $kb_search_found_match && self::reply_answers_beyond_knowledge_base( $provider, $ai_settings, $final_text, $total_tokens ) ) {
+ } elseif ( 1 === count( $tool_call_counts ) && isset( $tool_call_counts['search_knowledge_base'] ) && ! $kb_search_found_match && '' === self::$page_excerpt && self::reply_answers_beyond_knowledge_base( $provider, $ai_settings, $final_text, $total_tokens ) ) {
// search_knowledge_base was the only tool used this turn and never
// found a match, yet the model answered substantively anyway -
@@ -1201,7 +1276,17 @@
$max_calls = $metadata['max_calls_per_turn'] ?? 0;
$calls_so_far = $tool_call_counts[ $tool_name ] ?? 0;
- if ( $max_calls > 0 && $calls_so_far >= $max_calls ) {
+ // An identical call to a read-only tool already answered this turn cannot return anything new, so
+ // repeating it only costs another round trip. Hand back the earlier result and have the model reply.
+ $call_key = $tool_name . ':' . md5( (string) wp_json_encode( is_array( $tool_call['arguments'] ?? null ) ? $tool_call['arguments'] : array() ) );
+ $is_repeat_call = empty( $metadata['side_effecting'] ) && empty( $metadata['mutates_cart'] ) && isset( $tool_results_by_call[ $call_key ] );
+
+ if ( $is_repeat_call ) {
+ $tool_result = $tool_results_by_call[ $call_key ];
+ $tool_result['already_called_this_turn'] = true;
+ $tool_result['note'] = 'This exact call already ran this turn and returned the data in this result. Do not repeat it. Reply to the customer now using that result; if it does not contain what they asked for, say so.';
+ $force_final = true;
+ } elseif ( $max_calls > 0 && $calls_so_far >= $max_calls ) {
// Repeating a capped tool is not a failure of the tool: its real result
// from this turn is still valid. Hand that back (a bare success=false
// reads to the model as a technical fault it then reports to the
@@ -1215,6 +1300,13 @@
$tool_result = self::execute_chatbot_tool_call( $tool_call );
$tool_last_results[ $tool_name ] = $tool_result;
$tool_result = self::find_order_in_other_order_systems( $metadata['order_source'] ?? '', $tool_call, $tool_result );
+
+ if ( ! empty( $metadata['side_effecting'] ) || ! empty( $metadata['mutates_cart'] ) ) {
+ // State may have changed (e.g. the cart), so earlier read results can no longer be reused.
+ $tool_results_by_call = array();
+ } elseif ( is_array( $tool_result ) && ! empty( $tool_result['success'] ) ) {
+ $tool_results_by_call[ $call_key ] = $tool_result;
+ }
}
if ( ! is_array( $tool_result ) ) {
@@ -1243,6 +1335,12 @@
if ( is_string( $tool_result_json ) ) {
$grounding_corpus .= ' ' . $tool_result_json;
}
+
+ // A knowledge-base miss that came back with text from the page the customer is viewing
+ // (see WPSC_ACB_Search_Knowledge_Base) is a sourced answer, not a guess.
+ if ( 'search_knowledge_base' === $tool_name && ! empty( $tool_result['current_page_text'] ) ) {
+ $kb_search_found_match = true;
+ }
}
// Store add-ons flag their tools in the registry (see
@@ -1732,6 +1830,12 @@
$judge_system_prompt = 'You are a safety check reviewing one candidate customer-support chatbot reply, which may be written in any language. It was written in response to a customer question for which a knowledge-base search found no matching information. Decide only this: does the reply actually attempt to answer the customer's question with substantive information - facts, steps, recommendations, or explanations - as opposed to plainly telling the customer that the answer could not be found in the available information and stopping there (optionally still offering to create a support ticket, escalate, or help with something else)? Respond with exactly one word, in English: YES or NO. No punctuation, no explanation, no other text.';
+ // The customer may be viewing a page whose details the assistant was given as a legitimate source (see
+ // build_page_context()). An answer that only uses facts stated there is sourced, not invented.
+ if ( '' !== self::$page_context ) {
+ $judge_system_prompt .= ' Exception: the customer was viewing a web page whose details are given below, and the assistant was allowed to answer from them. If every substantive fact in the reply is stated in those page details, answer NO. Answer YES only if the reply gives substantive information that is NOT supported by them.' . self::$page_context;
+ }
+
$judge_response = $provider->wpsc_get_chat_response(
$ai_settings,
$plain_text,
@@ -2100,6 +2204,236 @@
}
/**
+ * Build the "Current Page" system-prompt block for the page the customer
+ * is on. The URL comes from the browser, so it is only used to find the
+ * page: it must belong to this site and resolve to a published,
+ * public, non-password-protected post - everything put in front of the
+ * model is then read from the database, never taken from the request
+ * (except the page title for URLs that are not a post, e.g. archives).
+ * Add-ons enrich or replace the details through the
+ * 'wpsc_acb_page_context_blocks' filter (e.g. WooCommerce product data).
+ *
+ * @param string $url Page URL sent by the browser.
+ * @param string $title Page title sent by the browser.
+ * @return string Prompt block, or an empty string when there is nothing usable.
+ */
+ private static function build_page_context( $url, $title ) {
+
+ self::$truncated_page_id = 0;
+ self::$page_post_id = 0;
+ self::$page_facts = '';
+
+ $url = trim( (string) $url );
+ if ( '' === $url || strlen( $url ) > 2000 ) {
+ return '';
+ }
+
+ // Same site only.
+ $url_parts = wp_parse_url( $url );
+ $home_host = wp_parse_url( home_url(), PHP_URL_HOST );
+ if ( empty( $url_parts['host'] ) || empty( $home_host ) || 0 !== strcasecmp( preg_replace( '/^www./i', '', $url_parts['host'] ), preg_replace( '/^www./i', '', $home_host ) ) ) {
+ return '';
+ }
+
+ // Resolve the page to a post: any permalink, ?p=ID, or the static front page.
+ $post_id = (int) url_to_postid( $url );
+ if ( ! $post_id ) {
+ $path = isset( $url_parts['path'] ) ? untrailingslashit( $url_parts['path'] ) : '';
+ $home_path = untrailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) );
+ if ( $path === $home_path && empty( $url_parts['query'] ) && 'page' === get_option( 'show_on_front' ) ) {
+ $post_id = (int) get_option( 'page_on_front' );
+ }
+ }
+
+ $post = $post_id ? get_post( $post_id ) : null;
+ $post_type_object = $post ? get_post_type_object( $post->post_type ) : null;
+ if ( ! $post || '' !== $post->post_password || ! $post_type_object || ! self::is_post_publicly_viewable( $post, $post_type_object ) ) {
+ $post = null;
+ }
+
+ /**
+ * Filter whether the text of a page may be given to the chatbot. The browser supplies the URL, so a
+ * published post that a membership/LMS/restriction plugin hides from the current visitor could
+ * otherwise be read through the chatbot. Only pages, posts and products are allowed by default, and
+ * posts restricted by the common membership plugins are refused (see is_page_context_allowed()).
+ * Other restriction plugins should return false for the posts they hide.
+ *
+ * @param bool $allowed Whether the post's content may be used.
+ * @param WP_Post|null $post The post the URL resolves to (already checked as public and not password protected).
+ */
+ if ( $post && ! apply_filters( 'wpsc_acb_allow_page_context', self::is_page_context_allowed( $post ), $post ) ) {
+ $post = null;
+ }
+
+ $blocks = array();
+ if ( $post ) {
+
+ self::$page_post_id = (int) $post->ID;
+ $blocks[] = '* Page title: ' . wp_strip_all_tags( get_the_title( $post ) );
+ $blocks[] = '* Page type: ' . $post_type_object->labels->singular_name;
+ $blocks[] = '* Page URL: ' . get_permalink( $post );
+
+ $full_text = self::get_page_plain_text( $post );
+ // What the visitor reads: the page content itself (a hand-written excerpt is often just a teaser
+ // without the facts); the excerpt is only a fallback for pages with no content.
+ $page_text = '' !== $full_text ? $full_text : self::clean_page_text( $post->post_excerpt );
+ if ( '' !== $page_text ) {
+ $blocks[] = '* Page text: ' . wp_html_excerpt( $page_text, self::PAGE_SUMMARY_CHARS, '...' );
+ }
+ if ( mb_strlen( $full_text ) > self::PAGE_SUMMARY_CHARS ) {
+ self::$truncated_page_id = (int) $post->ID;
+ }
+ } else {
+
+ // Not a post (archive, search results, etc.): only the address without its query string, and the title.
+ $title = wp_html_excerpt( $title, 150 );
+ if ( '' !== $title ) {
+ $blocks[] = '* Page title: ' . $title;
+ }
+ $blocks[] = '* Page URL: ' . ( $url_parts['scheme'] ?? 'https' ) . '://' . $url_parts['host'] . ( isset( $url_parts['port'] ) ? ':' . $url_parts['port'] : '' ) . ( $url_parts['path'] ?? '/' );
+ }
+
+ /**
+ * Filter the lines describing the page the customer is viewing, added to the chatbot's system prompt.
+ * An add-on may append details (price, stock, course info...) or replace the generic ones for its own content type.
+ *
+ * @param string[] $blocks Bullet-point lines (each already prefixed with "* ").
+ * @param WP_Post|null $post The page's post, or null when the page is not a single public post.
+ * @param string $url The page URL sent by the browser.
+ */
+ $blocks = apply_filters( 'wpsc_acb_page_context_blocks', $blocks, $post, $url );
+ $blocks = array_values( array_filter( array_map( 'strval', (array) $blocks ) ) );
+ if ( empty( $blocks ) ) {
+ return '';
+ }
+
+ // The detail lines searched together with the page text must not repeat that text (the "Page text" line
+ // does), or every word would look equally common across passages and nothing would count as distinctive.
+ self::$page_facts = implode(
+ ' ',
+ array_filter(
+ $blocks,
+ function ( $block ) {
+ return 0 !== strpos( $block, '* Page text: ' );
+ }
+ )
+ );
+
+ return "nnCurrent Pagenn"
+ . "* The customer is viewing this page (read just now); "this page/product/it" means it. Its details are an approved source like knowledge base results: check them first for every question, even if the page isn't mentioned, and answer from them when they contain the answer (never say it couldn't be found then). Never mention you were given them.n"
+ . ( self::$truncated_page_id ? "* The page text below is cut short: if the answer is not in it, call read_current_page with the customer's question before saying it is unavailable.n" : '' )
+ . implode( "n", $blocks );
+ }
+
+ /**
+ * Default answer to "may this post's text be given to the chatbot?". Fails closed: the visitor chooses the
+ * URL, so content that is restricted for them must never be read, whatever the page builder or plugin.
+ * Only pages, posts and products are used by default (custom post types such as lessons, courses or
+ * downloads are usually gated); 'wpsc_acb_page_context_post_types' extends that list. Posts restricted
+ * by MemberPress, Restrict Content Pro, Paid Memberships Pro or WooCommerce Memberships are refused for
+ * the current visitor.
+ *
+ * @param WP_Post $post The post.
+ * @return bool
+ */
+ private static function is_page_context_allowed( $post ) {
+
+ /**
+ * Filter the post types whose text the chatbot may read when the customer is viewing them.
+ *
+ * @param string[] $post_types Post type slugs.
+ */
+ $post_types = (array) apply_filters( 'wpsc_acb_page_context_post_types', array( 'page', 'post', 'product' ) );
+ if ( ! in_array( $post->post_type, $post_types, true ) ) {
+ return false;
+ }
+
+ $user_id = get_current_user_id();
+
+ // MemberPress.
+ if ( class_exists( 'MeprRule' ) && method_exists( 'MeprRule', 'is_locked' ) && MeprRule::is_locked( $post ) ) {
+ return false;
+ }
+
+ // Restrict Content Pro.
+ if ( function_exists( 'rcp_user_can_access' ) && ! rcp_user_can_access( $user_id, $post->ID ) ) {
+ return false;
+ }
+
+ // Paid Memberships Pro.
+ if ( function_exists( 'pmpro_has_membership_access' ) && ! pmpro_has_membership_access( $post->ID, $user_id ) ) {
+ return false;
+ }
+
+ // WooCommerce Memberships.
+ if ( function_exists( 'wc_memberships_is_post_content_restricted' ) && wc_memberships_is_post_content_restricted( $post->ID ) && ! current_user_can( 'wc_memberships_view_restricted_post_content', $post->ID ) ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * The passages of the viewed page (its detail lines and text) that match the customer's message, as a short
+ * string, or '' when nothing matches or there is no page. Costs no tokens when nothing matches.
+ *
+ * @param string $message Customer message.
+ * @return string
+ */
+ private static function find_page_excerpt( $message ) {
+
+ $post = self::$page_post_id > 0 ? get_post( self::$page_post_id ) : null;
+ if ( ! $post || ! class_exists( 'WPSC_ACB_Read_Current_Page' ) ) {
+ return '';
+ }
+
+ return WPSC_ACB_Read_Current_Page::find_passages( self::$page_facts . ' ' . self::get_page_plain_text( $post ), mb_substr( $message, 0, 300 ), 1000 );
+ }
+
+ /**
+ * Collapse markup, shortcodes, entities and whitespace into plain text.
+ *
+ * @param string $html Post content or excerpt.
+ * @return string
+ */
+ private static function clean_page_text( $html ) {
+
+ // Keep block boundaries as spaces so "<p>one.</p><p>Two</p>" does not become "one.Two".
+ $html = preg_replace( '/</?(?:p|div|li|ul|ol|h[1-6]|tr|td|th|br|blockquote|section|article)b[^>]*>/i', ' $0 ', (string) $html );
+ $text = html_entity_decode( wp_strip_all_tags( strip_shortcodes( $html ) ), ENT_QUOTES, 'UTF-8' );
+
+ return trim( preg_replace( '/s+/u', ' ', $text ) );
+ }
+
+ /**
+ * The full readable text of a page's post content.
+ *
+ * @param WP_Post $post Post.
+ * @return string
+ */
+ public static function get_page_plain_text( $post ) {
+
+ // Built once per request (it is needed by the prompt, the excerpt and both page tools) and capped,
+ // so an enormous post cannot make every chat message expensive.
+ static $cache = array();
+ if ( ! isset( $cache[ $post->ID ] ) ) {
+
+ $text = self::clean_page_text( mb_substr( (string) $post->post_content, 0, self::PAGE_MAX_CHARS ) );
+
+ /**
+ * Filter the readable text of the page the customer is viewing. Page builders keep their content
+ * outside post_content, so a builder integration can return that text here.
+ *
+ * @param string $text Plain text of the page.
+ * @param WP_Post $post The page's post.
+ */
+ $cache[ $post->ID ] = mb_substr( (string) apply_filters( 'wpsc_acb_page_plain_text', $text, $post ), 0, self::PAGE_MAX_CHARS );
+ }
+
+ return $cache[ $post->ID ];
+ }
+
+ /**
* Get the conversation history for a given session.
*
* @return array The conversation history.
@@ -2644,6 +2978,23 @@
return false;
}
+
+ /**
+ * Whether a post can be viewed publicly. Uses WordPress's own check (WP 5.7+) and an equivalent fallback for WP 5.6.
+ *
+ * @param WP_Post $post - post object.
+ * @param WP_Post_Type $post_type_object - post type object of the post.
+ * @return boolean
+ */
+ private static function is_post_publicly_viewable( $post, $post_type_object ) {
+
+ if ( function_exists( 'is_post_publicly_viewable' ) ) {
+ return is_post_publicly_viewable( $post );
+ }
+
+ $type_viewable = $post_type_object->publicly_queryable || ( $post_type_object->_builtin && $post_type_object->public );
+ return $type_viewable && 'publish' === get_post_status( $post );
+ }
}
endif;
--- a/supportcandy/includes/admin/ai-chatbot/includes/class-wpsc-acb-admin.php
+++ b/supportcandy/includes/admin/ai-chatbot/includes/class-wpsc-acb-admin.php
@@ -39,6 +39,66 @@
}
/**
+ * Determine whether the chat widget should be shown on the current front-end request,
+ * based on the Visibility setting (all pages / only selected / hide on selected).
+ * Must be called after the main query has run (e.g. from wp_enqueue_scripts or wp_footer).
+ *
+ * @return bool
+ */
+ private static function is_visible_on_current_page() {
+
+ static $cache = null;
+ if ( null !== $cache ) {
+ return $cache;
+ }
+
+ $acb_settings = get_option( 'wpsc-ps-acb-chatbot-settings', array() );
+ $mode = isset( $acb_settings['visibility-mode'] ) ? $acb_settings['visibility-mode'] : 'all';
+ $visible = true;
+
+ if ( in_array( $mode, array( 'include', 'exclude' ), true ) ) {
+
+ $pages = isset( $acb_settings['visibility-pages'] ) ? array_map( 'intval', (array) $acb_settings['visibility-pages'] ) : array();
+ $types = isset( $acb_settings['visibility-types'] ) ? (array) $acb_settings['visibility-types'] : array();
+
+ // Pages (static front page, shop, checkout, contact etc.) are matched by ID, including WPML/Polylang translations.
+ $queried = get_queried_object();
+ $page_id = $queried instanceof WP_Post ? (int) $queried->ID : 0;
+
+ /**
+ * Filters the ID of the page used to match the chat widget visibility "Pages" setting.
+ * Lets integrations resolve special pages (e.g. a shop page) that WordPress does not report as the queried post.
+ *
+ * @param int $page_id Current page ID, 0 if none.
+ */
+ $page_id = (int) apply_filters( 'wpsc_acb_visibility_page_id', $page_id );
+
+ $selected = $page_id && WPSC_Functions::page_id_in_pages_or_translations( $page_id, $pages );
+
+ // Content types: any post type of the current singular item, or archive/search/404 pages.
+ if ( ! $selected ) {
+ if ( is_singular() ) {
+ $selected = in_array( get_post_type(), $types, true );
+ } else {
+ $selected = in_array( '__archive', $types, true );
+ }
+ }
+
+ $visible = 'include' === $mode ? $selected : ! $selected;
+ }
+
+ /**
+ * Filters whether the chat widget is shown on the current page.
+ *
+ * @param bool $visible Whether the widget is shown.
+ * @param array $acb_settings Chatbot settings (wpsc-ps-acb-chatbot-settings).
+ */
+ $cache = (bool) apply_filters( 'wpsc_acb_is_visible_on_page', $visible, $acb_settings );
+
+ return $cache;
+ }
+
+ /**
* Backend scripts
*
* @return void
@@ -55,11 +115,8 @@
*/
public static function backend_styles() {
- if ( is_rtl() ) {
- echo file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/admin-rtl.css' ) . PHP_EOL . PHP_EOL; // phpcs:ignore
- } else {
- echo file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/admin.css' ) . PHP_EOL . PHP_EOL; // phpcs:ignore
- }
+ // One stylesheet for LTR and RTL: direction-dependent rules use logical properties.
+ echo file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/admin.css' ) . PHP_EOL . PHP_EOL; // phpcs:ignore
}
/**
@@ -70,8 +127,6 @@
public static function frontend_config() {
$css = file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/chatbot.css' ); // phpcs:ignore
- $modal_css = file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/chatbot-modal.css' ); // phpcs:ignore
- $ticket_form_css = file_get_contents( WPSC_ABSPATH . 'asset/css/ai-chatbot/chatbot-ticket-form.css' ); // phpcs:ignore
$appearance_setting = get_option(
'wpsc-acb-appearance-general',
@@ -111,8 +166,6 @@
return array(
'css' => $css,
- 'modal_css' => $modal_css,
- 'ticket_form_css' => $ticket_form_css,
'icons' => array(),
'template' => WPSC_Chatbot::get_template(),
'modal_template' => WPSC_Chatbot_Modal::get_modal_template(),
@@ -213,20 +266,10 @@
*/
public static function enqueue_frontend_scripts() {
- if ( ! self::is_frontend_enabled() ) {
+ if ( ! self::is_frontend_enabled() || ! self::is_visible_on_current_page() ) {
return;
}
- $files = array(
- 'chatbot-template.js',
- 'chatbot-ticket-modal.js',
- 'chatbot-modal.js',
- 'chatbot-welcome.js',
- 'chatbot-ticket-form.js',
- 'chatbot-icons.js',
- 'chatbot.js',
- );
- $dependency = array();
$config_js = 'window.WPSC_AI_Chatbot_Config = ' . wp_json_encode( self::frontend_config() ) . ';';
$identity = self::get_logged_in_identity();
$acb_settings = get_option( 'wpsc-ps-acb-chatbot-settings', array() );
@@ -244,33 +287,25 @@
'debug' => defined( 'WP_DEBUG' ) && WP_DEBUG,
);
- foreach ( $files as $index => $file ) {
-
- $handle = 'wpsc-acb-' . str_replace( '.js', '', $file );
- $file_path = WPSC_ABSPATH . 'asset/js/ai-chatbot/' . $file;
-
- // Bust the browser cache on every file change (not just a
- // plugin version bump) - during active development these
- // scripts change far more often than WPSC_VERSION does, and
- // a static version string lets browsers keep serving a
- // stale cached copy indefinitely after an edit.
- $version = file_exists( $file_path ) ? (string) filemtime( $file_path ) : WPSC_VERSION;
-
- wp_enqueue_script(
- $handle,
- WPSC_PLUGIN_URL . 'asset/js/ai-chatbot/' . $file,
- $dependency,
- $version,
- true
- );
-
- if ( 0 === $index ) {
- wp_add_inline_script( $handle, $config_js, 'before' );
- wp_localize_script( $handle, 'wpsc_ai_chatbot', $ajax_data );
- }
-
- $dependency = array( $handle );
- }
+ // Single script, no dependencies (the chatbot does not use jQuery).
+ // Version follows the file's mtime so browsers never serve a stale copy
+ // after an edit; 'defer' keeps it from blocking page rendering.
+ $file_path = WPSC_ABSPATH . 'asset/js/ai-chatbot/chatbot.js';
+ $version = file_exists( $file_path ) ? (string) filemtime( $file_path ) : WPSC_VERSION;
+ $handle = 'wpsc-acb-chatbot';
+
+ wp_enqueue_script(
+ $handle,
+ WPSC_PLUGIN_URL . 'asset/js/ai-chatbot/chatbot.js',
+ array(),
+ $version,
+ array(
+ 'in_footer' => true,
+ 'strategy' => 'defer',
+ )
+ );
+ wp_add_inline_script( $handle, $config_js, 'before' );
+ wp_localize_script( $handle, 'wpsc_ai_chatbot', $ajax_data );
}
/**
@@ -279,6 +314,10 @@
* @return void
*/
public static function shadow_css() {
+
+ if ( ! self::is_visible_on_current_page() ) {
+ return;
+ }
?>
<style id="wpsc-chatbot-shadow-css">
/* Add your dynamic CSS here. */
@@ -292,8 +331,14 @@
* @return void
*/
public static function render_chatbot_root() {
+
+ if ( ! self::is_visible_on_current_page() ) {
+ return;
+ }
+ $acb_settings = get_option( 'wpsc-ps-acb-chatbot-settings', array() );
+ $position = isset( $acb_settings['widget-position'] ) && 'left' === $acb_settings['widget-position'] ? 'left' : 'right';
?>
- <div id="wpsc-chatbot-root"></div>
+ <div id="wpsc-chatbot-root" data-position="<?php echo esc_attr( $position ); ?>" dir="<?php echo is_rtl() ? 'rtl' : 'ltr'; ?>"></div>
<?php
}
}
--- a/supportcandy/includes/admin/ai-chatbot/includes/index.php
+++ b/supportcandy/includes/admin/ai-chatbot/includes/index.php
@@ -1,6 +1,9 @@
<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly!
+}
// Load settings.
-foreach ( glob( __DIR__ . '/settings/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/settings/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
--- a/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-appearance-setting.php
+++ b/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-appearance-setting.php
@@ -77,6 +77,7 @@
private static function register_string( $name, $value ) {
if ( has_action( 'wpml_register_single_string' ) ) {
+ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Hook belongs to WPML's public API and is invoked on purpose; its name is fixed by WPML.
do_action( 'wpml_register_single_string', self::WPML_CONTEXT, $name, $value );
}
}
@@ -94,6 +95,7 @@
public static function translate( $name, $value ) {
if ( has_filter( 'wpml_translate_single_string' ) ) {
+ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Hook belongs to WPML's public API and is invoked on purpose; its name is fixed by WPML.
return apply_filters( 'wpml_translate_single_string', $value, self::WPML_CONTEXT, $name );
}
--- a/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-general-setting.php
+++ b/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-general-setting.php
@@ -58,6 +58,22 @@
if ( ! isset( $acb_settings['custom-prompt'] ) ) {
$acb_settings['custom-prompt'] = '';
}
+
+ $widget_position = isset( $acb_settings['widget-position'] ) && 'left' === $acb_settings['widget-position'] ? 'left' : 'right';
+ $visibility_mode = isset( $acb_settings['visibility-mode'] ) ? $acb_settings['visibility-mode'] : 'all';
+ $visibility_pages = isset( $acb_settings['visibility-pages'] ) ? (array) $acb_settings['visibility-pages'] : array();
+ $visibility_types = isset( $acb_settings['visibility-types'] ) ? (array) $acb_settings['visibility-types'] : array();
+
+ // Pages that no longer exist are left out, so saving the form drops them.
+ $visibility_pages = array_values(
+ array_filter(
+ array_map( 'absint', $visibility_pages ),
+ function ( $page_id ) {
+ return 'page' === get_post_type( $page_id );
+ }
+ )
+ );
+ $content_types = self::get_content_types();
?>
<form action="#" onsubmit="return false;" class="wpsc-frm-acb-settings">
@@ -96,6 +112,60 @@
</div>
</div>
+ <div class="wpsc-setting-group wpsc-acb-status-dependent" <?php echo '0' === (string) $acb_settings['status'] ? 'style="display:none;"' : ''; ?>>
+ <h3 class="wpsc-setting-group-title"><?php echo esc_html__( 'Display', 'supportcandy' ); ?></h3>
+ <div class="wpsc-setting-group-body">
+ <div class="wpsc-input-group">
+ <div class="label-container">
+ <label for="wpsc-acb-widget-position"><?php esc_attr_e( 'Widget position', 'supportcandy' ); ?></label>
+ </div>
+ <p class="wpsc-input-desc"><?php esc_attr_e( 'Side of the screen where the chat launcher and chat window appear.', 'supportcandy' ); ?></p>
+ <select id="wpsc-acb-widget-position" name="widget-position" style="max-width: 250px;">
+ <option <?php selected( $widget_position, 'right' ); ?> value="right"><?php esc_attr_e( 'Right', 'supportcandy' ); ?></option>
+ <option <?php selected( $widget_position, 'left' ); ?> value="left"><?php esc_attr_e( 'Left', 'supportcandy' ); ?></option>
+ </select>
+ </div>
+ <div class="wpsc-input-group">
+ <div class="label-container">
+ <label for="wpsc-acb-visibility-mode"><?php esc_attr_e( 'Chat widget visibility', 'supportcandy' ); ?></label>
+ </div>
+ <p class="wpsc-input-desc"><?php esc_attr_e( 'Choose on which front-end pages the chat widget is shown.', 'supportcandy' ); ?></p>
+ <select id="wpsc-acb-visibility-mode" name="visibility-mode" style="max-width: 250px;">
+ <option <?php selected( $visibility_mode, 'all' ); ?> value="all"><?php esc_attr_e( 'Show on all pages', 'supportcandy' ); ?></option>
+ <option <?php selected( $visibility_mode, 'include' ); ?> value="include"><?php esc_attr_e( 'Show only on selected', 'supportcandy' ); ?></option>
+ <option <?php selected( $visibility_mode, 'exclude' ); ?> value="exclude"><?php esc_attr_e( 'Hide on selected', 'supportcandy' ); ?></option>
+ </select>
+ </div>
+ <div class="wpsc-input-group wpsc-acb-visibility-dependent" <?php echo 'all' === $visibility_mode ? 'style="display:none;"' : ''; ?>>
+ <div class="label-container">
+ <label for="wpsc-acb-visibility-pages"><?php esc_attr_e( 'Pages', 'supportcandy' ); ?></label>
+ </div>
+ <p class="wpsc-input-desc"><?php esc_attr_e( 'Pages the selected mode applies to, such as the home, shop, contact or checkout page.', 'supportcandy' ); ?></p>
+ <select id="wpsc-acb-visibility-pages" class="wpsc-acb-select-wp-page" name="visibility-pages[]" data-nonce="<?php echo esc_attr( wp_create_nonce( 'wpsc_search_wp_pages' ) ); ?>" multiple>
+ <?php
+ foreach ( $visibility_pages as $page_id ) {
+ ?>
+ <option selected value="<?php echo esc_attr( $page_id ); ?>"><?php echo esc_attr( get_the_title( $page_id ) ); ?></option>
+ <?php
+ }
+ ?>
+ </select>
+ </div>
+ <div class="wpsc-input-group wpsc-acb-visibility-dependent" <?php echo 'all' === $visibility_mode ? 'style="display:none;"' : ''; ?>>
+ <div class="label-container">
+ <label for="wpsc-acb-visibility-types"><?php esc_attr_e( 'Content types', 'supportcandy' ); ?></label>
+ </div>
+ <p class="wpsc-input-desc"><?php esc_attr_e( 'Content that is not a page, such as posts, products, courses or downloads. Selecting a type applies the mode to every item of that type.', 'supportcandy' ); ?></p>
+ <select id="wpsc-acb-visibility-types" class="wpsc-acb-select-content-type" name="visibility-types[]" multiple>
+ <?php foreach ( $content_types as $slug => $label ) : ?>
+ <option <?php selected( in_array( $slug, $visibility_types, true ) ); ?> value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $label ); ?></option>
+ <?php endforeach; ?>
+ </select>
+ </div>
+ <p class="wpsc-acb-visibility-error" role="alert" style="display:none; color:#d63638; margin:0;"><?php echo esc_html__( 'Select at least one page or content type, or choose "Show on all pages".', 'supportcandy' ); ?></p>
+ </div>
+ </div>
+
<div class="wpsc-setting-group">
<h3 class="wpsc-setting-group-title"><?php echo esc_html__( 'Greeting Bubble', 'supportcandy' ); ?></h3>
<div class="wpsc-setting-group-body">
@@ -181,6 +251,26 @@
}
/**
+ * Content types selectable in the chat widget visibility setting: every public post type except pages (those
+ * are picked by name) and attachments, plus archive pages.
+ *
+ * @return array Label by slug.
+ */
+ private static function get_content_types() {
+
+ $content_types = array();
+ foreach ( get_post_types( array( 'public' => true ), 'objects' ) as $post_type ) {
+ if ( 'page' === $post_type->name || 'attachment' === $post_type->name ) {
+ continue;
+ }
+ $content_types[ $post_type->name ] = $post_type->labels->name;
+ }
+ $content_types['__archive'] = __( 'Archive, search & 404 pages', 'supportcandy' );
+
+ return $content_types;
+ }
+
+ /**
* Save AI assistant settings
*
* @return void
@@ -239,7 +329,47 @@
$custom_prompt = isset( $_POST['custom-prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['custom-prompt'] ) ) : '';
+ $visibility_mode = isset( $_POST['visibility-mode'] ) ? sanitize_text_field( wp_unslash( $_POST['visibility-mode'] ) ) : 'all';
+ if ( ! in_array( $visibility_mode, array( 'all', 'include', 'exclude' ), true ) ) {
+ wp_send_json_error( __( 'Invalid chat widget visibility option!', 'supportcandy' ), 400 );
+ }
+
+ $visibility_pages = isset( $_POST['visibility-pages'] ) ? array_values( array_unique( array_filter( array_map( 'absint', wp_unslash( (array) $_POST['visibility-pages'] ) ) ) ) ) : array();
+ foreach ( $visibility_pages as $page_id ) {
+ if ( 'page' !== get_post_type( $page_id ) ) {
+ wp_send_json_error( __( 'Invalid page selected for chat widget visibility!', 'supportcandy' ), 400 );
+ }
+ }
+
+ $visibility_types = isset( $_POST['visibility-types'] ) ? array_values( array_unique( array_filter( array_map( 'sanitize_key', wp_unslash( (array) $_POST['visibility-types'] ) ) ) ) ) : array();
+ $content_types = self::get_content_types();
+ foreach ( $visibility_types as $type ) {
+ if ( ! isset( $content_types[ $type ] ) ) {
+ wp_send_json_error( __( 'Invalid content type selected for chat widget visibility!', 'supportcandy' ), 400 );
+ }
+ }
+
+ // "Show only on selected" with nothing selected would hide the chat widget everywhere, and "Hide on selected" would do nothing.
+ if ( 'all' !== $visibility_mode && empty( $visibility_pages ) && empty( $visibility_types ) ) {
+ wp_send_json_error( __( 'Select at least one page or content type, or choose "Show on all pages".', 'supportcandy' ), 400 );
+ }
+
+ // Nothing to apply the mode to when showing everywhere.
+ if ( 'all' === $visibility_mode ) {
+ $visibility_pages = array();
+ $visibility_types = array();
+ }
+
+ $widget_position = isset( $_POST['widget-position'] ) ? sanitize_text_field( wp_unslash( $_POST['widget-position'] ) ) : 'right';
+ if ( ! in_array( $widget_position, array( 'right', 'left' ), true ) ) {
+ wp_send_json_error( __( 'Invalid widget position!', 'supportcandy' ), 400 );
+ }
+
$acb_settings = array(
+ 'widget-position' => $widget_position,
+ 'visibility-mode' => $visibility_mode,
+ 'visibility-pages' => $visibility_pages,
+ 'visibility-types' => $visibility_types,
'status' => $status,
'delete-acb-session-time' => $retention_policy_time,
'delete-acb-session-unit' => $retention_policy_unit,
@@ -278,6 +408,10 @@
update_option(
'wpsc-ps-acb-chatbot-settings',
array(
+ 'widget-position' => 'right',
+ 'visibility-mode' => 'all',
+ 'visibility-pages' => array(),
+ 'visibility-types' => array(),
'status' => '0',
'delete-acb-session-time' => 1,
'delete-acb-session-unit' => 'year',
--- a/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-submenu.php
+++ b/supportcandy/includes/admin/ai-chatbot/includes/settings/class-wpsc-acb-submenu.php
@@ -490,14 +490,14 @@
<div class="wpsc-acb-toolbar-item">
<label><?php esc_attr_e( 'Duration', 'supportcandy' ); ?></label>
<select id="wpsc-message-duration-filter">
- <option value="today"><?php esc_attr_e( 'Today', 'wpsc-reports' ); ?></option>
- <option value="yesterday"><?php esc_attr_e( 'Yesterday', 'wpsc-reports' ); ?></option>
- <option value="this-week"><?php esc_attr_e( 'This Week', 'wpsc-reports' ); ?></option>
- <option value="last-week"><?php esc_attr_e( 'Last Week', 'wpsc-reports' ); ?></option>
- <option value="last-30-days" selected="selected"><?php esc_attr_e( 'Last 30 Days', 'wpsc-reports' ); ?></option>
- <option value="this-month"><?php esc_attr_e( 'This Month', 'wpsc-reports' ); ?></option>
- <option value="last-month"><?php esc_attr_e( 'Last Month', 'wpsc-reports' ); ?></option>
- <option value="custom"><?php esc_attr_e( 'Custom', 'wpsc-reports' ); ?></option>
+ <option value="today"><?php esc_attr_e( 'Today', 'supportcandy' ); ?></option>
+ <option value="yesterday"><?php esc_attr_e( 'Yesterday', 'supportcandy' ); ?></option>
+ <option value="this-week"><?php esc_attr_e( 'This Week', 'supportcandy' ); ?></option>
+ <option value="last-week"><?php esc_attr_e( 'Last Week', 'supportcandy' ); ?></option>
+ <option value="last-30-days" selected="selected"><?php esc_attr_e( 'Last 30 Days', 'supportcandy' ); ?></option>
+ <option value="this-month"><?php esc_attr_e( 'This Month', 'supportcandy' ); ?></option>
+ <option value="last-month"><?php esc_attr_e( 'Last Month', 'supportcandy' ); ?></option>
+ <option value="custom"><?php esc_attr_e( 'Custom', 'supportcandy' ); ?></option>
</select>
</div>
@@ -576,6 +576,10 @@
</div>
</div>
<script>
+ if (typeof wpsc_acb_fit_split === 'function') {
+ wpsc_acb_fit_split();
+ }
+
function normalizeDateStringForFilter(inputValue) {
if (!inputValue) {
return '';
--- a/supportcandy/includes/admin/ai-chatbot/index.php
+++ b/supportcandy/includes/admin/ai-chatbot/index.php
@@ -1,44 +1,48 @@
<?php
-$acb_settings = get_option( 'wpsc-ps-acb-chatbot-settings', array() );
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly!
+}
+
+$wpsc_acb_settings = get_option( 'wpsc-ps-acb-chatbot-settings', array() );
// Load includes (settings, admin & cron hooks) so the settings UI stays reachable regardless of status.
-foreach ( glob( __DIR__ . '/includes/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/includes/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load models and the reaction / status values regardless of status too: they only read and describe
// stored chat sessions (no chatbot behaviour), and the AI ChatBot reports need them to show past
// sessions after the chatbot has been turned off.
-foreach ( glob( __DIR__ . '/models/*.php' ) as $filename ) {
- include_once $filename;
+foreach ( glob( __DIR__ . '/models/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
require_once __DIR__ . '/controller/class-wpsc-acb-reaction.php';
require_once __DIR__ . '/controller/class-wpsc-acb-status.php';
// Load the rest of the chatbot's functionality only when it's enabled.
-if ( ! empty( $acb_settings['status'] ) && '1' === $acb_settings['status'] ) {
+if ( ! empty( $wpsc_acb_settings['status'] ) && '1' === $wpsc_acb_settings['status'] ) {
// Load controller.
- foreach ( glob( __DIR__ . '/controller/*.php' ) as $filename ) {
- include_once $filename;
+ foreach ( glob( __DIR__ . '/controller/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load tools.
- foreach ( glob( __DIR__ . '/tools/*.php' ) as $filename ) {
- include_once $filename;
+ foreach ( glob( __DIR__ . '/tools/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
// Load providers.
require_once __DIR__ . '/providers/class-wpsc-aibot-provider-interface.php';
- foreach ( glob( __DIR__ . '/providers/*.php' ) as $filename ) {
- if ( $filename === __DIR__ . '/providers/class-wpsc-aibot-provider-interface.php' ) {
+ foreach ( glob( __DIR__ . '/providers/*.php' ) as $wpsc_file ) {
+ if ( $wpsc_file === __DIR__ . '/providers/class-wpsc-aibot-provider-interface.php' ) {
continue;
}
- include_once $filename;
+ include_once $wpsc_file;
}
// Load ui templates.
- foreach ( glob( __DIR__ . '/templates/*.php' ) as $filename ) {
- include_once $filename;
+ foreach ( glob( __DIR__ . '/templates/*.php' ) as $wpsc_file ) {
+ include_once $wpsc_file;
}
}
--- a/supportcandy/includes/admin/ai-chatbot/models/class-wpsc-acb-messages.php
+++ b/supportcandy/includes/admin/ai-chatbot/models/class-wpsc-acb-messages.php
@@ -357,7 +357,7 @@
* Get where for find method
*
* @param array $filter - user filter.
- * @return array
+ * @return string
*/
private static function get_where( $filter ) {
--- a/supportcandy/includes/admin/ai-chatbot/models/class-wpsc-acb-sessions.php
+++ b/supportcandy/includes/admin/ai-chatbot/models/class-wpsc-acb-sessions.php
@@ -444,7 +444,7 @@
* Get where for find method
*
* @param array $filter - user filter.
- * @return array
+ * @return string
*/
private static function get_where( $filter ) {
$where = array( '1=1' );
--- a/supportcandy/includes/admin/ai-chatbot/models/index.php
+++ b/supportcandy/includes/admin/ai-chatbot/models/index.php
@@ -1,6 +1,9 @@
<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if acc