PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services / 7.5.6
WPBot – AI ChatBot for Live Support, Lead Generation, WordPress Automation, AI Services v7.5.6
8.7.8 8.7.7 8.7.6 8.7.5 8.7.4 8.7.3 8.7.2 8.7.1 8.7.0 8.6.9 8.6.8 8.6.7 8.6.6 8.6.5 8.6.4 8.6.2 8.6.1 8.6.0 8.5.9 8.5.8 8.5.7 8.5.6 8.5.5 8.5.4 8.5.3 All 534 releases
chatbot / includes / integration / openai / qcld-bot-openai.php

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

830 lines 37.5 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_openai_response',[$this,'qcld_openai_response_callback']);
65 add_action('wp_ajax_nopriv_qcld_openai_response', [$this, 'qcld_openai_response_callback']);
66 add_action('wp_ajax_openai_troubleshooting',[$this,'openai_troubleshooting']);
67 if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) {
68 add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts'));
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/integration/openai/qcld_wp_OpenAI.php" );
126 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/integration/openai/OpenAi_WPBot_Menu.php" );
127 require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/Parsedown.php" );
128
129 }
130
131
132 public function buildFormBody( $fields, $boundary )
133 {
134 $body = '';
135 foreach ( $fields as $name => $value ) {
136 if ( $name == 'data' ) {
137 continue;
138 }
139 $body .= "--$boundary\r\n";
140 $body .= "Content-Disposition: form-data; name=\"$name\"";
141 if ( $name == 'file' ) {
142 $body .= "; filename=\"{$value}\"\r\n";
143 $body .= "Content-Type: application/json\r\n\r\n";
144 $body .= $fields['data'] . "\r\n";
145 }else {
146 $body .= "\r\n\r\n$value\r\n";
147 }
148 }
149 $body .= "--$boundary--\r\n";
150 return $body;
151 }
152
153 // public function openai_file_list_callback(){
154 // $url = 'https://api.openai.com/v1/files';
155 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
156 // $curl = curl_init();
157 // curl_setopt($curl, CURLOPT_URL, $url);
158 // $headers = array(
159 // "Content-Type: application/json",
160 // $apt_key,
161 // );
162 // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
163 // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
164 // $response = curl_exec($curl);
165 // curl_close($curl);
166 // wp_send_json( json_decode($response));
167 // wp_die();
168 // }
169 public function qcld_sanitize_text_or_array_field($array_or_string) {
170 if( is_string($array_or_string) ){
171 $array_or_string = sanitize_text_field($array_or_string);
172 }elseif( is_array($array_or_string) ){
173 foreach ( $array_or_string as $key => &$value ) {
174 if ( is_array( $value ) ) {
175 $value = $this->qcld_sanitize_text_or_array_field($value);
176 }
177 else {
178 $value = sanitize_text_field( $value );
179 }
180 }
181 }
182
183 return $array_or_string;
184 }
185
186 // public function openai_file_upload_callback(){
187 // $uploadedfile = $_FILES['file'];
188 // $url = 'https://api.openai.com/v1/files';
189 // $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
190 // $curl = curl_init($url);
191 // curl_setopt($curl, CURLOPT_URL, $url);
192 // curl_setopt($curl, CURLOPT_POST, true);
193 // $headers = array(
194 // "Content-Type: multipart/form-data",
195 // $apt_key,
196 // );
197 // if (function_exists('curl_file_create')) {
198 // $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']);
199 // } else {
200 // $tmp_file = open($uploadedfile['tmp_name']);
201 // }
202 // $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune');
203 // $init = curl_init();
204 // //function parameteres
205 // curl_setopt($init, CURLOPT_URL,$url);
206 // curl_setopt($init, CURLOPT_HTTPHEADER, $headers);
207 // curl_setopt($init, CURLOPT_POSTFIELDS, $data);
208 // curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
209 // $res = json_decode(curl_exec ($init));
210
211 // curl_close ($init);
212 // if(!empty($res->error)){
213 // $response['status'] = 'error';
214 // $response['message'] = $res->error->message;
215 // }
216
217 // if(!empty($res->status)){
218 // $response['status'] = 'success';
219 // $response['message'] = 'Successfully Created file' . $res->id ;
220
221 // }
222 // echo wp_send_json([$response]);
223 // wp_die();
224 // }
225 public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){
226 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
227 $headers = array(
228 "Content-Type: application/json",
229 $apt_key,
230 );
231 $curl = curl_init();
232 $qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix');
233 $openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines');
234 $base_engine = explode('-',$openai_engines);
235 if( $base_engine[0] == 'gpt'){
236 $data = json_encode(array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ));
237 $url = "https://api.openai.com/v1/fine_tuning/jobs";
238 curl_setopt($curl, CURLOPT_URL, $url);
239 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
240 curl_setopt($curl, CURLOPT_POST, true);
241 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
242 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
243 $result = json_decode(curl_exec($curl));
244 curl_close($curl);
245 }else{
246
247 $data = json_encode(array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ));
248 $url = "https://api.openai.com/v1/fine-tunes";
249 curl_setopt($curl, CURLOPT_URL, $url);
250 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
251 curl_setopt($curl, CURLOPT_POST, true);
252 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
253 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
254 $result = json_decode(curl_exec($curl));
255 curl_close($curl);
256 }
257 return $result;
258 }
259 public function relevant_pagelink($search_query){
260
261 $stopwords = explode( ',', get_option('qlcd_wp_chatbot_stop_words') );
262
263 $finalQueryWordsWithoutStopWords = $this->qcpd_remove_wa_stopwords( strtolower($search_query), $stopwords );
264
265 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
266
267 $q = trim($cleanWordsWithoutPunctuationMarks);
268
269 $links = [];
270
271 $post_type_array = get_option('qcld_openai_relevant_post');
272
273 //Proceeding with traditional search
274
275 $the_query = new WP_Query( array( 'post_status' => 'publish', 'posts_per_page' => 5, 's' => esc_attr( $q ), 'post_type' => $post_type_array ) );
276
277 if( $the_query->have_posts() ){
278
279 while( $the_query->have_posts() ){
280
281 $the_query->the_post();
282
283 $url = esc_url( get_permalink() );
284
285 $link = '<li><mark><a style="color: #000" href=' . $url . '>' . get_the_title() . '</a><mark></li>';
286
287 array_push($links, $link);
288
289 } //End of WHILE
290
291 wp_reset_postdata();
292
293 } //End of IF
294
295 $links = array_unique($links);
296
297 return $links;
298
299 } //End of function relevant_pagelink()
300 public function openai_retrive_fine_tune($keyword){
301
302 $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key');
303 $headers = array(
304 "Content-Type: application/json",
305 $apt_key,
306 );
307 $curl = curl_init();
308 $max_tokens = (int)get_option( 'openai_max_tokens');
309 $temp = (float)get_option( 'openai_temperature');
310 $frequency_penalty = (float)get_option( 'frequency_penalty');
311 $presence_penalty = (float)get_option( 'presence_penalty');
312 $engines = explode('-',get_option( 'openai_engines'));
313 $custom_model = get_option( 'qcld_openai_custom_model');
314 $custom_model = (explode(":",$custom_model));
315 $prompts = $this->get_prompt($keyword);
316
317 if($custom_model[1] != 'gpt-3.5-turbo-0613'){
318 $data = json_encode(array(
319 'prompt'=> $prompts,
320 'model'=> get_option( 'qcld_openai_custom_model'),
321 "max_tokens" => $max_tokens,
322 "temperature" => $temp,
323 "top_p" => 1,
324 "presence_penalty" => $frequency_penalty,
325 "frequency_penalty"=> $presence_penalty,
326 "best_of"=> 1,
327 "stop"=> ["\n###\n","###"]
328 ));
329 $url = "https://api.openai.com/v1/completions";
330
331 $ch = curl_init();
332
333 curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
334 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
335 // curl_setopt($ch, CURLOPT_POST, 1);
336 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
337 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
338 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
339 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
340
341 $result = (curl_exec($ch));
342 $result = str_replace("#","",$result );
343
344 return $result;
345 if (curl_errno($ch)) {
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("#","",$results );
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 qcld_openai_response_callback() {
451 if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( $_POST['nonce'] ), 'wp_chatbot' ) ) {
452 wp_send_json_error([
453 'status' => 'error',
454 'message' => esc_html__( 'Security check failed. Unauthorized request.', 'chatbot' )
455 ]);
456 wp_die();
457 }
458 $response['status'] = 'success';
459 $response['message'] ='A preset message';
460 $OpenAI = new qcld_wp_OpenAI();
461 $gptkeyword = [];
462 $keyword = sanitize_text_field($_POST['keyword']);
463 $relevant_pagelink = $this->relevant_pagelink($keyword);
464
465 // Build context-aware system instructions
466 $system_content = get_option('qcld_openai_system_content');
467 if ( get_option('context_awareness_enabled') == '1' ) {
468 $site_name = get_bloginfo('name');
469 $site_desc = get_bloginfo('description');
470
471 // Get current page URL and title more reliably
472 $current_url = '';
473 $page_title = '';
474 $page_summary = '';
475
476 // Try to get from referrer first
477 $ref = wp_get_referer();
478 if ( ! $ref && isset($_SERVER['HTTP_REFERER']) ) {
479 $ref = esc_url_raw( $_SERVER['HTTP_REFERER'] );
480 }
481
482 if ( $ref ) {
483 $current_url = $ref;
484
485 // Try to get post/page by URL
486 $post_id = url_to_postid( $ref );
487 if ( $post_id ) {
488 $page_title = get_the_title( $post_id );
489 $raw_content = get_post_field( 'post_content', $post_id );
490 $text_content = wp_strip_all_tags( $raw_content );
491 $page_summary = wp_trim_words( $text_content, 120, '' );
492 } else {
493 // If not a post/page, try to extract title from URL or use current page
494 $parsed_url = parse_url( $ref );
495 if ( isset($parsed_url['path']) ) {
496 $path = trim($parsed_url['path'], '/');
497 if ( ! empty($path) ) {
498 // Try to get title from current page if we're on it
499 if ( is_singular() ) {
500 $page_title = get_the_title();
501 $raw_content = get_the_content();
502 $text_content = wp_strip_all_tags( $raw_content );
503 $page_summary = wp_trim_words( $text_content, 120, '' );
504 } elseif ( is_archive() ) {
505 $page_title = get_the_archive_title();
506 } elseif ( is_search() ) {
507 $page_title = 'Search Results';
508 } elseif ( is_404() ) {
509 $page_title = 'Page Not Found';
510 }
511 }
512 }
513 }
514 } else {
515 // Fallback to current page info.
516 $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
517 $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
518 $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
519 $current_url = esc_url_raw($scheme . '://' . $host . $request_uri);
520
521 if ( is_singular() ) {
522 $page_title = get_the_title();
523 $raw_content = get_the_content();
524 $text_content = wp_strip_all_tags( $raw_content );
525 $page_summary = wp_trim_words( $text_content, 120, '' );
526 } elseif ( is_archive() ) {
527 $page_title = get_the_archive_title();
528 } elseif ( is_search() ) {
529 $page_title = 'Search Results';
530 } elseif ( is_404() ) {
531 $page_title = 'Page Not Found';
532 }
533 }
534
535 $context_bits = array();
536 if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; }
537 if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; }
538 if ( $page_title ) { $context_bits[] = 'Page title: ' . $page_title; }
539 if ( $current_url ) { $context_bits[] = 'URL: ' . $current_url; }
540 if ( $page_summary ) { $context_bits[] = 'Page summary: ' . $page_summary; }
541
542 if ( ! empty( $context_bits ) ) {
543 $context_info = 'Context Information: ' . implode( '. ', $context_bits ) . '. Please use this context to provide more relevant and accurate responses.';
544 $system_content = $system_content . "\n\n" . $context_info;
545 }
546 }
547
548 $relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true);
549
550 if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){
551
552 $relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai');
553
554 if(is_array($relevant_post_link )){
555
556 $relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>';
557 }else{
558 $relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>';
559 }
560 }else{
561 $relevant_pagelinks = '';
562 }
563
564
565 array_push( $gptkeyword, array(
566 "role" => "system",
567 "content" => $system_content
568 ));
569 array_push($gptkeyword, array(
570 "role" => "user",
571 "content" => $keyword
572 ));
573 if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){
574 $prompts = $this->include_exclude_prompt($keyword);
575
576 $gptkeyword = [];
577 array_push($gptkeyword, array(
578 "role" => "user",
579 "content" => $prompts,
580 ));
581 }else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){
582 if($this->qcld_include_keyword_exist($keyword) == false){
583
584 $response['message'] = 'Sorry, No result found!';
585 echo wp_json_encode($response);
586 wp_die();
587 }else{
588 array_push($gptkeyword, array(
589 "role" => "user",
590 "content" => $keyword
591 ));
592 }
593
594 }
595 $res = $OpenAI->gptcomplete(
596 $gptkeyword
597 );
598 $mess = json_decode($res);
599 $Qcld_Parsedown = new Qcld_Parsedown();
600 $msg = $mess->output[0]->content[0]->text;
601 if( $msg == null || empty($msg) ){
602 $msg = $mess->output[1]->content[0]->text;
603 }
604 $msg = $Qcld_Parsedown->text($msg);
605
606 $response['message'] = $msg ;
607 if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){
608 $response['message'] = 'Sorry, No result found!';
609 }else{
610 $Qcld_Parsedown = new Qcld_Parsedown();
611 $msg = $mess->output[0]->content[0]->text;
612 if( $msg == null || empty($msg) ){
613 $msg = $mess->output[1]->content[0]->text;
614 }
615 $msg = $Qcld_Parsedown->text($msg);
616 $response['message'] = $msg . $relevant_pagelinks;
617 }
618
619 echo wp_json_encode($response);
620 wp_die();
621 //}
622 }
623 public function openai_settings_option_callback() {
624 $nonce = sanitize_text_field($_POST['nonce']);
625
626 if (! wp_verify_nonce($nonce,'wp_chatbot')) {
627 wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot')));
628 wp_die();
629
630 }else{
631
632 $api_key = sanitize_text_field($_POST['api_key']);
633 $openai_engines = sanitize_text_field($_POST['openai_engines']);
634
635 $qcld_openai_prompt = isset( $_POST['qcld_openai_prompt'] ) ? sanitize_text_field($_POST['qcld_openai_prompt']) : '';
636
637
638 $max_tokens = sanitize_text_field($_POST['max_tokens']);
639 $qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field($_POST['qcld_openai_suffix']) : '';
640
641 $qcld_openai_custom_model = isset( $_POST['qcld_openai_custom_model'] ) ? sanitize_text_field($_POST['qcld_openai_custom_model']) : '';
642
643
644
645 $frequency_penalty = sanitize_text_field($_POST['frequency_penalty']);
646 $presence_penalty = sanitize_text_field($_POST['presence_penalty']);
647 $temperature = sanitize_text_field($_POST['temperature']);
648 $ai_enabled = sanitize_text_field($_POST['ai_enabled']);
649 $suggestion_enabled = sanitize_text_field($_POST['is_page_suggestion_enabled']);
650 $context_awareness_enabled = sanitize_text_field($_POST['is_context_awareness_enabled']);
651
652
653
654 $is_relevant_enabled = sanitize_text_field($_POST['is_relevant_enabled']);
655 $file_id = (!empty($_POST['file_id'])) ? sanitize_text_field($_POST['file_id']) : '';
656
657 $qcld_openai_prompt_custom = isset( $_POST['qcld_openai_prompt_custom'] ) ? sanitize_text_field($_POST['qcld_openai_prompt_custom']) : '';
658
659 $openai_post_types = array();
660 if (isset($_POST['openai_post_type'])) {
661 $raw_post_types = wp_unslash($_POST['openai_post_type']);
662 if (is_array($raw_post_types)) {
663 $openai_post_types = array_map('sanitize_text_field', $raw_post_types);
664 } else {
665 $openai_post_types = sanitize_text_field($raw_post_types);
666 }
667 }
668 update_option('qcld_openai_relevant_post', $openai_post_types);
669
670 $conversation_continuity = sanitize_text_field($_POST['conversation_continuity']);
671 $qcld_openai_system_content = sanitize_text_field($_POST['qcld_openai_system_content']);
672 $qcld_openai_append_content = sanitize_text_field($_POST['qcld_openai_append_content']);
673
674 /* Customized by Kadir on 05-12-2023 : To set empty value for API field */
675 $disable_ss = isset( $_POST['disable_ss'] ) ? sanitize_text_field( $_POST['disable_ss'] ) : '';
676
677
678 if($api_key != ''){
679 update_option( 'open_ai_api_key', $api_key );
680 }
681 else{
682 delete_option( 'open_ai_api_key');
683 }
684
685 /* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */
686
687 if($openai_engines != ''){
688 update_option( 'openai_engines', $openai_engines );
689 }
690 if($conversation_continuity != ''){
691 update_option( 'conversation_continuity', $conversation_continuity );
692 }
693 update_option( 'openai_max_tokens', $max_tokens );
694
695 if($qcld_openai_suffix != ''){
696 update_option('qcld_openai_suffix', $qcld_openai_suffix);
697 }
698 if($frequency_penalty != ''){
699 update_option( 'frequency_penalty', $frequency_penalty );
700 }
701 if($presence_penalty != ''){
702 update_option( 'presence_penalty', $presence_penalty );
703 }
704 if($temperature != ''){
705 update_option( 'openai_temperature', $temperature );
706 }
707 if($qcld_openai_prompt_custom != ''){
708 update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom );
709 }
710 update_option('qcld_openai_custom_model',$qcld_openai_custom_model);
711 update_option( 'qcld_openai_system_content', stripslashes( $qcld_openai_system_content) );
712 update_option( 'qcld_openai_append_content', stripslashes( $qcld_openai_append_content) );
713
714 update_option('ai_enabled',$ai_enabled);
715 if( $ai_enabled == 1 ){
716
717 update_option('qcld_openrouter_enabled',0);
718 update_option('qcld_gemini_enabled',0);
719 }
720
721 update_option('qcld_openai_relevant_enabled',$is_relevant_enabled);
722 update_option('page_suggestion_enabled',$suggestion_enabled);
723 update_option('context_awareness_enabled',$context_awareness_enabled);
724
725
726 if($file_id != ''){
727 update_option('file_id',$file_id);
728 }
729 $openai_include_keyword = sanitize_text_field($_POST['openai_include_keyword']);
730 update_option('openai_include_keyword',$openai_include_keyword);
731 $openai_exclude_keyword = sanitize_text_field($_POST['openai_exclude_keyword']);
732 update_option('openai_exclude_keyword',$openai_exclude_keyword);
733
734
735 /* Customized by Kadir on 05-12-2023 : To Disable Site Search*/
736 //Disable Site Search
737 if( $disable_ss == 1 ){
738 update_option('disable_wp_chatbot_site_search',1);
739 update_option('enable_wp_chatbot_post_content', '');
740 }
741 /* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/
742
743
744
745 }
746 if($qcld_openai_prompt != ''){
747 update_option('qcld_openai_prompt', $qcld_openai_prompt);
748 }
749 $tem = get_option( 'openai_temperature', $temperature );
750
751 echo wp_json_encode($ai_enabled);wp_die();
752
753 }
754 public function qcld_update_settings_option_callback(){
755 update_option('disable_wp_chatbot_site_search',1);
756 update_option('enable_wp_chatbot_post_content', '');
757 }
758 public function qcpd_remove_wa_stopwords($query, $stopwords){
759
760 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
761
762 }
763 public function openai_troubleshooting() {
764 $nonce = sanitize_text_field( $_POST['nonce'] );
765 $OpenAI = new qcld_wp_OpenAI();
766 if ( ! wp_verify_nonce( $nonce, 'wp_chatbot' ) ) {
767 wp_send_json(
768 array(
769 'success' => false,
770 'msg' => esc_html__( 'Failed in Security check', 'chatbot' ),
771 )
772 );
773 wp_die();
774
775 } else {
776 $gptkeyword = array();
777 array_push(
778 $gptkeyword,
779 array(
780 'role' => 'user',
781 'content' => 'Is our request comes from openAI ?',
782 )
783 );
784 $res = $OpenAI->gptcomplete(
785 $gptkeyword
786 );
787
788 if ( empty( json_decode( $res )->error ) ) {
789 $mess = json_decode( $res );
790 $msg = preg_replace( "/\r\n|\r|\n/", '<br/>', $mess->output[0]->content[0]->text );
791 wp_send_json(
792 array(
793 'success' => true,
794 'title' => esc_html__( 'success', 'chatbot' ),
795 'icon' => esc_html__( 'success', 'chatbot' ),
796 'msg' => esc_html( $msg ),
797 )
798 );
799 } else {
800
801 wp_send_json(
802 array(
803 'success' => true,
804 'title' => esc_html__( 'Error', 'chatbot' ),
805 'icon' => esc_html__( 'error', 'chatbot' ),
806 'msg' => esc_html( json_decode( $res )->error->message ),
807 )
808 );
809 }
810 }
811 }
812
813
814 }
815
816 /**
817 * @return qcld_wpopenai_addon
818 */
819 if(!function_exists('qcld_wpopenai_addons')){
820 function qcld_openais() {
821 $qcld_wpopenai_addon = new qcld_wpopenai_addons();
822 return $qcld_wpopenai_addon->instance();
823
824 }
825 }
826
827 //fire off the plugin
828 qcld_openais();
829
830 }