PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 7.9.5
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v7.9.5
8.7.9 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 All 535 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 7.9.5, at includes/openai/qcld-bot-openai.php

740 lines 34.4 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 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
226 $headers = array(
227 "Content-Type: application/json",
228 $apt_key,
229 );
230 $curl = curl_init();
231 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
232 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
233 $base_engine = explode('-',$openai_engines);
234 if( $base_engine[0] == 'gpt'){
235 $data = json_encode(array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ));
236 $url = "https://api.openai.com/v1/fine_tuning/jobs";
237 curl_setopt($curl, CURLOPT_URL, $url);
238 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
239 curl_setopt($curl, CURLOPT_POST, true);
240 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
241 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
242 $result = json_decode(curl_exec($curl));
243 curl_close($curl);
244 }else{
245
246 $data = json_encode(array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ));
247 $url = "https://api.openai.com/v1/fine-tunes";
248 curl_setopt($curl, CURLOPT_URL, $url);
249 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
250 curl_setopt($curl, CURLOPT_POST, true);
251 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
252 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
253 $result = json_decode(curl_exec($curl));
254 curl_close($curl);
255 }
256 return $result;
257 }
258 public function relevant_pagelink($search_query){
259
260 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
261
262 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
263
264 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
265
266 $q = trim($cleanWordsWithoutPunctuationMarks);
267
268 $links = [];
269
270 $post_type_array = ['post','page'];
271
272 //Proceeding with traditional search
273
274 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
275
276 if( $the_query->have_posts() ){
277
278 while( $the_query->have_posts() ){
279
280 $the_query->the_post();
281
282 $url = esc_url( get_permalink() );
283
284 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
285
286 array_push($links, $link);
287
288 } //End of WHILE
289
290 wp_reset_postdata();
291
292 } //End of IF
293
294 $links = array_unique($links);
295
296 return $links;
297
298 } //End of function relevant_pagelink()
299 public function openai_retrive_fine_tune($keyword){
300
301 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
302 $headers = array(
303 "Content-Type: application/json",
304 $apt_key,
305 );
306 $curl = curl_init();
307 $max_tokens = (int)get_option( 'openai_max_tokens');
308 $temp = (float)get_option( 'openai_temperature');
309 $frequency_penalty = (float)get_option( 'frequency_penalty');
310 $presence_penalty = (float)get_option( 'presence_penalty');
311 $engines = explode('-',get_option( 'openai_engines'));
312 $custom_model = get_option( 'qcld_openai_custom_model');
313 $custom_model = (explode(":",$custom_model));
314 $prompts = $this->get_prompt($keyword);
315
316 if($custom_model[1] != 'gpt-3.5-turbo-0613'){
317 $data = json_encode(array(
318 'prompt'=> $prompts,
319 'model'=> get_option( 'qcld_openai_custom_model'),
320 "max_tokens" => $max_tokens,
321 "temperature" => $temp,
322 "top_p" => 1,
323 "presence_penalty" => $frequency_penalty,
324 "frequency_penalty"=> $presence_penalty,
325 "best_of"=> 1,
326 "stop"=> ["\n###\n","###"]
327 ));
328 $url = "https://api.openai.com/v1/completions";
329
330 $ch = curl_init();
331
332 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
333 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
334 // curl_setopt($ch, CURLOPT_POST, 1);
335 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
336 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
337 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
338 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
339
340 $result = (curl_exec($ch));
341 $result = str_replace("#","",$result );
342
343 return $result;
344 if (curl_errno($ch)) {
345 // phpcs:ignore
346 echo esc_html('Error: ' . curl_error($ch));
347 }
348 curl_close($ch);
349 }else{
350 $data = json_encode(array(
351 'model'=> get_option( 'qcld_openai_custom_model'),
352 "messages"=> [
353
354 [
355 "role"=> "user",
356 "content"=>$keyword
357 ]
358
359 ],
360
361 ));
362 $ch = curl_init();
363
364 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
365 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
366 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
367 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
368 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
369
370 $results = (curl_exec($ch));
371 $results = str_replace("#","",$result );
372 $result = (json_decode($results)->choices[0]->message->content);
373 return $result;
374
375
376 }
377
378 }
379 public function response_form_file($keyword){
380 $max_tokens = (int)get_option( 'openai_max_tokens');
381 $temp = (float)get_option( 'openai_temperature');
382 $frequency_penalty = (float)get_option( 'frequency_penalty');
383 $presence_penalty = (float)get_option( 'presence_penalty');
384 $engines = explode('-',get_option( 'openai_engines'));
385 if($engines[0] != 'gpt'){
386 // $prompts = $this->get_prompt($keyword);
387 }
388
389 $request_body = [
390 "prompt" => $keyword,
391 "model" => get_option( 'qcld_openai_custom_model'),
392 "max_tokens" => $max_tokens,
393 "temperature" => 0,
394 "top_p" => 1,
395 "stop" => [],
396 "presence_penalty" => 0,
397 "frequency_penalty"=> 0,
398 "best_of"=> 1,
399 ];
400 $postFields = json_encode($request_body);
401 $OpenAI = new qcld_wp_OpenAI();
402 $result = $OpenAI->get_response($postFields);
403
404 return $result;
405 }
406 public function get_prompt($keyword){
407 $openai_include_keyword = get_option( 'openai_include_keyword');
408 $openai_exclude_keyword = get_option( 'openai_exclude_keyword');
409 $qcld_openai_prompt = get_option('qcld_openai_prompt',true);
410
411 }
412 public function include_exclude_prompt($keyword){
413 $openai_include_keyword = strtolower(get_option('openai_include_keyword'));
414 $openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword'));
415
416 if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){
417 $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;
418 return $prompts;
419 }else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){
420
421 $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';
422 return $prompts;
423 }else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){
424 $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;
425 return $prompts;
426 }
427 }
428 public function qcld_include_keyword_exist( $keyword ){
429 $keyword = isset($keyword) ? $keyword : '';
430 $openai_include_keywords = strtolower(get_option('openai_include_keyword'));
431 if(!empty($keyword)){
432 $openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : '');
433
434 if( !empty($openai_include_keyword)){
435 $include_items = explode(',', $openai_include_keyword);
436 if(!empty($include_items)){
437 foreach($include_items as $k => $item){
438 if((strpos($keyword,trim($item)) !== false) && !empty($item)){
439 return true;
440 }
441 }
442 }
443 return false;
444 }
445 }
446
447 return false;
448
449 }
450 public function openai_response_callback() {
451 // $nonce = sanitize_text_field($_POST['nonce']);
452 // if (! wp_verify_nonce($nonce,'qcsecretbotnonceval123qc')) {
453 // wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
454 // wp_die();
455
456 // }else{
457 $response['status'] = 'success';
458 $response['message'] ='A preset message';
459 $OpenAI = new qcld_wp_OpenAI();
460 $gptkeyword = [];
461 $keyword = sanitize_text_field($_POST['keyword']);
462 $relevant_pagelink = $this->relevant_pagelink($keyword);
463
464 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
465
466 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
467
468 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
469
470 if(is_array($relevant_post_link )){
471
472 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
473 }else{
474 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
475 }
476 }else{
477 $relevant_pagelinks = '';
478 }
479 if(get_option( 'is_asst_enabled') != 1){
480 $response_files = $this->openai_retrive_fine_tune($keyword);
481 $response_file = json_decode($response_files, true);
482 $gptkeywords = [];
483 if((empty($response_file['choices'][0]["text"])) && empty($response_file['choices'][0]["message"]['content'])){
484 array_push( $gptkeyword, array(
485 "role" => "system",
486 "content" => get_option('qcld_openai_system_content')
487 ));
488 array_push($gptkeyword, array(
489 "role" => "user",
490 "content" => $keyword
491 ));
492 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
493 $prompts = $this->include_exclude_prompt($keyword);
494
495 $gptkeyword = [];
496 array_push($gptkeyword, array(
497 "role" => "user",
498 "content" => $prompts,
499 ));
500 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
501 if($this->qcld_include_keyword_exist($keyword) == false){
502
503 $response['message'] = 'Sorry, No result found!';
504 echo wp_json_encode($response);
505 wp_die();
506 }else{
507 array_push($gptkeyword, array(
508 "role" => "user",
509 "content" => $keyword
510 ));
511 }
512
513 }
514 $res = $OpenAI->gptcomplete(
515 $gptkeyword
516 );
517 $mess = json_decode($res);
518
519 $Qcld_Parsedown = new Qcld_Parsedown();
520 $msg = $mess->output[0]->content[0]->text;
521 $msg = $Qcld_Parsedown->text($msg);
522 $response['message'] = $msg ;
523 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
524 $response['message'] = 'Sorry, No result found!';
525 }else{
526 $Qcld_Parsedown = new Qcld_Parsedown();
527 $msg = $mess->output[0]->content[0]->text;
528 $msg = $Qcld_Parsedown->text($msg);
529 $response['message'] = $msg . $relevant_pagelinks;
530 }
531 }else if(!empty($response_file['choices'][0]["message"]['content'])){
532 $result = $response_file['choices'][0]["message"]['content'];
533 $Qcld_Parsedown = new Qcld_Parsedown();
534 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$result);
535 $response['message'] = $msg . $relevant_pagelinks;
536 }else{
537 $result = $response_file['choices'][0]["text"];
538 $message = explode(">",$result);
539 if(empty($message)){
540 $message = $result;
541 }elseif(empty($message[1])){
542 $message = $message[0];
543 }else{
544 $message = $message[1];
545 }
546 $Qcld_Parsedown = new Qcld_Parsedown();
547 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$message);
548 $message = $Qcld_Parsedown->text($msg);
549 if(get_option('conversation_continuity') == 1){
550 $lasfivecookie = $_COOKIE["last_five_prompt"] . $message . '###';
551 setcookie('last_five_prompt', $lasfivecookie, time() + (60000), "/");
552 $response['cookie'] = $lasfivecookie;
553 }
554 $response['message'] = $message . $relevant_pagelinks;
555 }
556 }else{
557 $url = 'https://api.openai.com/v1/threads';
558 $api_key = get_option('open_ai_api_key');
559 $engines = get_option( 'openai_engines');
560
561 $header = [
562 'Content-Type: application/json',
563 'OpenAI-Beta: assistants=v1',
564 'Authorization: Bearer ' . $api_key
565 ];
566 // $threads_id = '';
567 $threads_id_COOKIE = $_COOKIE["qcld_threads_id"];
568 $threads_id = $threads_id_COOKIE;
569 if(($threads_id == '')){
570
571 $ch = curl_init();
572 curl_setopt($ch, CURLOPT_URL, $url);
573 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
574 curl_setopt($ch, CURLOPT_POST, 1);
575 // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
576 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
577 $threads = curl_exec($ch);
578 $threads_id = json_decode($threads)->id;
579 setcookie('qcld_threads_id',$threads_id , time() + (60000), "/");
580 if (curl_errno($ch)) {
581 // phpcs:ignore
582 echo 'Error: ' . curl_error($ch);
583 }
584 curl_close($ch);
585 }
586
587 $msg = $this->add_on_thrrads($threads_id,$keyword);
588 $Qcld_Parsedown = new Qcld_Parsedown();
589 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$msg);
590 $message = $Qcld_Parsedown->text($msg);
591 $response['message'] = $message . $relevant_pagelinks;
592
593 }
594 echo wp_json_encode($response);
595 wp_die();
596 //}
597 }
598 public function openai_settings_option_callback() {
599 $nonce = sanitize_text_field($_POST['nonce']);
600
601 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
602 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
603 wp_die();
604
605 }else{
606
607 $api_key = sanitize_text_field($_POST['api_key']);
608 $openai_engines = sanitize_text_field($_POST['openai_engines']);
609 $qcld_openai_prompt = sanitize_text_field($_POST['qcld_openai_prompt']);
610 $max_tokens = sanitize_text_field($_POST['max_tokens']);
611 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field($_POST['qcld_openai_suffix']) : '';
612 $qcld_openai_custom_model = sanitize_text_field($_POST['qcld_openai_custom_model']);
613 $frequency_penalty = sanitize_text_field($_POST['frequency_penalty']);
614 $presence_penalty = sanitize_text_field($_POST['presence_penalty']);
615 $temperature = sanitize_text_field($_POST['temperature']);
616 $ai_enabled = sanitize_text_field($_POST['ai_enabled']);
617 $suggestion_enabled = sanitize_text_field($_POST['is_page_suggestion_enabled']);
618 $is_relevant_enabled = sanitize_text_field($_POST['is_relevant_enabled']);
619 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field($_POST['file_id']) : '';
620 $qcld_openai_prompt_custom = sanitize_text_field($_POST['qcld_openai_prompt_custom']);
621 $conversation_continuity = sanitize_text_field($_POST['conversation_continuity']);
622 $qcld_openai_system_content = sanitize_text_field($_POST['qcld_openai_system_content']);
623 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
624
625 $disable_ss = sanitize_text_field($_POST['disable_ss']);
626
627 if($api_key != ''){
628 update_option( 'open_ai_api_key', $api_key );
629 }
630 else{
631 delete_option( 'open_ai_api_key');
632 }
633
634 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
635
636 if($openai_engines != ''){
637 update_option( 'openai_engines', $openai_engines );
638 }
639 if($conversation_continuity != ''){
640 update_option( 'conversation_continuity', $conversation_continuity );
641 }
642 update_option( 'openai_max_tokens', $max_tokens );
643
644 if($qcld_openai_suffix != ''){
645 update_option('qcld_openai_suffix', $qcld_openai_suffix);
646 }
647 if($frequency_penalty != ''){
648 update_option( 'frequency_penalty', $frequency_penalty );
649 }
650 if($presence_penalty != ''){
651 update_option( 'presence_penalty', $presence_penalty );
652 }
653 if($temperature != ''){
654 update_option( 'openai_temperature', $temperature );
655 }
656 if($qcld_openai_prompt_custom != ''){
657 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
658 }
659 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
660 update_option('qcld_openai_system_content', stripslashes( $qcld_openai_system_content));
661 update_option('ai_enabled',$ai_enabled);
662 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
663 update_option('page_suggestion_enabled',$suggestion_enabled);
664 if($file_id != ''){
665 update_option('file_id',$file_id);
666 }
667 $openai_include_keyword = sanitize_text_field($_POST['openai_include_keyword']);
668 update_option('openai_include_keyword',$openai_include_keyword);
669 $openai_exclude_keyword = sanitize_text_field($_POST['openai_exclude_keyword']);
670 update_option('openai_exclude_keyword',$openai_exclude_keyword);
671
672
673 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
674 //Disable Site Search
675 if( $disable_ss == 1 ){
676 update_option('disable_wp_chatbot_site_search',1);
677 }
678 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
679
680
681
682 }
683 if($qcld_openai_prompt != ''){
684 update_option('qcld_openai_prompt', $qcld_openai_prompt);
685 }
686 $tem = get_option( 'openai_temperature', $temperature );
687
688 echo wp_json_encode($ai_enabled);wp_die();
689
690 }
691 public function qcpd_remove_wa_stopwords($query, $stopwords){
692
693 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
694
695 }
696 public function openai_troubleshooting(){
697 $nonce = sanitize_text_field($_POST['nonce']);
698 $OpenAI = new qcld_wp_OpenAI();
699 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
700 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
701 wp_die();
702
703 }else{
704 $gptkeyword = [];
705 array_push($gptkeyword, array(
706 "role" => "user",
707 "content" => "Is our request comes from openAI ?"
708 ));
709 $res = $OpenAI->gptcomplete(
710 $gptkeyword
711 );
712 if(empty(json_decode($res)->error)){
713 $mess = json_decode($res);
714 $msg = preg_replace("/\r\n|\r|\n/", '<br/>',$mess->choices[0]->message->content);
715 wp_send_json(array('success' => true,'title' => esc_html__('success', 'chatbot'),'icon'=>esc_html__('alert-success', 'chatbot'),'msg' => wp_kses_post($msg)));
716 }else{
717 // If there's an error, the 'success' flag should be false.
718 wp_send_json(array('success' => false,'title' => esc_html__('Error', 'chatbot'),'icon'=>esc_html__('error', 'chatbot'), 'msg' => esc_html(json_decode($res)->error->message)));
719 }
720 }
721 }
722
723
724 }
725
726 /**
727 * @return qcld_wpopenai_addon
728 */
729 if(!function_exists('qcld_wpopenai_addons')){
730 function qcld_openais() {
731 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
732 return $qcld_wpopenai_addon->instance();
733
734 }
735 }
736
737 //fire off the plugin
738 qcld_openais();
739
740 }