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

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

704 lines 33.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_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_openai_response',[$this,'openai_response_callback']);
64 add_action('wp_ajax_nopriv_openai_response', [$this, 'openai_response_callback']);
65 add_action('wp_ajax_openai_troubleshooting',[$this,'openai_troubleshooting']);
66 if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) {
67 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts'));
68 }
69
70
71 }
72
73
74 /**
75 * Define wpbot Constants.
76 *
77 * @return void
78 * @since 1.0.0
79 */
80 public function define_constants() {
81 if( ! defined( 'QCLD_openai_addon_VERSION' ) ){
82 define('QCLD_openai_addon_VERSION', $this->version);
83 }
84 //define('QCLD_openai_addon_REQUIRED_wpCOMMERCE_VERSION', 2.2);
85
86 if( ! defined( 'QCLD_openai_addon_PLUGIN_DIR_PATH' ) ){
87 define('QCLD_openai_addon_PLUGIN_DIR_PATH', plugin_dir_path(__FILE__));
88 }
89 if( ! defined( 'QCLD_openai_addon_PLUGIN_URL' ) ){
90 define('QCLD_openai_addon_PLUGIN_URL', plugin_dir_url(__FILE__));
91 }
92 if( ! defined( 'QCLD_openai_addon_IMG_URL' ) ){
93 define('QCLD_openai_addon_IMG_URL', QCLD_openai_addon_PLUGIN_URL . "images/");
94 }
95 if( ! defined( 'QCLD_openai_addon_IMG_ABSOLUTE_PATH' ) ){
96 define('QCLD_openai_addon_IMG_ABSOLUTE_PATH', plugin_dir_path(__FILE__) . "images");
97 }
98
99 }
100
101
102 // public function qcld_wb_chatbot_admin_scripts(){
103 // // wp_register_style('qlcd-open-ai-bootstap', QCLD_openai_addon_PLUGIN_URL . 'css/openai-bootstrap.css', '', QCLD_openai_addon_VERSION, 'screen');
104 // // wp_enqueue_style('qlcd-open-ai-bootstap');
105 // // wp_register_style('qlcd-open-ai-admin-style', QCLD_openai_addon_PLUGIN_URL . 'css/openai-admin-style.css', '', QCLD_openai_addon_VERSION, 'screen');
106 // // wp_enqueue_style('qlcd-open-ai-admin-style');
107 // // wp_register_script('qlcd-openai_collapse', QCLD_openai_addon_PLUGIN_URL . 'js/collapse.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
108 // // wp_enqueue_script('qlcd-openai_collapse');
109 // // wp_register_script('qlcd-openai_settings', QCLD_openai_addon_PLUGIN_URL . 'js/openai_settings.js', array('jquery'),'',QCLD_openai_addon_VERSION,true);
110 // // wp_enqueue_script('qlcd-openai_settings');
111
112 // // wp_localize_script( 'qlcd-openai_settings', 'openai_ajax', array(
113 // // 'url' => admin_url( 'admin-ajax.php' ),
114 // // ) );
115
116 // }
117 /**
118 * Include all required files
119 *
120 * since 1.0.0
121 *
122 * @return void
123 */
124 public function includes() {
125 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/qcld_wp_OpenAI.php" );
126 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/OpenAi_WPBot_Menu.php" );
127 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/openai/Parsedown.php" );
128
129 }
130
131 public function buildFormBody( $fields, $boundary )
132 {
133 $body = '';
134 foreach ( $fields as $name => $value ) {
135 if ( $name == 'data' ) {
136 continue;
137 }
138 $body .= "--$boundary\r\n";
139 $body .= "Content-Disposition: form-data; name=\"$name\"";
140 if ( $name == 'file' ) {
141 $body .= "; filename=\"{$value}\"\r\n";
142 $body .= "Content-Type: application/json\r\n\r\n";
143 $body .= $fields['data'] . "\r\n";
144 }else {
145 $body .= "\r\n\r\n$value\r\n";
146 }
147 }
148 $body .= "--$boundary--\r\n";
149 return $body;
150 }
151
152 // public function openai_file_list_callback(){
153 // $url = 'https://api.openai.com/v1/files';
154 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
155 // $curl = curl_init();
156 // curl_setopt($curl, CURLOPT_URL, $url);
157 // $headers = array(
158 // "Content-Type: application/json",
159 // $apt_key,
160 // );
161 // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
162 // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
163 // $response = curl_exec($curl);
164 // curl_close($curl);
165 // wp_send_json( json_decode($response));
166 // wp_die();
167 // }
168 public function qcld_sanitize_text_or_array_field($array_or_string) {
169 if( is_string($array_or_string) ){
170 $array_or_string = sanitize_text_field($array_or_string);
171 }elseif( is_array($array_or_string) ){
172 foreach ( $array_or_string as $key => &$value ) {
173 if ( is_array( $value ) ) {
174 $value = $this->sanitize_text_or_array_field($value);
175 }
176 else {
177 $value = sanitize_text_field( $value );
178 }
179 }
180 }
181
182 return $array_or_string;
183 }
184
185 // public function openai_file_upload_callback(){
186 // $uploadedfile = $_FILES['file'];
187 // $url = 'https://api.openai.com/v1/files';
188 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
189 // $curl = curl_init($url);
190 // curl_setopt($curl, CURLOPT_URL, $url);
191 // curl_setopt($curl, CURLOPT_POST, true);
192 // $headers = array(
193 // "Content-Type: multipart/form-data",
194 // $apt_key,
195 // );
196 // if (function_exists('curl_file_create')) {
197 // $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']);
198 // } else {
199 // $tmp_file = open($uploadedfile['tmp_name']);
200 // }
201 // $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune');
202 // $init = curl_init();
203 // //function parameteres
204 // curl_setopt($init, CURLOPT_URL,$url);
205 // curl_setopt($init, CURLOPT_HTTPHEADER, $headers);
206 // curl_setopt($init, CURLOPT_POSTFIELDS, $data);
207 // curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
208 // $res = json_decode(curl_exec ($init));
209
210 // curl_close ($init);
211 // if(!empty($res->error)){
212 // $response['status'] = 'error';
213 // $response['message'] = $res->error->message;
214 // }
215
216 // if(!empty($res->status)){
217 // $response['status'] = 'success';
218 // $response['message'] = 'Successfully Created file' . $res->id ;
219
220 // }
221 // echo wp_send_json([$response]);
222 // wp_die();
223 // }
224 public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){
225 $api_key = get_option('open_ai_api_key');
226 $request_headers = array(
227 'Content-Type' => 'application/json',
228 'Authorization' => 'Bearer ' . $api_key,
229 );
230 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
231 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
232 $base_engine = explode('-',$openai_engines);
233 if( $base_engine[0] == 'gpt'){
234 $url = "https://api.openai.com/v1/fine_tuning/jobs";
235 $response = wp_remote_post( $url, array(
236 'headers' => $request_headers,
237 'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ) ),
238 'timeout' => 60,
239 ) );
240 $result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null;
241 }else{
242 $url = "https://api.openai.com/v1/fine-tunes";
243 $response = wp_remote_post( $url, array(
244 'headers' => $request_headers,
245 'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ) ),
246 'timeout' => 60,
247 ) );
248 $result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null;
249 }
250 return $result;
251 }
252 public function relevant_pagelink($search_query){
253
254 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
255
256 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
257
258 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
259
260 $q = trim($cleanWordsWithoutPunctuationMarks);
261
262 $links = [];
263
264 $post_type_array = ['post','page'];
265
266 //Proceeding with traditional search
267
268 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
269
270 if( $the_query->have_posts() ){
271
272 while( $the_query->have_posts() ){
273
274 $the_query->the_post();
275
276 $url = esc_url( get_permalink() );
277
278 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
279
280 array_push($links, $link);
281
282 } //End of WHILE
283
284 wp_reset_postdata();
285
286 } //End of IF
287
288 $links = array_unique($links);
289
290 return $links;
291
292 } //End of function relevant_pagelink()
293 public function openai_retrive_fine_tune($keyword){
294
295 $api_key = get_option('open_ai_api_key');
296 $request_headers = array(
297 'Content-Type' => 'application/json',
298 'Authorization' => 'Bearer ' . $api_key,
299 );
300 $max_tokens = (int)get_option( 'openai_max_tokens');
301 $temp = (float)get_option( 'openai_temperature');
302 $frequency_penalty= (float)get_option( 'frequency_penalty');
303 $presence_penalty = (float)get_option( 'presence_penalty');
304 $custom_model = get_option( 'qcld_openai_custom_model');
305 $custom_model = explode(":", $custom_model);
306 $prompts = $this->get_prompt($keyword);
307
308 if ( isset( $custom_model[1] ) && $custom_model[1] !== 'gpt-3.5-turbo-0613' ) {
309 $response = wp_remote_post( 'https://api.openai.com/v1/completions', array(
310 'headers' => $request_headers,
311 'body' => wp_json_encode( array(
312 'prompt' => $prompts,
313 'model' => get_option( 'qcld_openai_custom_model'),
314 'max_tokens' => $max_tokens,
315 'temperature' => $temp,
316 'top_p' => 1,
317 'presence_penalty' => $frequency_penalty,
318 'frequency_penalty' => $presence_penalty,
319 'best_of' => 1,
320 'stop' => ["\n###\n","###"]
321 ) ),
322 'timeout' => 60,
323 ) );
324 if ( is_wp_error( $response ) ) { return ''; }
325 $result = str_replace( "#", "", wp_remote_retrieve_body( $response ) );
326 return $result;
327 } else {
328 $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array(
329 'headers' => $request_headers,
330 'body' => wp_json_encode( array(
331 'model' => get_option( 'qcld_openai_custom_model'),
332 'messages' => [ [ 'role' => 'user', 'content' => $keyword ] ],
333 ) ),
334 'timeout' => 60,
335 ) );
336 if ( is_wp_error( $response ) ) { return ''; }
337 $results = str_replace( "#", "", wp_remote_retrieve_body( $response ) );
338 $decoded = json_decode( $results );
339 return isset( $decoded->choices[0]->message->content ) ? $decoded->choices[0]->message->content : '';
340 }
341
342 }
343 public function response_form_file($keyword){
344 $max_tokens = (int)get_option( 'openai_max_tokens');
345 $temp = (float)get_option( 'openai_temperature');
346 $frequency_penalty = (float)get_option( 'frequency_penalty');
347 $presence_penalty = (float)get_option( 'presence_penalty');
348 $engines = explode('-',get_option( 'openai_engines'));
349 if($engines[0] != 'gpt'){
350 // $prompts = $this->get_prompt($keyword);
351 }
352
353 $request_body = [
354 "prompt" => $keyword,
355 "model" => get_option( 'qcld_openai_custom_model'),
356 "max_tokens" => $max_tokens,
357 "temperature" => 0,
358 "top_p" => 1,
359 "stop" => [],
360 "presence_penalty" => 0,
361 "frequency_penalty"=> 0,
362 "best_of"=> 1,
363 ];
364 $postFields = wp_json_encode($request_body);
365 $OpenAI = new qcld_wp_OpenAI();
366 $result = $OpenAI->get_response($postFields);
367
368 return $result;
369 }
370 public function get_prompt($keyword){
371 $openai_include_keyword = get_option( 'openai_include_keyword');
372 $openai_exclude_keyword = get_option( 'openai_exclude_keyword');
373 $qcld_openai_prompt = get_option('qcld_openai_prompt',true);
374
375 }
376 public function include_exclude_prompt($keyword){
377 $openai_include_keyword = strtolower(get_option('openai_include_keyword'));
378 $openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword'));
379
380 if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){
381 $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;
382 return $prompts;
383 }else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){
384
385 $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';
386 return $prompts;
387 }else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){
388 $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;
389 return $prompts;
390 }
391 }
392 public function qcld_include_keyword_exist( $keyword ){
393 $keyword = isset($keyword) ? $keyword : '';
394 $openai_include_keywords = strtolower(get_option('openai_include_keyword'));
395 if(!empty($keyword)){
396 $openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : '');
397
398 if( !empty($openai_include_keyword)){
399 $include_items = explode(',', $openai_include_keyword);
400 if(!empty($include_items)){
401 foreach($include_items as $k => $item){
402 if((strpos($keyword,trim($item)) !== false) && !empty($item)){
403 return true;
404 }
405 }
406 }
407 return false;
408 }
409 }
410
411 return false;
412
413 }
414 public function openai_response_callback() {
415 // $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
416 // if (! wp_verify_nonce($nonce,'qcsecretbotnonceval123qc')) {
417 // wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
418 // wp_die();
419
420 // }else{
421 if (get_option('is_rate_limiting_enabled') == '1') {
422 do_action('rate_limit_checker');
423 }
424 $response['status'] = 'success';
425 $response['message'] ='A preset message';
426 $OpenAI = new qcld_wp_OpenAI();
427 $gptkeyword = [];
428 $keyword = sanitize_text_field(wp_unslash($_POST['keyword']));
429 $relevant_pagelink = $this->relevant_pagelink($keyword);
430
431 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
432 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
433
434 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
435
436 if(is_array($relevant_post_link )){
437
438 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
439 }else{
440 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
441 }
442 }else{
443 $relevant_pagelinks = '';
444 }
445 if(get_option( 'is_asst_enabled') != 1){
446 $response_files = $this->openai_retrive_fine_tune($keyword);
447 $response_file = json_decode($response_files, true);
448 $gptkeywords = [];
449 if((empty($response_file['choices'][0]["text"])) && empty($response_file['choices'][0]["message"]['content'])){
450 array_push( $gptkeyword, array(
451 "role" => "system",
452 "content" => get_option('qcld_openai_system_content')
453 ));
454 array_push($gptkeyword, array(
455 "role" => "user",
456 "content" => $keyword
457 ));
458 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
459 $prompts = $this->include_exclude_prompt($keyword);
460
461 $gptkeyword = [];
462 array_push($gptkeyword, array(
463 "role" => "user",
464 "content" => $prompts,
465 ));
466 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
467 if($this->qcld_include_keyword_exist($keyword) == false){
468
469 $response['message'] = 'Sorry, No result found!';
470 echo wp_json_encode($response);
471 wp_die();
472 }else{
473 array_push($gptkeyword, array(
474 "role" => "user",
475 "content" => $keyword
476 ));
477 }
478
479 }
480 $res = $OpenAI->gptcomplete(
481 $gptkeyword
482 );
483 $mess = json_decode($res);
484
485 $Qcld_Parsedown = new Qcld_Parsedown();
486 $msg = $mess->output[0]->content[0]->text;
487 $msg = $Qcld_Parsedown->text($msg);
488 $response['message'] = $msg ;
489 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
490 $response['message'] = 'Sorry, No result found!';
491 }else{
492 $Qcld_Parsedown = new Qcld_Parsedown();
493 $msg = $mess->output[0]->content[0]->text;
494 $msg = $Qcld_Parsedown->text($msg);
495 $response['message'] = $msg . $relevant_pagelinks;
496 }
497 }else if(!empty($response_file['choices'][0]["message"]['content'])){
498 $result = $response_file['choices'][0]["message"]['content'];
499 $Qcld_Parsedown = new Qcld_Parsedown();
500 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$result);
501 $response['message'] = $msg . $relevant_pagelinks;
502 }else{
503 $result = $response_file['choices'][0]["text"];
504 $message = explode(">",$result);
505 if(empty($message)){
506 $message = $result;
507 }elseif(empty($message[1])){
508 $message = $message[0];
509 }else{
510 $message = $message[1];
511 }
512 $Qcld_Parsedown = new Qcld_Parsedown();
513 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$message);
514 $message = $Qcld_Parsedown->text($msg);
515 if(get_option('conversation_continuity') == 1){
516 $lasfivecookie = $_COOKIE["last_five_prompt"] . $message . '###';
517 setcookie('last_five_prompt', $lasfivecookie, time() + (60000), "/");
518 $response['cookie'] = $lasfivecookie;
519 }
520 $response['message'] = $message . $relevant_pagelinks;
521 }
522 }else{
523 $url = 'https://api.openai.com/v1/threads';
524 $api_key = get_option('open_ai_api_key');
525 $engines = get_option( 'openai_engines');
526
527 $header = [
528 'Content-Type: application/json',
529 'OpenAI-Beta: assistants=v1',
530 'Authorization: Bearer ' . $api_key
531 ];
532 // $threads_id = '';
533 $threads_id_COOKIE = $_COOKIE["qcld_threads_id"];
534 $threads_id = $threads_id_COOKIE;
535 if(($threads_id == '')){
536 $response_raw = wp_remote_post( $url, array(
537 'headers' => array(
538 'Content-Type' => 'application/json',
539 'Authorization' => 'Bearer ' . $api_key,
540 'OpenAI-Beta' => 'assistants=v2',
541 ),
542 'timeout' => 30,
543 ) );
544 if ( ! is_wp_error( $response_raw ) ) {
545 $threads_obj = json_decode( wp_remote_retrieve_body( $response_raw ) );
546 $threads_id = isset( $threads_obj->id ) ? $threads_obj->id : '';
547 setcookie( 'qcld_threads_id', $threads_id, time() + 60000, "/" );
548 }
549 }
550
551 $msg = $this->add_on_thrrads($threads_id,$keyword);
552 $Qcld_Parsedown = new Qcld_Parsedown();
553 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$msg);
554 $message = $Qcld_Parsedown->text($msg);
555 $response['message'] = $message . $relevant_pagelinks;
556
557 }
558 do_action('qcld_openai_user_rate_cal', 1);
559 wp_send_json( $response );
560 //}
561 }
562 public function openai_settings_option_callback() {
563 $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
564
565 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
566 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
567 wp_die();
568
569 }else{
570
571 $api_key = sanitize_text_field(wp_unslash($_POST['api_key']));
572 $openai_engines = sanitize_text_field(wp_unslash($_POST['openai_engines']));
573 $qcld_openai_prompt = sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt']));
574 $max_tokens = sanitize_text_field(wp_unslash($_POST['max_tokens']));
575 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_suffix'])) : '';
576 $qcld_openai_custom_model = sanitize_text_field(wp_unslash($_POST['qcld_openai_custom_model']));
577 $frequency_penalty = sanitize_text_field(wp_unslash($_POST['frequency_penalty']));
578 $presence_penalty = sanitize_text_field(wp_unslash($_POST['presence_penalty']));
579 $temperature = sanitize_text_field(wp_unslash($_POST['temperature']));
580 $ai_enabled = sanitize_text_field(wp_unslash($_POST['ai_enabled']));
581 $suggestion_enabled = sanitize_text_field(wp_unslash($_POST['is_page_suggestion_enabled']));
582 $is_relevant_enabled = sanitize_text_field(wp_unslash($_POST['is_relevant_enabled']));
583 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field(wp_unslash($_POST['file_id'])) : '';
584 $qcld_openai_prompt_custom = sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt_custom']));
585 $conversation_continuity = sanitize_text_field(wp_unslash($_POST['conversation_continuity']));
586 $qcld_openai_system_content = sanitize_text_field(wp_unslash($_POST['qcld_openai_system_content']));
587 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
588
589 $disable_ss = sanitize_text_field(wp_unslash($_POST['disable_ss']));
590
591 if($api_key != ''){
592 update_option( 'open_ai_api_key', $api_key );
593 }
594 else{
595 delete_option( 'open_ai_api_key');
596 }
597
598 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
599
600 if($openai_engines != ''){
601 update_option( 'openai_engines', $openai_engines );
602 }
603 if($conversation_continuity != ''){
604 update_option( 'conversation_continuity', $conversation_continuity );
605 }
606 update_option( 'openai_max_tokens', $max_tokens );
607
608 if($qcld_openai_suffix != ''){
609 update_option('qcld_openai_suffix', $qcld_openai_suffix);
610 }
611 if($frequency_penalty != ''){
612 update_option( 'frequency_penalty', $frequency_penalty );
613 }
614 if($presence_penalty != ''){
615 update_option( 'presence_penalty', $presence_penalty );
616 }
617 if($temperature != ''){
618 update_option( 'openai_temperature', $temperature );
619 }
620 if($qcld_openai_prompt_custom != ''){
621 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
622 }
623 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
624 update_option('qcld_openai_system_content', stripslashes( $qcld_openai_system_content));
625 update_option('ai_enabled',$ai_enabled);
626 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
627 update_option('page_suggestion_enabled',$suggestion_enabled);
628 if($file_id != ''){
629 update_option('file_id',$file_id);
630 }
631 $openai_include_keyword = sanitize_text_field(wp_unslash($_POST['openai_include_keyword']));
632 update_option('openai_include_keyword',$openai_include_keyword);
633 $openai_exclude_keyword = sanitize_text_field(wp_unslash($_POST['openai_exclude_keyword']));
634 update_option('openai_exclude_keyword',$openai_exclude_keyword);
635
636
637 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
638 //Disable Site Search
639 if( $disable_ss == 1 ){
640 update_option('disable_wp_chatbot_site_search',1);
641 }
642 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
643
644
645
646 }
647 if($qcld_openai_prompt != ''){
648 update_option('qcld_openai_prompt', $qcld_openai_prompt);
649 }
650 $tem = get_option( 'openai_temperature', $temperature );
651
652 echo wp_json_encode($ai_enabled);wp_die();
653
654 }
655 public function qcpd_remove_wa_stopwords($query, $stopwords){
656
657 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
658
659 }
660 public function openai_troubleshooting(){
661 $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
662 $OpenAI = new qcld_wp_OpenAI();
663 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
664 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
665 wp_die();
666
667 }else{
668 $gptkeyword = [];
669 array_push($gptkeyword, array(
670 "role" => "user",
671 "content" => "If you get this query respond in plain text: Congrats! You are connected to AI."
672 ));
673 $res = $OpenAI->gptcomplete(
674 $gptkeyword
675 );
676 if(empty(json_decode($res)->error)){
677 $mess = json_decode($res);
678 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$mess->choices[0]->message->content);
679 wp_send_json(array('success' => true,'title' => esc_html__('success', 'chatbot'),'icon'=>esc_html__('alert-success', 'chatbot'),'msg' => wp_kses_post($msg)));
680 }else{
681 // If there's an error, the 'success' flag should be false.
682 wp_send_json(array('success' => false,'title' => esc_html__('Error', 'chatbot'),'icon'=>esc_html__('error', 'chatbot'), 'msg' => esc_html(json_decode($res)->error->message)));
683 }
684 }
685 }
686
687
688 }
689
690 /**
691 * @return qcld_wpopenai_addon
692 */
693 if(!function_exists('qcld_wpopenai_addons')){
694 function qcld_openais() {
695 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
696 return $qcld_wpopenai_addon->instance();
697
698 }
699 }
700
701 //fire off the plugin
702 qcld_openais();
703
704 }