PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 5.4.9
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v5.4.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 8.5.3 All 534 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 5.4.9, at includes/openai/qcld-bot-openai.php

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