PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 8.2.5
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v8.2.5
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 8.5.2 All 533 releases
chatbot / includes / integration / openai / qcld-bot-openai.php

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

911 lines 41.8 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_wpopenai_addons')){
5
6
7 /**
8 * Main Class.
9 */
10 final class qcld_wpopenai_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 $this->define_constants();
61 $this->includes();
62 add_action('wp_ajax_openai_settings_option', [$this, 'openai_settings_option_callback']);
63 add_action('wp_ajax_update_settings_option', [$this, 'qcld_update_settings_option_callback']);
64 add_action('wp_ajax_qcld_rag_settings_option', array($this, 'rag_settings_option_callback'));
65 add_action('wp_ajax_qcld_openai_response',[$this,'qcld_openai_response_callback']);
66 add_action('wp_ajax_nopriv_qcld_openai_response', [$this, 'qcld_openai_response_callback']);
67 add_action('wp_ajax_openai_troubleshooting',[$this,'openai_troubleshooting']);
68 if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) {
69 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts'));
70 }
71
72 }
73
74
75 /**
76 * Define wpbot Constants.
77 *
78 * @return void
79 * @since 1.0.0
80 */
81 public function define_constants() {
82 if( ! defined( 'QCLD_openai_addon_VERSION' ) ){
83 define('QCLD_openai_addon_VERSION', $this->version);
84 }
85 //define('QCLD_openai_addon_REQUIRED_wpCOMMERCE_VERSION', 2.2);
86
87 if( ! defined( 'QCLD_openai_addon_PLUGIN_DIR_PATH' ) ){
88 define('QCLD_openai_addon_PLUGIN_DIR_PATH', plugin_dir_path(__FILE__));
89 }
90 if( ! defined( 'QCLD_openai_addon_PLUGIN_URL' ) ){
91 define('QCLD_openai_addon_PLUGIN_URL', plugin_dir_url(__FILE__));
92 }
93 if( ! defined( 'QCLD_openai_addon_IMG_URL' ) ){
94 define('QCLD_openai_addon_IMG_URL', QCLD_openai_addon_PLUGIN_URL . "images/");
95 }
96 if( ! defined( 'QCLD_openai_addon_IMG_ABSOLUTE_PATH' ) ){
97 define('QCLD_openai_addon_IMG_ABSOLUTE_PATH', plugin_dir_path(__FILE__) . "images");
98 }
99
100 }
101
102
103 public function qcld_wb_chatbot_admin_scripts(){
104 // wp_register_style('qlcd-open-ai-bootstap', QCLD_openai_addon_PLUGIN_URL . 'css/openai-bootstrap.css', '', QCLD_openai_addon_VERSION, 'screen');
105 // wp_enqueue_style('qlcd-open-ai-bootstap');
106 // wp_register_style('qlcd-open-ai-admin-style', QCLD_openai_addon_PLUGIN_URL . 'css/openai-admin-style.css', '', QCLD_openai_addon_VERSION, 'screen');
107 // wp_enqueue_style('qlcd-open-ai-admin-style');
108 // wp_register_script('qlcd-openai_collapse', QCLD_openai_addon_PLUGIN_URL . 'js/collapse.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
109 // wp_enqueue_script('qlcd-openai_collapse');
110 // wp_register_script('qlcd-openai_settings', QCLD_openai_addon_PLUGIN_URL . 'js/openai_settings.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
111 // wp_enqueue_script('qlcd-openai_settings');
112
113 // wp_localize_script( 'qlcd-openai_settings', 'openai_ajax', array(
114 // 'url' => admin_url( 'admin-ajax.php' ),
115 // ) );
116
117 }
118 /**
119 * Include all required files
120 *
121 * since 1.0.0
122 *
123 * @return void
124 */
125 public function includes() {
126 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/integration/openai/qcld_wp_OpenAI.php" );
127 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/integration/openai/OpenAi_WPBot_Menu.php" );
128 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/Parsedown.php" );
129
130 }
131
132
133 public function buildFormBody( $fields, $boundary )
134 {
135 $body = '';
136 foreach ( $fields as $name => $value ) {
137 if ( $name == 'data' ) {
138 continue;
139 }
140 $body .= "--$boundary\r\n";
141 $body .= "Content-Disposition: form-data; name=\"$name\"";
142 if ( $name == 'file' ) {
143 $body .= "; filename=\"{$value}\"\r\n";
144 $body .= "Content-Type: application/json\r\n\r\n";
145 $body .= $fields['data'] . "\r\n";
146 }else {
147 $body .= "\r\n\r\n$value\r\n";
148 }
149 }
150 $body .= "--$boundary--\r\n";
151 return $body;
152 }
153
154 // public function openai_file_list_callback(){
155 // $url = 'https://api.openai.com/v1/files';
156 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
157 // $curl = curl_init();
158 // curl_setopt($curl, CURLOPT_URL, $url);
159 // $headers = array(
160 // "Content-Type: application/json",
161 // $apt_key,
162 // );
163 // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
164 // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
165 // $response = curl_exec($curl);
166 // curl_close($curl);
167 // wp_send_json( json_decode($response));
168 // wp_die();
169 // }
170 public function qcld_sanitize_text_or_array_field($array_or_string) {
171 if( is_string($array_or_string) ){
172 $array_or_string = sanitize_text_field($array_or_string);
173 }elseif( is_array($array_or_string) ){
174 foreach ( $array_or_string as $key => &$value ) {
175 if ( is_array( $value ) ) {
176 $value = $this->qcld_sanitize_text_or_array_field($value);
177 }
178 else {
179 $value = sanitize_text_field( $value );
180 }
181 }
182 }
183
184 return $array_or_string;
185 }
186
187 // public function openai_file_upload_callback(){
188 // $uploadedfile = $_FILES['file'];
189 // $url = 'https://api.openai.com/v1/files';
190 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
191 // $curl = curl_init($url);
192 // curl_setopt($curl, CURLOPT_URL, $url);
193 // curl_setopt($curl, CURLOPT_POST, true);
194 // $headers = array(
195 // "Content-Type: multipart/form-data",
196 // $apt_key,
197 // );
198 // if (function_exists('curl_file_create')) {
199 // $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']);
200 // } else {
201 // $tmp_file = open($uploadedfile['tmp_name']);
202 // }
203 // $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune');
204 // $init = curl_init();
205 // //function parameteres
206 // curl_setopt($init, CURLOPT_URL,$url);
207 // curl_setopt($init, CURLOPT_HTTPHEADER, $headers);
208 // curl_setopt($init, CURLOPT_POSTFIELDS, $data);
209 // curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
210 // $res = json_decode(curl_exec ($init));
211
212 // curl_close ($init);
213 // if(!empty($res->error)){
214 // $response['status'] = 'error';
215 // $response['message'] = $res->error->message;
216 // }
217
218 // if(!empty($res->status)){
219 // $response['status'] = 'success';
220 // $response['message'] = 'Successfully Created file' . $res->id ;
221
222 // }
223 // echo wp_send_json([$response]);
224 // wp_die();
225 // }
226
227 public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){
228 $api_key = get_option('open_ai_api_key');
229 $request_headers = array(
230 'Content-Type' => 'application/json',
231 'Authorization' => 'Bearer ' . $api_key,
232 );
233 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
234 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
235 $base_engine = explode('-',$openai_engines);
236 if( $base_engine[0] == 'gpt'){
237 $url = "https://api.openai.com/v1/fine_tuning/jobs";
238 $response = wp_remote_post( $url, array(
239 'headers' => $request_headers,
240 'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ) ),
241 'timeout' => 60,
242 ) );
243 $result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null;
244 }else{
245 $url = "https://api.openai.com/v1/fine-tunes";
246 $response = wp_remote_post( $url, array(
247 'headers' => $request_headers,
248 'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ) ),
249 'timeout' => 60,
250 ) );
251 $result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null;
252 }
253 return $result;
254 }
255 public function relevant_pagelink($search_query){
256
257 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
258
259 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
260
261 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
262
263 $q = trim($cleanWordsWithoutPunctuationMarks);
264
265 $links = [];
266
267 $post_type_array = get_option('qcld_openai_relevant_post');
268
269 //Proceeding with traditional search
270
271 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
272
273 if( $the_query->have_posts() ){
274
275 while( $the_query->have_posts() ){
276
277 $the_query->the_post();
278
279 $url = esc_url( get_permalink() );
280
281 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
282
283 array_push($links, $link);
284
285 } //End of WHILE
286
287 wp_reset_postdata();
288
289 } //End of IF
290
291 $links = array_unique($links);
292
293 return $links;
294
295 } //End of function relevant_pagelink()
296 public function openai_retrive_fine_tune($keyword){
297 $api_key = get_option('open_ai_api_key');
298 $request_headers = array(
299 'Content-Type' => 'application/json',
300 'Authorization' => 'Bearer ' . $api_key,
301 );
302 $max_tokens = (int)get_option( 'openai_max_tokens');
303 $temp = (float)get_option( 'openai_temperature');
304 $frequency_penalty= (float)get_option( 'frequency_penalty');
305 $presence_penalty = (float)get_option( 'presence_penalty');
306 $custom_model = get_option( 'qcld_openai_custom_model');
307 $custom_model = explode(":", $custom_model);
308 $prompts = $this->get_prompt($keyword);
309
310 if ( isset( $custom_model[1] ) && $custom_model[1] !== 'gpt-3.5-turbo-0613' ) {
311 $response = wp_remote_post( 'https://api.openai.com/v1/completions', array(
312 'headers' => $request_headers,
313 'body' => wp_json_encode( array(
314 'prompt' => $prompts,
315 'model' => get_option( 'qcld_openai_custom_model'),
316 'max_tokens' => $max_tokens,
317 'temperature' => $temp,
318 'top_p' => 1,
319 'presence_penalty' => $frequency_penalty,
320 'frequency_penalty' => $presence_penalty,
321 'best_of' => 1,
322 'stop' => ["\n###\n","###"]
323 ) ),
324 'timeout' => 60,
325 ) );
326 if ( is_wp_error( $response ) ) { return ''; }
327 $result = str_replace( "#", "", wp_remote_retrieve_body( $response ) );
328 return $result;
329 } else {
330 $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array(
331 'headers' => $request_headers,
332 'body' => wp_json_encode( array(
333 'model' => get_option( 'qcld_openai_custom_model'),
334 'messages' => [ [ 'role' => 'user', 'content' => $keyword ] ],
335 ) ),
336 'timeout' => 60,
337 ) );
338 if ( is_wp_error( $response ) ) { return ''; }
339 $results = str_replace( "#", "", wp_remote_retrieve_body( $response ) );
340 $decoded = json_decode( $results );
341 return isset( $decoded->choices[0]->message->content ) ? $decoded->choices[0]->message->content : '';
342 }
343 }
344 public function response_form_file($keyword){
345 $max_tokens = (int)get_option( 'openai_max_tokens');
346 $temp = (float)get_option( 'openai_temperature');
347 $frequency_penalty = (float)get_option( 'frequency_penalty');
348 $presence_penalty = (float)get_option( 'presence_penalty');
349 $engines = explode('-',get_option( 'openai_engines'));
350 if($engines[0] != 'gpt'){
351 // $prompts = $this->get_prompt($keyword);
352 }
353
354 $request_body = [
355 "prompt" => $keyword,
356 "model" => get_option( 'qcld_openai_custom_model'),
357 "max_tokens" => $max_tokens,
358 "temperature" => 0,
359 "top_p" => 1,
360 "stop" => [],
361 "presence_penalty" => 0,
362 "frequency_penalty"=> 0,
363 "best_of"=> 1,
364 ];
365 $postFields = wp_json_encode($request_body);
366 $OpenAI = new qcld_wp_OpenAI();
367 $result = $OpenAI->get_response($postFields);
368
369 return $result;
370 }
371 public function get_prompt($keyword){
372 $openai_include_keyword = get_option( 'openai_include_keyword');
373 $openai_exclude_keyword = get_option( 'openai_exclude_keyword');
374 $qcld_openai_prompt = get_option('qcld_openai_prompt',true);
375
376 }
377 public function include_exclude_prompt($keyword){
378 $openai_include_keyword = strtolower(get_option('openai_include_keyword'));
379 $openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword'));
380
381 if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){
382 $prompts = 'If the query is not relevant to one of the keywords: '.$openai_include_keyword .' then only say DUH. Provide a response only if the following query is relevant to one of the keywords: '.$openai_include_keyword .' The actual query is as follows: '. $keyword;
383 return $prompts;
384 }else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){
385
386 $prompts = 'If the query is relevant to one of the keywords: ' .$openai_exclude_keyword . ', then do not respond and only say "DUH." The actual query is as follows: '. $keyword. '?/n';
387 return $prompts;
388 }else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){
389 $prompts = 'If the query is not relevant to one of the keywords: '.$openai_include_keyword .' then only say "DUH." Provide a response only if the following query is relevant to one of the keywords: '.$openai_include_keyword .' The actual query is as follows: '. $keyword;
390 return $prompts;
391 }
392 }
393 public function qcld_include_keyword_exist( $keyword ){
394 $keyword = isset($keyword) ? $keyword : '';
395 $openai_include_keywords = strtolower(get_option('openai_include_keyword'));
396 if(!empty($keyword)){
397 $openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : '');
398
399 if( !empty($openai_include_keyword)){
400 $include_items = explode(',', $openai_include_keyword);
401 if(!empty($include_items)){
402 foreach($include_items as $k => $item){
403 if((strpos($keyword,trim($item)) !== false) && !empty($item)){
404 return true;
405 }
406 }
407 }
408 return false;
409 }
410 }
411
412 return false;
413
414 }
415
416 public function qcld_openai_response_callback() {
417 if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_chatbot' ) ) {
418 wp_send_json_error([
419 'status' => 'error',
420 'message' => esc_html__( 'Security check failed. Unauthorized request.', 'chatbot' )
421 ]);
422 wp_die();
423 }
424 if (get_option('is_rate_limiting_enabled') == '1') {
425 do_action('rate_limit_checker');
426 }
427 $response['status'] = 'success';
428 $response['message'] ='A preset message';
429 $OpenAI = new qcld_wp_OpenAI();
430 $gptkeyword = [];
431 $keyword = sanitize_text_field(wp_unslash($_POST['keyword']));
432 $relevant_pagelink = $this->relevant_pagelink($keyword);
433
434 // Build context-aware system instructions
435 $system_content = get_option('qcld_openai_system_content');
436
437 // RAG Integration
438 if (get_option('is_page_rag_enabled') == '1') {
439 $rag_context_text = Qcld_Bot_Rag::instance()->run_rag_search($keyword);
440 if (!empty($rag_context_text) && $rag_context_text != "No knowledge base found.") {
441 $rag_context = "Relevant Knowledge Base Information:\n";
442 $rag_context .= $rag_context_text;
443 $rag_context .= "\n\nUse the above information to answer the user's question. If the answer is not in the Knowledge Base, rely on your general knowledge but mention that this information is not in the local knowledge base.";
444 $system_content .= "\n\n" . $rag_context;
445 }
446 }
447
448 if ( get_option('context_awareness_enabled') == '1' ) {
449 $site_name = get_bloginfo('name');
450 $site_desc = get_bloginfo('description');
451
452 // Get current page URL and title more reliably
453 $current_url = '';
454 $page_title = '';
455 $page_summary = '';
456
457 // Try to get from referrer first
458 $ref = wp_get_referer();
459 if ( ! $ref && isset($_SERVER['HTTP_REFERER']) ) {
460 $ref = esc_url_raw( $_SERVER['HTTP_REFERER'] );
461 }
462
463 if ( $ref ) {
464 $current_url = $ref;
465
466 // Try to get post/page by URL
467 $post_id = url_to_postid( $ref );
468 if ( $post_id ) {
469 $page_title = get_the_title( $post_id );
470 $raw_content = get_post_field( 'post_content', $post_id );
471 $text_content = wp_strip_all_tags( $raw_content );
472 $page_summary = wp_trim_words( $text_content, 120, '' );
473 } else {
474 // If not a post/page, try to extract title from URL or use current page
475 $parsed_url = wp_parse_url( $ref );
476 if ( isset($parsed_url['path']) ) {
477 $path = trim($parsed_url['path'], '/');
478 if ( ! empty($path) ) {
479 // Try to get title from current page if we're on it
480 if ( is_singular() ) {
481 $page_title = get_the_title();
482 $raw_content = get_the_content();
483 $text_content = wp_strip_all_tags( $raw_content );
484 $page_summary = wp_trim_words( $text_content, 120, '' );
485 } elseif ( is_archive() ) {
486 $page_title = get_the_archive_title();
487 } elseif ( is_search() ) {
488 $page_title = 'Search Results';
489 } elseif ( is_404() ) {
490 $page_title = 'Page Not Found';
491 }
492 }
493 }
494 }
495 } else {
496 // Fallback to current page info.
497 $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
498 $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
499 $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
500 $current_url = esc_url_raw($scheme . '://' . $host . $request_uri);
501
502 if ( is_singular() ) {
503 $page_title = get_the_title();
504 $raw_content = get_the_content();
505 $text_content = wp_strip_all_tags( $raw_content );
506 $page_summary = wp_trim_words( $text_content, 120, '' );
507 } elseif ( is_archive() ) {
508 $page_title = get_the_archive_title();
509 } elseif ( is_search() ) {
510 $page_title = 'Search Results';
511 } elseif ( is_404() ) {
512 $page_title = 'Page Not Found';
513 }
514 }
515
516 $context_bits = array();
517 if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; }
518 if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; }
519 if ( $page_title ) { $context_bits[] = 'Page title: ' . $page_title; }
520 if ( $current_url ) { $context_bits[] = 'URL: ' . $current_url; }
521 if ( $page_summary ) { $context_bits[] = 'Page summary: ' . $page_summary; }
522
523 if ( ! empty( $context_bits ) ) {
524 $context_info = 'Context Information: ' . implode( '. ', $context_bits ) . '. Please use this context to provide more relevant and accurate responses.';
525 $system_content = $system_content . "\n\n" . $context_info;
526 }
527 }
528
529 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
530
531 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
532
533 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
534
535 if(is_array($relevant_post_link )){
536
537 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
538 }else{
539 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
540 }
541 }else{
542 $relevant_pagelinks = '';
543 }
544
545
546 array_push( $gptkeyword, array(
547 "role" => "system",
548 "content" => $system_content
549 ));
550 array_push($gptkeyword, array(
551 "role" => "user",
552 "content" => $keyword
553 ));
554 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
555 $prompts = $this->include_exclude_prompt($keyword);
556
557 $gptkeyword = [];
558 array_push($gptkeyword, array(
559 "role" => "user",
560 "content" => $prompts,
561 ));
562 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
563 if($this->qcld_include_keyword_exist($keyword) == false){
564
565 $response['message'] = 'Sorry, No result found!';
566 wp_send_json( $response );
567 }else{
568 array_push($gptkeyword, array(
569 "role" => "user",
570 "content" => $keyword
571 ));
572 }
573
574 }
575 $res = $OpenAI->gptcomplete(
576 $gptkeyword
577 );
578 $mess = json_decode($res);
579 $Qcld_Parsedown = new Qcld_Parsedown();
580 $msg = $mess->output[0]->content[0]->text;
581 if( $msg == null || empty($msg) ){
582 $msg = $mess->output[1]->content[0]->text;
583 }
584 $msg = $Qcld_Parsedown->text($msg);
585
586 $response['message'] = $msg ;
587 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
588 $response['message'] = 'Sorry, No result found!';
589 }else{
590 $Qcld_Parsedown = new Qcld_Parsedown();
591 $msg = $mess->output[0]->content[0]->text;
592 if( $msg == null || empty($msg) ){
593 $msg = $mess->output[1]->content[0]->text;
594 }
595 $msg = $Qcld_Parsedown->text($msg);
596 $response['message'] = $msg . $relevant_pagelinks;
597 }
598 do_action('qcld_openai_user_rate_cal', 1);
599 wp_send_json( $response );
600 //}
601 }
602 public function openai_settings_option_callback() {
603 $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
604
605 if (! wp_verify_nonce($nonce,'wp_chatbot') || ! current_user_can('manage_options')) {
606 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
607 wp_die();
608
609 }else{
610
611 $api_key = sanitize_text_field(wp_unslash($_POST['api_key']));
612 $openai_engines = sanitize_text_field(wp_unslash($_POST['openai_engines']));
613
614 $qcld_openai_prompt = isset( $_POST['qcld_openai_prompt'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt'])) : '';
615
616
617 $max_tokens = sanitize_text_field(wp_unslash($_POST['max_tokens']));
618 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_suffix'])) : '';
619
620 $qcld_openai_custom_model = isset( $_POST['qcld_openai_custom_model'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_custom_model'])) : '';
621
622
623
624 $frequency_penalty = sanitize_text_field(wp_unslash($_POST['frequency_penalty']));
625 $presence_penalty = sanitize_text_field(wp_unslash($_POST['presence_penalty']));
626 $temperature = sanitize_text_field(wp_unslash($_POST['temperature']));
627 $ai_enabled = sanitize_text_field(wp_unslash($_POST['ai_enabled']));
628 $suggestion_enabled = sanitize_text_field(wp_unslash($_POST['is_page_suggestion_enabled']));
629 $context_awareness_enabled = sanitize_text_field(wp_unslash($_POST['is_context_awareness_enabled']));
630 $is_page_rag_enabled = sanitize_text_field(wp_unslash($_POST['is_page_rag_enabled']));
631
632
633 $is_relevant_enabled = sanitize_text_field(wp_unslash($_POST['is_relevant_enabled']));
634 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field(wp_unslash($_POST['file_id'])) : '';
635
636 $qcld_openai_prompt_custom = isset( $_POST['qcld_openai_prompt_custom'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt_custom'])) : '';
637
638 $openai_post_types = array();
639 if (isset($_POST['openai_post_type'])) {
640 $raw_post_types = wp_unslash($_POST['openai_post_type']);
641 if (is_array($raw_post_types)) {
642 $openai_post_types = array_map('sanitize_text_field', $raw_post_types);
643 } else {
644 $openai_post_types = sanitize_text_field($raw_post_types);
645 }
646 }
647 update_option('qcld_openai_relevant_post', $openai_post_types);
648
649 $conversation_continuity = sanitize_text_field(wp_unslash($_POST['conversation_continuity']));
650 $qcld_openai_system_content = sanitize_text_field(wp_unslash($_POST['qcld_openai_system_content']));
651 $qcld_openai_append_content = sanitize_text_field(wp_unslash($_POST['qcld_openai_append_content']));
652
653 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
654 $disable_ss = isset( $_POST['disable_ss'] ) ? sanitize_text_field(wp_unslash($_POST['disable_ss'])) : '';
655
656
657 if($api_key != ''){
658 update_option( 'open_ai_api_key', $api_key );
659 }
660 else{
661 delete_option( 'open_ai_api_key');
662 }
663
664 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
665
666 if($openai_engines != ''){
667 update_option( 'openai_engines', $openai_engines );
668 }
669 if($conversation_continuity != ''){
670 update_option( 'conversation_continuity', $conversation_continuity );
671 }
672 update_option( 'openai_max_tokens', $max_tokens );
673
674 if($qcld_openai_suffix != ''){
675 update_option('qcld_openai_suffix', $qcld_openai_suffix);
676 }
677 if($frequency_penalty != ''){
678 update_option( 'frequency_penalty', $frequency_penalty );
679 }
680 if($presence_penalty != ''){
681 update_option( 'presence_penalty', $presence_penalty );
682 }
683 if($temperature != ''){
684 update_option( 'openai_temperature', $temperature );
685 }
686 if($qcld_openai_prompt_custom != ''){
687 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
688 }
689 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
690 update_option( 'qcld_openai_system_content', stripslashes( $qcld_openai_system_content) );
691 update_option( 'qcld_openai_append_content', stripslashes( $qcld_openai_append_content) );
692
693 update_option('ai_enabled',$ai_enabled);
694 if( $ai_enabled == 1 ){
695
696 update_option('qcld_openrouter_enabled',0);
697 update_option('qcld_gemini_enabled',0);
698 }
699
700 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
701 update_option('page_suggestion_enabled',$suggestion_enabled);
702 update_option('context_awareness_enabled',$context_awareness_enabled);
703 update_option('is_page_rag_enabled',$is_page_rag_enabled);
704
705
706 if($file_id != ''){
707 update_option('file_id',$file_id);
708 }
709 $openai_include_keyword = sanitize_text_field(wp_unslash($_POST['openai_include_keyword']));
710 update_option('openai_include_keyword',$openai_include_keyword);
711 $openai_exclude_keyword = sanitize_text_field(wp_unslash($_POST['openai_exclude_keyword']));
712 update_option('openai_exclude_keyword',$openai_exclude_keyword);
713
714
715 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
716 //Disable Site Search
717 if( $disable_ss == 1 ){
718 update_option('disable_wp_chatbot_site_search',1);
719 update_option('enable_wp_chatbot_post_content', '');
720 }
721 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
722 if($qcld_openai_prompt != ''){
723 update_option('qcld_openai_prompt', $qcld_openai_prompt);
724 }
725 }
726 $OpenAI = new qcld_wp_OpenAI();
727 $gptkeyword = array();
728 array_push(
729 $gptkeyword,
730 array(
731 'role' => 'user',
732 'content' => 'Is our request comes from openAI ?',
733 )
734 );
735 $res = $OpenAI->gptcomplete(
736 $gptkeyword
737 );
738
739 if ( empty( json_decode( $res )->error ) ) {
740 $mess = json_decode( $res );
741 $msg = preg_replace( "/\r\n|\r|\n/", '<br/>', $mess->output[0]->content[0]->text );
742 wp_send_json(
743 array(
744 'success' => true,
745 'title' => esc_html__( 'success', 'chatbot' ),
746 'icon' => esc_html__( 'success', 'chatbot' ),
747 'msg' => esc_html( $msg ),
748 )
749 );
750 } else {
751
752 wp_send_json(
753 array(
754 'success' => true,
755 'title' => esc_html__( 'Error', 'chatbot' ),
756 'icon' => esc_html__( 'error', 'chatbot' ),
757 'msg' => esc_html( json_decode( $res )->error->message ),
758 )
759 );
760 }
761
762 // echo wp_json_encode($ai_enabled);wp_die();
763
764 }
765 public function rag_settings_option_callback()
766 {
767 $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
768 if (!wp_verify_nonce($nonce, 'wp_chatbot') || !current_user_can('manage_options')) {
769 wp_send_json_error(array('message' => esc_html__('Security check failed', 'chatbot')));
770 wp_die();
771 }
772 if( (get_option('is_page_rag_enabled') == '1' && get_option('open_ai_api_key')) || (get_option('qcld_gemini_rag_enabled') == '1' && get_option('qcld_gemini_api_key'))){
773
774
775 $rag_embed_pages = sanitize_text_field(wp_unslash($_POST['rag_embed_pages']) ?? 0);
776 $rag_embed_posts = sanitize_text_field(wp_unslash($_POST['rag_embed_posts']) ?? 0);
777 $rag_embed_str = sanitize_text_field(wp_unslash($_POST['rag_embed_str']) ?? 0);
778 $rag_auto_sync_enabled = sanitize_text_field(wp_unslash($_POST['rag_auto_sync_enabled']) ?? 0);
779
780 $rag_embed_cpts = isset($_POST['rag_embed_cpts']) ? wp_unslash($_POST['rag_embed_cpts']) : [];
781 if(is_array($rag_embed_cpts)){
782 $rag_embed_cpts = array_map('sanitize_text_field', $rag_embed_cpts);
783 }
784
785 if (isset($_POST['is_page_rag_enabled'])) {
786 $is_rag_enabled = sanitize_text_field(wp_unslash($_POST['is_page_rag_enabled']));
787 update_option('is_page_rag_enabled', $is_rag_enabled);
788 if($is_rag_enabled == 1){
789 update_option('is_asst_enabled', 0);
790 }
791 }
792
793 update_option('rag_embed_pages', $rag_embed_pages);
794 update_option('rag_embed_str', $rag_embed_str);
795 update_option('rag_embed_posts', $rag_embed_posts);
796 update_option('rag_auto_sync_enabled', $rag_auto_sync_enabled);
797 update_option('rag_embed_cpts', $rag_embed_cpts);
798
799 wp_send_json( array('status' => 'success') );
800 }else{
801 if( !get_option('open_ai_api_key') || !get_option('qcld_gemini_api_key') ){
802 wp_send_json_success(array('status' => 'error', 'message' => esc_html__('RAG cannot be enabled without an API key.', 'chatbot')));
803 }else if( get_option('is_page_rag_enabled') != '1' && get_option('qcld_gemini_rag_enabled') != '1' ){
804 wp_send_json_success(array('status' => 'error', 'message' => esc_html__('Please enable RAG in settings to save RAG related options.', 'chatbot')));
805 }
806 wp_die();
807 }
808 }
809 public function qcld_update_settings_option_callback(){
810 // Verify nonce for CSRF protection
811 $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
812 if (!wp_verify_nonce($nonce, 'wp_chatbot') || !current_user_can('manage_options')) {
813 wp_send_json_error(array('message' => esc_html__('Security check failed', 'chatbot')));
814 wp_die();
815 }
816
817 // Check user capability - only administrators can modify settings
818 if (!current_user_can('manage_options')) {
819 wp_send_json_error(array('message' => esc_html__('Unauthorized access', 'chatbot')));
820 wp_die();
821 }
822
823 // Proceed with option updates
824 update_option('disable_wp_chatbot_site_search', 1);
825 update_option('enable_wp_chatbot_post_content', '');
826
827 // Send success response
828 wp_send_json_success(array('message' => esc_html__('Settings updated successfully', 'chatbot')));
829 wp_die();
830 }
831 public function qcpd_remove_wa_stopwords($query, $stopwords){
832
833 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
834
835 }
836 public function openai_troubleshooting() {
837 $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
838 $OpenAI = new qcld_wp_OpenAI();
839 if ( ! wp_verify_nonce( $nonce, 'wp_chatbot' ) ) {
840 wp_send_json(
841 array(
842 'success' => false,
843 'msg' => esc_html__( 'Failed in Security check', 'chatbot' ),
844 )
845 );
846 wp_die();
847
848 } elseif ( ! current_user_can( 'manage_options' ) ) {
849 wp_send_json(
850 array(
851 'success' => false,
852 'msg' => esc_html__( 'Unauthorized user', 'chatbot' ),
853 )
854 );
855 wp_die();
856 } else {
857 $gptkeyword = array();
858 array_push(
859 $gptkeyword,
860 array(
861 'role' => 'user',
862 'content' => 'Is our request comes from openAI ?',
863 )
864 );
865 $res = $OpenAI->gptcomplete(
866 $gptkeyword
867 );
868
869 if ( empty( json_decode( $res )->error ) ) {
870 $mess = json_decode( $res );
871 $msg = preg_replace( "/\r\n|\r|\n/", '<br/>', $mess->output[0]->content[0]->text );
872 wp_send_json(
873 array(
874 'success' => true,
875 'title' => esc_html__( 'success', 'chatbot' ),
876 'icon' => esc_html__( 'success', 'chatbot' ),
877 'msg' => esc_html( $msg ),
878 )
879 );
880 } else {
881
882 wp_send_json(
883 array(
884 'success' => true,
885 'title' => esc_html__( 'Error', 'chatbot' ),
886 'icon' => esc_html__( 'error', 'chatbot' ),
887 'msg' => esc_html( json_decode( $res )->error->message ),
888 )
889 );
890 }
891 }
892 }
893
894
895 }
896
897 /**
898 * @return qcld_wpopenai_addon
899 */
900 if(!function_exists('qcld_wpopenai_addons')){
901 function qcld_openais() {
902 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
903 return $qcld_wpopenai_addon->instance();
904
905 }
906 }
907
908 //fire off the plugin
909 qcld_openais();
910
911 }