PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 7.3.1
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v7.3.1
8.7.8 8.7.7 8.7.6 8.7.5 8.7.4 8.7.3 8.7.2 8.7.1 8.7.0 8.6.9 8.6.8 8.6.7 8.6.6 8.6.5 8.6.4 8.6.2 8.6.1 8.6.0 8.5.9 8.5.8 8.5.7 8.5.6 8.5.5 8.5.4 8.5.3 All 534 releases
chatbot / includes / integration / openrouter / qcld-bot-openrouter.php

qcld-bot-openrouter.php in WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services 7.3.1, at includes/integration/openrouter/qcld-bot-openrouter.php

354 lines 16.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')) exit; // Exit if accessed directly
3
4 if(!class_exists('qcld_wpopenrouter_addons')){
5
6
7 /**
8 * Main Class.
9 */
10 final class qcld_wpopenrouter_addons
11 {
12 private $id = 'Open AI';
13
14 /**
15 * WPBot Pro version.
16 *
17 * @var string
18 */
19 public $version = '1.0.6';
20
21 /**
22 * WPBot Pro helper.
23 *
24 * @var object
25 */
26 public $helper;
27
28 /**
29 * The single instance of the class.
30 *
31 * @var qcld_wb_Chatbot
32 * @since 1.0.0
33 */
34 protected static $_instance = null;
35
36 /**
37 * Main wpbot Instance.
38 *
39 * Ensures only one instance of wpbot is loaded or can be loaded.
40 *
41 * @return qcld_wb_Chatbot - Main instance.
42 * @since 1.0.0
43 * @static
44 */
45 public static function instance() {
46 if ( is_null( self::$_instance ) ) {
47 self::$_instance = new self();
48 }
49
50 return self::$_instance;
51 }
52
53 public $response_list;
54
55 /**
56 * Constructor
57 */
58 public function __construct()
59 {
60
61 $this->includes();
62 add_action('wp_ajax_openai_save_assistant', [$this, 'save_assistant_callback']);
63 add_action('wp_ajax_openrouter_response',[$this,'openrouter_response_callback']);
64 add_action('wp_ajax_nopriv_openrouter_response', [$this, 'openrouter_response_callback']);
65 add_action('wp_ajax_qcld_openrouter_settings_option',[$this,'qcld_openrouter_settings_option_callback']);
66
67 add_action('wp_ajax_update_settings_option', [$this, 'qcld_update_settings_option_callback']);
68
69 if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) {
70 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts'));
71 }
72 //add_action('wp_enqueue_scripts', array($this, 'qcld_wb_chatbot_openrouter_scripts'));
73 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_openrouter_admin_scripts'));
74 }
75
76
77
78 public function qcld_wb_chatbot_openrouter_admin_scripts() {
79 if ( ! current_user_can( 'manage_options' ) ) {
80 return ;
81 }
82 wp_register_script(
83 'qcld-wp-chatbot-openrouter-admin-js',
84 QCLD_wpCHATBOT_PLUGIN_URL . 'includes/integration/openrouter/assets/js/qcld-wp-openrouter-admin.js',
85 array('jquery'),
86 QCLD_wpCHATBOT_VERSION,
87 true
88 );
89
90 // Localize the script with necessary data
91 wp_localize_script('qcld-wp-chatbot-openrouter-admin-js', 'qcld_gemini_admin_data', array(
92 'ajax_url' => admin_url('admin-ajax.php'),
93 'ajax_nonce' => wp_create_nonce('wp_chatbot'),
94 'openrouter_api_key' => get_option('qcld_openrouter_api_key'),
95 'openrouter_model' => get_option('qcld_openrouter_model'),
96 'openrouter_enabled' => get_option('qcld_openrouter_enabled'),
97 'qcld_openrouter_append_content' => get_option('qcld_openrouter_append_content'),
98 'qcld_openrouter_prepend_content' => get_option('qcld_openrouter_prepend_content')
99 ));
100
101 wp_enqueue_script('qcld-wp-chatbot-openrouter-admin-js');
102 }
103
104 /**
105 * Define wpbot Constants.
106 *
107 * @return void
108 * @since 1.0.0
109 */
110 public function includes() {
111 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/Parsedown.php" );
112 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/class-common-function.php" );
113 }
114 public function qcld_openrouter_settings_option_callback() {
115 $nonce = sanitize_text_field($_POST['nonce']);
116 if (!wp_verify_nonce($nonce, 'wp_chatbot')) {
117 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
118 wp_die();
119 } else {
120 $openrouter_api_key = sanitize_text_field($_POST['openrouter_api_key']);
121 $openrouter_model = sanitize_text_field($_POST['openrouter_model']);
122 $openrouter_enabled = sanitize_text_field($_POST['openrouter_enabled']);
123 $qcld_openrouter_page_suggestion_enabled = sanitize_text_field($_POST['qcld_openrouter_page_suggestion_enabled']);
124 $opnrouter_is_context_awareness_enabled = sanitize_text_field($_POST['opnrouter_is_context_awareness_enabled']);
125 $qcld_openrouter_append_content = sanitize_text_field($_POST['qcld_openrouter_append_content']) ?? '';
126 $qcld_openrouter_prepend_content = sanitize_text_field($_POST['qcld_openrouter_prepend_content']) ?? '';
127 if($openrouter_api_key != '') {
128 update_option('qcld_openrouter_api_key', $openrouter_api_key);
129 }
130 if($openrouter_model != '') {
131 update_option('qcld_openrouter_model', $openrouter_model);
132 }
133 if($openrouter_enabled != '') {
134 update_option('qcld_openrouter_enabled', $openrouter_enabled);
135 }
136 if($openrouter_enabled == '1') {
137 update_option('ai_enabled', 0);
138 update_option('qcld_gemini_enabled', 0);
139
140 } else {
141 update_option('ai_enabled', 1);
142 update_option('qcld_gemini_enabled', 0);
143 }
144 update_option('qcld_openrouter_page_suggestion_enabled', $qcld_openrouter_page_suggestion_enabled);
145 update_option('opnrouter_context_awareness_enabled', $opnrouter_is_context_awareness_enabled);
146 $openai_post_types = array();
147 if (isset($_POST['openai_post_type'])) {
148 $raw_post_types = wp_unslash($_POST['openai_post_type']);
149 if (is_array($raw_post_types)) {
150 $openai_post_types = array_map('sanitize_text_field', $raw_post_types);
151 } else {
152 $openai_post_types = sanitize_text_field($raw_post_types);
153 }
154 }
155 update_option('qcld_openai_relevant_post', $openai_post_types);
156
157 update_option('qcld_openrouter_append_content', $qcld_openrouter_append_content);
158 update_option('qcld_openrouter_prepend_content', $qcld_openrouter_prepend_content);
159
160 }
161 echo wp_json_encode($openrouter_enabled);
162 wp_die();
163 }
164 public function openrouter_response_callback(){
165 $openrouter_model = get_option('qcld_openrouter_model');
166 $openrouter_api_key = get_option('qcld_openrouter_api_key');
167 $keyword = $_POST['keyword'];
168 $relevant_pagelink = Qcld_WPBot_Common_Functions::qcpd_relevant_pagelink($keyword);
169 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
170
171 // Build context-aware messages with system instructions
172 $messages = array();
173
174 // Add system message with context if enabled
175 if ( get_option('opnrouter_context_awareness_enabled') == '1' ) {
176 $site_name = get_bloginfo('name');
177 $site_desc = get_bloginfo('description');
178
179 // Get current page URL and title more reliably
180 $current_url = '';
181 $page_title = '';
182 $page_summary = '';
183
184 // Try to get from referrer first
185 $ref = wp_get_referer();
186 if ( ! $ref && isset($_SERVER['HTTP_REFERER']) ) {
187 $ref = esc_url_raw( $_SERVER['HTTP_REFERER'] );
188 }
189
190 if ( $ref ) {
191 $current_url = $ref;
192
193 // Try to get post/page by URL
194 $post_id = url_to_postid( $ref );
195 if ( $post_id ) {
196 $page_title = get_the_title( $post_id );
197 $raw_content = get_post_field( 'post_content', $post_id );
198 $text_content = wp_strip_all_tags( $raw_content );
199 $page_summary = wp_trim_words( $text_content, 120, '' );
200 } else {
201 // If not a post/page, try to extract title from URL or use current page
202 $parsed_url = parse_url( $ref );
203 if ( isset($parsed_url['path']) ) {
204 $path = trim($parsed_url['path'], '/');
205 if ( ! empty($path) ) {
206 // Try to get title from current page if we're on it
207 if ( is_singular() ) {
208 $page_title = get_the_title();
209 $raw_content = get_the_content();
210 $text_content = wp_strip_all_tags( $raw_content );
211 $page_summary = wp_trim_words( $text_content, 120, '' );
212 } elseif ( is_archive() ) {
213 $page_title = get_the_archive_title();
214 } elseif ( is_search() ) {
215 $page_title = 'Search Results';
216 } elseif ( is_404() ) {
217 $page_title = 'Page Not Found';
218 }
219 }
220 }
221 }
222 } else {
223 // Fallback to current page info
224 $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
225 $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field($_SERVER['HTTP_HOST']) : '';
226 $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
227 $current_url = esc_url_raw($scheme . '://' . $host . $request_uri);
228
229 if ( is_singular() ) {
230 $page_title = get_the_title();
231 $raw_content = get_the_content();
232 $text_content = wp_strip_all_tags( $raw_content );
233 $page_summary = wp_trim_words( $text_content, 120, '' );
234 } elseif ( is_archive() ) {
235 $page_title = get_the_archive_title();
236 } elseif ( is_search() ) {
237 $page_title = 'Search Results';
238 } elseif ( is_404() ) {
239 $page_title = 'Page Not Found';
240 }
241 }
242
243 $context_bits = array();
244 if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; }
245 if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; }
246 if ( $page_title ) { $context_bits[] = 'Page title: ' . $page_title; }
247 if ( $current_url ) { $context_bits[] = 'URL: ' . $current_url; }
248 if ( $page_summary ) { $context_bits[] = 'Page summary: ' . $page_summary; }
249
250 if ( ! empty( $context_bits ) ) {
251 $context_info = 'Context Information: ' . implode( '. ', $context_bits ) . '. Please use this context to provide more relevant and accurate responses.';
252
253 // Add system message with context
254 $messages[] = array(
255 'role' => 'system',
256 'content' => $context_info
257 );
258 }
259 }
260
261 // Add user message
262 $messages[] = array(
263 'role' => 'user',
264 'content' => $keyword
265 );
266
267 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
268
269 $relevant_post_link = maybe_unserialize(get_option('qlcd_wp_chatbot_relevant_post_link_openai'));
270
271 // Avoid call to undefined function get_wpbot_locale()
272 $locale = ( function_exists('get_locale') ) ? get_locale() : 'en_US';
273 if ( isset($relevant_post_link[$locale]) && is_array($relevant_post_link[$locale]) ) {
274 $relevant_pagelinks = '<br><br><p><em>' . implode('', $relevant_post_link[$locale]) . '</em><p>' . implode("</br>", $relevant_pagelink);
275 } elseif ( isset($relevant_post_link[$locale]) ) {
276 $relevant_pagelinks = '<br><br><p><em>' . $relevant_post_link[$locale] . '</em><p>' . implode("</br>", $relevant_pagelink);
277 } else {
278 $relevant_pagelinks = '<br><br><p><em></em><p>' . implode("</br>", $relevant_pagelink);
279 }
280
281
282 }else{
283 $relevant_pagelinks = '';
284 }
285 $Qcld_Parsedown = new Qcld_Parsedown();
286 $data = json_encode(array(
287 'model' => $openrouter_model,
288 'messages' => $messages
289 ));
290
291 $api_url = 'https://openrouter.ai/api/v1/chat/completions';
292
293 // Use WordPress wp_remote_post for better error handling and consistency
294 $args = array(
295 'body' => $data,
296 'headers' => array(
297 'Content-Type' => 'application/json',
298 'Authorization' => 'Bearer ' . $openrouter_api_key
299 ),
300 'timeout' => 60,
301 'redirection' => 5,
302 'blocking' => true,
303 'httpversion' => '1.0',
304 'sslverify' => true,
305 );
306
307 $result = wp_remote_post($api_url, $args);
308
309 // Check for WordPress errors
310 if (is_wp_error($result)) {
311 $response['status'] = 'error';
312 $response['message'] = 'API request failed: ' . $result->get_error_message();
313 } else {
314 $http_code = wp_remote_retrieve_response_code($result);
315 $response_body = wp_remote_retrieve_body($result);
316
317 if ($http_code === 200) {
318 $msg = json_decode($response_body);
319 if(isset($msg->choices[0]->message->content)) {
320 $response['status'] = 'success';
321 $response['message'] = $Qcld_Parsedown->text($msg->choices[0]->message->content) . $relevant_pagelinks;
322 } else {
323 $response['status'] = 'error';
324 $response['message'] = 'Sorry, I encountered an error processing your AI request. Please check api key and try again later.';
325 }
326 } else {
327 $response['status'] = 'error';
328 $response['message'] = 'API request failed with HTTP code: ' . $http_code;
329 }
330 }
331 echo wp_json_encode($response);
332 wp_die();
333 }
334 public function qcld_update_settings_option_callback(){
335 update_option('disable_wp_chatbot_site_search',1);
336 update_option('enable_wp_chatbot_post_content', '');
337 }
338 }
339
340 /**
341 * @return qcld_wpopenai_addon
342 */
343 if(!function_exists('qcld_wpopenrouter_addons')){
344 function qcld_wpopenrouter_addons() {
345 $qcld_wpopenrouter_addon = new qcld_wpopenrouter_addons();
346 return $qcld_wpopenrouter_addon->instance();
347
348 }
349 }
350
351 //fire off the plugin
352 qcld_wpopenrouter_addons();
353
354 }