PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 7.1.2
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v7.1.2
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.1.2, at includes/integration/openrouter/qcld-bot-openrouter.php

342 lines 15.3 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, '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', 'ajax_object', 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', 'sm')));
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 update_option( 'qcld_openai_relevant_post', $_POST['openai_post_type'] );
147
148 update_option('qcld_openrouter_append_content', $qcld_openrouter_append_content);
149 update_option('qcld_openrouter_prepend_content', $qcld_openrouter_prepend_content);
150
151 }
152 echo json_encode($openrouter_enabled);
153 wp_die();
154 }
155 public function openrouter_response_callback(){
156 $openrouter_model = get_option('qcld_openrouter_model');
157 $openrouter_api_key = get_option('qcld_openrouter_api_key');
158 $keyword = $_POST['keyword'];
159 $relevant_pagelink = Qcld_WPBot_Common_Functions::qcpd_relevant_pagelink($keyword);
160 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
161
162 // Build context-aware messages with system instructions
163 $messages = array();
164
165 // Add system message with context if enabled
166 if ( get_option('opnrouter_context_awareness_enabled') == '1' ) {
167 $site_name = get_bloginfo('name');
168 $site_desc = get_bloginfo('description');
169
170 // Get current page URL and title more reliably
171 $current_url = '';
172 $page_title = '';
173 $page_summary = '';
174
175 // Try to get from referrer first
176 $ref = wp_get_referer();
177 if ( ! $ref && isset($_SERVER['HTTP_REFERER']) ) {
178 $ref = esc_url_raw( $_SERVER['HTTP_REFERER'] );
179 }
180
181 if ( $ref ) {
182 $current_url = $ref;
183
184 // Try to get post/page by URL
185 $post_id = url_to_postid( $ref );
186 if ( $post_id ) {
187 $page_title = get_the_title( $post_id );
188 $raw_content = get_post_field( 'post_content', $post_id );
189 $text_content = wp_strip_all_tags( $raw_content );
190 $page_summary = wp_trim_words( $text_content, 120, '' );
191 } else {
192 // If not a post/page, try to extract title from URL or use current page
193 $parsed_url = parse_url( $ref );
194 if ( isset($parsed_url['path']) ) {
195 $path = trim($parsed_url['path'], '/');
196 if ( ! empty($path) ) {
197 // Try to get title from current page if we're on it
198 if ( is_singular() ) {
199 $page_title = get_the_title();
200 $raw_content = get_the_content();
201 $text_content = wp_strip_all_tags( $raw_content );
202 $page_summary = wp_trim_words( $text_content, 120, '' );
203 } elseif ( is_archive() ) {
204 $page_title = get_the_archive_title();
205 } elseif ( is_search() ) {
206 $page_title = 'Search Results';
207 } elseif ( is_404() ) {
208 $page_title = 'Page Not Found';
209 }
210 }
211 }
212 }
213 } else {
214 // Fallback to current page info
215 $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
216
217 if ( is_singular() ) {
218 $page_title = get_the_title();
219 $raw_content = get_the_content();
220 $text_content = wp_strip_all_tags( $raw_content );
221 $page_summary = wp_trim_words( $text_content, 120, '' );
222 } elseif ( is_archive() ) {
223 $page_title = get_the_archive_title();
224 } elseif ( is_search() ) {
225 $page_title = 'Search Results';
226 } elseif ( is_404() ) {
227 $page_title = 'Page Not Found';
228 }
229 }
230
231 $context_bits = array();
232 if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; }
233 if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; }
234 if ( $page_title ) { $context_bits[] = 'Page title: ' . $page_title; }
235 if ( $current_url ) { $context_bits[] = 'URL: ' . $current_url; }
236 if ( $page_summary ) { $context_bits[] = 'Page summary: ' . $page_summary; }
237
238 if ( ! empty( $context_bits ) ) {
239 $context_info = 'Context Information: ' . implode( '. ', $context_bits ) . '. Please use this context to provide more relevant and accurate responses.';
240
241 // Add system message with context
242 $messages[] = array(
243 'role' => 'system',
244 'content' => $context_info
245 );
246 }
247 }
248
249 // Add user message
250 $messages[] = array(
251 'role' => 'user',
252 'content' => $keyword
253 );
254
255 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
256
257 $relevant_post_link = maybe_unserialize(get_option('qlcd_wp_chatbot_relevant_post_link_openai'));
258
259 // Avoid call to undefined function get_wpbot_locale()
260 $locale = ( function_exists('get_locale') ) ? get_locale() : 'en_US';
261 if ( isset($relevant_post_link[$locale]) && is_array($relevant_post_link[$locale]) ) {
262 $relevant_pagelinks = '<br><br><p><em>' . implode('', $relevant_post_link[$locale]) . '</em><p>' . implode("</br>", $relevant_pagelink);
263 } elseif ( isset($relevant_post_link[$locale]) ) {
264 $relevant_pagelinks = '<br><br><p><em>' . $relevant_post_link[$locale] . '</em><p>' . implode("</br>", $relevant_pagelink);
265 } else {
266 $relevant_pagelinks = '<br><br><p><em></em><p>' . implode("</br>", $relevant_pagelink);
267 }
268
269
270 }else{
271 $relevant_pagelinks = '';
272 }
273 $Parsedown = new Parsedown();
274 $data = json_encode(array(
275 'model' => $openrouter_model,
276 'messages' => $messages
277 ));
278
279 $api_url = 'https://openrouter.ai/api/v1/chat/completions';
280
281 // Use WordPress wp_remote_post for better error handling and consistency
282 $args = array(
283 'body' => $data,
284 'headers' => array(
285 'Content-Type' => 'application/json',
286 'Authorization' => 'Bearer ' . $openrouter_api_key
287 ),
288 'timeout' => 60,
289 'redirection' => 5,
290 'blocking' => true,
291 'httpversion' => '1.0',
292 'sslverify' => true,
293 );
294
295 $result = wp_remote_post($api_url, $args);
296
297 // Check for WordPress errors
298 if (is_wp_error($result)) {
299 $response['status'] = 'error';
300 $response['message'] = 'API request failed: ' . $result->get_error_message();
301 } else {
302 $http_code = wp_remote_retrieve_response_code($result);
303 $response_body = wp_remote_retrieve_body($result);
304
305 if ($http_code === 200) {
306 $msg = json_decode($response_body);
307 if(isset($msg->choices[0]->message->content)) {
308 $response['status'] = 'success';
309 $response['message'] = $Parsedown->text($msg->choices[0]->message->content) . $relevant_pagelinks;
310 } else {
311 $response['status'] = 'error';
312 $response['message'] = 'Sorry, I encountered an error processing your AI request. Please check api key and try again later.';
313 }
314 } else {
315 $response['status'] = 'error';
316 $response['message'] = 'API request failed with HTTP code: ' . $http_code;
317 }
318 }
319 echo json_encode($response);
320 wp_die();
321 }
322 public function update_settings_option_callback(){
323 update_option('disable_wp_chatbot_site_search',1);
324 update_option('enable_wp_chatbot_post_content', '');
325 }
326 }
327
328 /**
329 * @return qcld_wpopenai_addon
330 */
331 if(!function_exists('qcld_wpopenrouter_addons')){
332 function qcld_wpopenrouter_addons() {
333 $qcld_wpopenrouter_addon = new qcld_wpopenrouter_addons();
334 return $qcld_wpopenrouter_addon->instance();
335
336 }
337 }
338
339 //fire off the plugin
340 qcld_wpopenrouter_addons();
341
342 }