core = $mwai_core; if ( is_admin() ) { return; } add_shortcode( 'mwai_chat', array( $this, 'chat' ) ); add_shortcode( 'mwai_chatbot', array( $this, 'chat' ) ); add_shortcode( 'mwai_imagesbot', array( $this, 'imageschat' ) ); add_action( 'rest_api_init', array( $this, 'rest_api_init' ) ); if ( $this->core->get_option( 'shortcode_chat_inject' ) ) { //add_action( 'wp_body_open', array( $this, 'inject_chat' ) ); add_action( 'wp_footer', array( $this, 'inject_chat' ) ); } // Only for test now, but later we should probably import the JS/CSS if ( $this->core->get_option( 'shortcode_chat_syntax_highlighting' ) ) { wp_enqueue_script( 'mwai_chatbot', '//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js', [], null, false ); wp_enqueue_style( 'mwai_chatbot', '//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/stackoverflow-dark.min.css' ); } $logs = $this->core->get_option( 'shortcode_chat_logs' ); if ( $logs && strpos( $logs, 'file' ) !== false ) { new Meow_MWAI_Modules_Chatbot_Logs(); } if ( $this->core->get_option( 'shortcode_chat_styles' ) ) { add_filter( 'mwai_chatbot_style', [ $this, 'apply_chat_styles' ], 10, 2 ); } } function rest_api_init() { try { register_rest_route( $this->namespace, '/chat', array( 'methods' => 'POST', 'callback' => array( $this, 'rest_chat' ), 'permission_callback' => '__return_true' ) ); register_rest_route( $this->namespace, '/imagesbot', array( 'methods' => 'POST', 'callback' => array( $this, 'rest_imagesbot' ), 'permission_callback' => '__return_true' ) ); } catch ( Exception $e ) { var_dump( $e ); } } function chatgpt_style( $id ) { $css = file_get_contents( MWAI_PATH . '/classes/modules/chatbot-chatgpt.css' ); $css = str_replace( '#mwai-chat-id', "#mwai-chat-{$id}", $css ); return ""; } function rest_chat( $request ) { try { $params = $request->get_json_params(); $query = new Meow_MWAI_QueryText( $params['prompt'], 1024 ); $query->injectParams( $params ); $answer = $this->core->ai->run( $query ); $rawText = $answer->result; $html = apply_filters( 'mwai_chatbot_reply', $rawText, $query, $params ); $html = $this->core->markdown_to_html( $html ); return new WP_REST_Response([ 'success' => true, 'answer' => $rawText, 'html' => $html, 'usage' => $answer->usage ], 200 ); } catch ( Exception $e ) { return new WP_REST_Response([ 'success' => false, 'message' => $e->getMessage() ], 500 ); } } function rest_imagesbot( $request ) { try { $params = $request->get_json_params(); $query = new Meow_MWAI_QueryImage( $params['prompt'] ); $query->injectParams( $params ); $answer = $this->core->ai->run( $query ); return new WP_REST_Response([ 'success' => true, 'images' => $answer->results, 'usage' => $answer->usage ], 200 ); } catch ( Exception $e ) { return new WP_REST_Response([ 'success' => false, 'message' => $e->getMessage() ], 500 ); } } function apply_chat_styles( $css, $chatbotId ) { $chatStyles = $this->core->get_option( 'shortcode_chat_styles' ); return preg_replace_callback( '/--mwai-(\w+):\s*([^;]+);/', function ( $matches ) use ($chatStyles ) { if( isset( $chatStyles[$matches[1]] ) ) { return "--mwai-" . $matches[1] . ": " . $chatStyles[$matches[1]] . ";"; } return $matches[0]; }, $css ); } function inject_chat() { $params = $this->core->get_option( 'shortcode_chat_params' ); echo $this->chat( $params ); } function imageschat( $atts ) { $atts['mode'] = 'images'; return $this->chat( $atts ); } function getCurrentUser() { if ( is_user_logged_in() ) { return wp_get_current_user(); } return null; } function handlePlaceholders( $data, $guestName = "Guest: " ) { if ( strpos( $data, '{' ) === false ) { return $data; } $placeholders_meta = [ '{FIRST_NAME}', '{LAST_NAME}' ]; $placeholders_data = [ '{USER_LOGIN}', '{DISPLAY_NAME}' ]; $user = $this->getCurrentUser(); if ( $user ) { foreach ( $placeholders_meta as $placeholder ) { if ( strpos( $data, $placeholder ) === false ) { continue; } $lcPlaceholder = substr( strtolower( $placeholder ), 1, -1 ); $value = get_user_meta( $user->ID, $lcPlaceholder, true ); $data = str_replace( $placeholder, $value, $data ); } foreach ( $placeholders_data as $placeholder ) { if ( strpos( $data, $placeholder ) === false ) { continue; } $lcPlaceholder = substr( strtolower( $placeholder ), 1, -1 ); $value = $user->data->$lcPlaceholder; $data = str_replace( $placeholder, $value, $data ); } if ( !empty( $data ) ) { return $data; } } return $guestName; } function formatUserName( $userName, $guestName = "Guest: " ) { // Default avatar if ( empty( $userName ) ) { $user = $this->getCurrentUser(); if ( $user ) { // Gravatar $userName = '
'; } else { // Default avatar $userName = '
'; } } // Custom avatar else if ( $this->core->isUrl( $userName ) ) { $userName = '
'; } // Placeholders else { $userName = $this->handlePlaceholders( $userName, $guestName ); $userName = '
' . $userName . '
'; } return $userName; } function formatAiName( $aiName ) { // Default avatar if ( empty( $aiName ) ) { $aiName = '
'; } // Custom avatar else if ( $this->core->isUrl( $aiName ) ) { $aiName = '
'; } else { $aiName = '
' . $aiName . '
'; } return $aiName; } function formatRawName( $aiName ) { return "AI: "; } function formatRawUserName( $userName, $guestName ) { return "User: "; } function chat( $atts ) { // Use the core default parameters, or the user default parameters $override = $this->core->get_option( 'shortcode_chat_params_override' ); $defaults_params = $override ? $this->core->get_option( 'shortcode_chat_params' ) : $this->core->get_option( 'shortcode_chat_default_params' ); // Give a chance to modify the default parameters one last time $defaults = apply_filters( 'mwai_chatbot_params_defaults', $defaults_params ); // Make sure all the mandatory params are set foreach ( $this->core->defaultChatbotParams as $key => $value ) { if ( !isset( $defaults[$key] ) ) { $defaults[$key] = $value; } } // Override with the shortcode, and before/after filters $atts = apply_filters( 'mwai_chatbot_params_before', $atts ); $atts = shortcode_atts( $defaults, $atts ); $atts = apply_filters( 'mwai_chatbot_params', $atts ); // UI Parameters $aiName = addslashes( trim($atts['ai_name']) ); $userName = addslashes( trim($atts['user_name']) ); $guestName = addslashes( trim($atts['guest_name']) ); $sysName = addslashes( trim($atts['sys_name']) ); $context = addslashes( $atts['context'] ); $context = preg_replace( '/\v+/', "\\n", $context ); $textSend = addslashes( trim( $atts['text_send'] ) ); $textClear = addslashes( trim( $atts['text_clear'] ) ); $textInputPlaceholder = addslashes( trim( $atts['text_input_placeholder'] ) ); $startSentence = addslashes( trim( $atts['start_sentence'] ) ); $window = filter_var( $atts['window'], FILTER_VALIDATE_BOOLEAN ); $fullscreen = filter_var( $atts['fullscreen'], FILTER_VALIDATE_BOOLEAN ); $icon = isset( $atts['icon'] ) ? addslashes( trim( $atts['icon'] ) ) : ""; $iconText = trim($atts['icon_text']); $iconPosition = addslashes( trim($atts['icon_position']) ); $style = $atts['style']; // Validade & Enhance UI Parameters $aiName = $this->formatAiName( $aiName ); $userName = $this->formatUserName( $userName, $guestName ); $rawAiName = $this->formatRawName( $aiName ); $rawUserName = $this->formatRawUserName( $userName, $guestName ); // Chatbot System Parameters $id = empty( $atts['id'] ) ? uniqid() : $atts['id']; $memorizeChat = !empty( $atts['id'] ); $id = preg_replace( '/[^a-zA-Z0-9]/', '', $id ); $env = $atts['env']; $mode = $atts['mode']; $maxResults = $mode === 'chat' ? 1 : $atts['max_results']; $maxSentences = $atts['max_sentences']; $sessionId = $this->core->get_session_id(); $rest_nonce = wp_create_nonce( 'wp_rest' ); $casuallyFineTuned = boolval( $atts['casually_fine_tuned'] ); $promptEnding = addslashes( trim( $atts['prompt_ending'] ) ); $completionEnding = addslashes( trim( $atts['completion_ending'] ) ); if ( $casuallyFineTuned ) { $promptEnding = "\\n\\n===\\n\\n"; $completionEnding = "\\n\\n"; } $debugMode = $chatStyles = $this->core->get_option( 'debug_mode' ); // OpenAI Parameters $model = $atts['model']; $temperature = $atts['temperature']; $maxTokens = $atts['max_tokens']; $apiKey = $atts['api_key']; // Named functions $onSentClickFn = "mwai_{$id}_onSendClick"; $addReplyFn = "mwai_{$id}_addReply"; $initChatBotFn = "mwai_{$id}_initChatBot"; $setButtonTextFn = "mwai_{$id}_setButtonText"; $onTidyOnGoingPromptFn = "mwai_{$id}_onUpdateOnGoingPrompt"; $injectTimerFn = "mwai_{$id}_injectTimer"; $textAreaResizeFn = "mwai_{$id}_textAreaResize"; $textAreaDelayedResizeFn = "mwai_{$id}_textAreaDelayedResize"; // Variables $apiUrl = get_rest_url( null, $mode === 'images' ? 'ai-chatbot/v1/imagesbot' : 'ai-chatbot/v1/chat' ); $onGoingPrompt = "mwai_{$id}_onGoingPrompt"; $memorizedChat = "mwai_{$id}_memorizedChat"; $baseClasses = "mwai-chat"; $baseClasses .= ( $window ? " mwai-window" : "" ); $baseClasses .= ( !$window && $fullscreen ? " mwai-fullscreen" : "" ); $baseClasses .= ( $style === 'chatgpt' ? " mwai-chatgpt" : "" ); $baseClasses .= ( $window && !empty( $iconPosition ) ? (" mwai-" . $iconPosition) : "" ); // Output CSS ob_start(); $style_content = ""; if ( $style === 'chatgpt' ) { $style_content = $this->chatgpt_style( $id, $style ); } echo apply_filters( 'mwai_chatbot_style', $style_content, $id ); // Output HTML & CSS $chatStyles = $this->core->get_option( 'shortcode_chat_styles' ); $iconUrl = MWAI_URL . '/images/chat-green.svg'; if ( !empty( $icon ) ) { $iconUrl = $icon; } else if ( !empty( $chatStyles ) && isset( $chatStyles['icon'] ) ) { $url = $chatStyles['icon']; $iconUrl = $this->core->isUrl( $url ) ? $url : (MWAI_URL . 'images/' . $chatStyles['icon']); } ?>