| 1 |
<?php |
| 2 |
if (!defined('ABSPATH')) exit; // Exit if accessed directly |
| 3 |
|
| 4 |
if(!class_exists('qcld_wpopenai_addons')){ |
| 5 |
|
| 6 |
|
| 7 |
/** |
| 8 |
* Main Class. |
| 9 |
*/ |
| 10 |
final class qcld_wpopenai_addons |
| 11 |
{ |
| 12 |
private $id = 'Open AI'; |
| 13 |
|
| 14 |
/** |
| 15 |
* WPBot Pro version. |
| 16 |
* |
| 17 |
* @var string |
| 18 |
*/ |
| 19 |
public $version = '1.0.6'; |
| 20 |
|
| 21 |
/** |
| 22 |
* WPBot Pro helper. |
| 23 |
* |
| 24 |
* @var object |
| 25 |
*/ |
| 26 |
public $helper; |
| 27 |
|
| 28 |
/** |
| 29 |
* The single instance of the class. |
| 30 |
* |
| 31 |
* @var qcld_wb_Chatbot |
| 32 |
* @since 1.0.0 |
| 33 |
*/ |
| 34 |
protected static $_instance = null; |
| 35 |
|
| 36 |
/** |
| 37 |
* Main wpbot Instance. |
| 38 |
* |
| 39 |
* Ensures only one instance of wpbot is loaded or can be loaded. |
| 40 |
* |
| 41 |
* @return qcld_wb_Chatbot - Main instance. |
| 42 |
* @since 1.0.0 |
| 43 |
* @static |
| 44 |
*/ |
| 45 |
public static function instance() { |
| 46 |
if ( is_null( self::$_instance ) ) { |
| 47 |
self::$_instance = new self(); |
| 48 |
} |
| 49 |
|
| 50 |
return self::$_instance; |
| 51 |
} |
| 52 |
|
| 53 |
public $response_list; |
| 54 |
|
| 55 |
/** |
| 56 |
* Constructor |
| 57 |
*/ |
| 58 |
public function __construct() |
| 59 |
{ |
| 60 |
$this->define_constants(); |
| 61 |
$this->includes(); |
| 62 |
add_action('wp_ajax_openai_settings_option', [$this, 'openai_settings_option_callback']); |
| 63 |
add_action('wp_ajax_update_settings_option', [$this, 'qcld_update_settings_option_callback']); |
| 64 |
add_action('wp_ajax_qcld_rag_settings_option', array($this, 'rag_settings_option_callback')); |
| 65 |
add_action('wp_ajax_qcld_openai_response',[$this,'qcld_openai_response_callback']); |
| 66 |
add_action('wp_ajax_nopriv_qcld_openai_response', [$this, 'qcld_openai_response_callback']); |
| 67 |
add_action('wp_ajax_qcld_stream_openai', [$this, 'qcld_stream_openai_callback']); |
| 68 |
add_action('wp_ajax_nopriv_qcld_stream_openai', [$this, 'qcld_stream_openai_callback']); |
| 69 |
add_action('wp_ajax_openai_troubleshooting',[$this,'openai_troubleshooting']); |
| 70 |
add_action('wp_ajax_wpbot_wizard_save', array($this, 'wpbot_wizard_save_callback')); |
| 71 |
add_action('wp_ajax_wpbot_wizard_verify_key', array($this, 'wpbot_wizard_verify_key_callback')); |
| 72 |
if (is_admin() && !empty($_GET["page"]) && (($_GET["page"] == "openai-panel_dashboard") || ($_GET["page"] == "openai-panel_file") || ($_GET["page"] == "openai-panel_help"))) { |
| 73 |
add_action('admin_enqueue_scripts', array($this, 'qcld_wb_chatbot_admin_scripts')); |
| 74 |
} |
| 75 |
|
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
/** |
| 80 |
* Define wpbot Constants. |
| 81 |
* |
| 82 |
* @return void |
| 83 |
* @since 1.0.0 |
| 84 |
*/ |
| 85 |
public function define_constants() { |
| 86 |
if( ! defined( 'QCLD_openai_addon_VERSION' ) ){ |
| 87 |
define('QCLD_openai_addon_VERSION', $this->version); |
| 88 |
} |
| 89 |
//define('QCLD_openai_addon_REQUIRED_wpCOMMERCE_VERSION', 2.2); |
| 90 |
|
| 91 |
if( ! defined( 'QCLD_openai_addon_PLUGIN_DIR_PATH' ) ){ |
| 92 |
define('QCLD_openai_addon_PLUGIN_DIR_PATH', plugin_dir_path(__FILE__)); |
| 93 |
} |
| 94 |
if( ! defined( 'QCLD_openai_addon_PLUGIN_URL' ) ){ |
| 95 |
define('QCLD_openai_addon_PLUGIN_URL', plugin_dir_url(__FILE__)); |
| 96 |
} |
| 97 |
if( ! defined( 'QCLD_openai_addon_IMG_URL' ) ){ |
| 98 |
define('QCLD_openai_addon_IMG_URL', QCLD_openai_addon_PLUGIN_URL . "images/"); |
| 99 |
} |
| 100 |
if( ! defined( 'QCLD_openai_addon_IMG_ABSOLUTE_PATH' ) ){ |
| 101 |
define('QCLD_openai_addon_IMG_ABSOLUTE_PATH', plugin_dir_path(__FILE__) . "images"); |
| 102 |
} |
| 103 |
|
| 104 |
} |
| 105 |
|
| 106 |
|
| 107 |
public function qcld_wb_chatbot_admin_scripts(){ |
| 108 |
// wp_register_style('qlcd-open-ai-bootstap', QCLD_openai_addon_PLUGIN_URL . 'css/openai-bootstrap.css', '', QCLD_openai_addon_VERSION, 'screen'); |
| 109 |
// wp_enqueue_style('qlcd-open-ai-bootstap'); |
| 110 |
// wp_register_style('qlcd-open-ai-admin-style', QCLD_openai_addon_PLUGIN_URL . 'css/openai-admin-style.css', '', QCLD_openai_addon_VERSION, 'screen'); |
| 111 |
// wp_enqueue_style('qlcd-open-ai-admin-style'); |
| 112 |
// wp_register_script('qlcd-openai_collapse', QCLD_openai_addon_PLUGIN_URL . 'js/collapse.js', array('jquery'),'',QCLD_openai_addon_VERSION,true); |
| 113 |
// wp_enqueue_script('qlcd-openai_collapse'); |
| 114 |
// wp_register_script('qlcd-openai_settings', QCLD_openai_addon_PLUGIN_URL . 'js/openai_settings.js', array('jquery'),'',QCLD_openai_addon_VERSION,true); |
| 115 |
// wp_enqueue_script('qlcd-openai_settings'); |
| 116 |
|
| 117 |
// wp_localize_script( 'qlcd-openai_settings', 'openai_ajax', array( |
| 118 |
// 'url' => admin_url( 'admin-ajax.php' ), |
| 119 |
// ) ); |
| 120 |
|
| 121 |
} |
| 122 |
/** |
| 123 |
* Include all required files |
| 124 |
* |
| 125 |
* since 1.0.0 |
| 126 |
* |
| 127 |
* @return void |
| 128 |
*/ |
| 129 |
public function includes() { |
| 130 |
require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/integration/openai/qcld_wp_OpenAI.php" ); |
| 131 |
require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/integration/openai/OpenAi_WPBot_Menu.php" ); |
| 132 |
require_once( QCLD_wpCHATBOT_PLUGIN_DIR_PATH . "includes/Parsedown.php" ); |
| 133 |
|
| 134 |
} |
| 135 |
|
| 136 |
|
| 137 |
public function buildFormBody( $fields, $boundary ) |
| 138 |
{ |
| 139 |
$body = ''; |
| 140 |
foreach ( $fields as $name => $value ) { |
| 141 |
if ( $name == 'data' ) { |
| 142 |
continue; |
| 143 |
} |
| 144 |
$body .= "--$boundary\r\n"; |
| 145 |
$body .= "Content-Disposition: form-data; name=\"$name\""; |
| 146 |
if ( $name == 'file' ) { |
| 147 |
$body .= "; filename=\"{$value}\"\r\n"; |
| 148 |
$body .= "Content-Type: application/json\r\n\r\n"; |
| 149 |
$body .= $fields['data'] . "\r\n"; |
| 150 |
}else { |
| 151 |
$body .= "\r\n\r\n$value\r\n"; |
| 152 |
} |
| 153 |
} |
| 154 |
$body .= "--$boundary--\r\n"; |
| 155 |
return $body; |
| 156 |
} |
| 157 |
|
| 158 |
// public function openai_file_list_callback(){ |
| 159 |
// $url = 'https://api.openai.com/v1/files'; |
| 160 |
// $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key'); |
| 161 |
// $curl = curl_init(); |
| 162 |
// curl_setopt($curl, CURLOPT_URL, $url); |
| 163 |
// $headers = array( |
| 164 |
// "Content-Type: application/json", |
| 165 |
// $apt_key, |
| 166 |
// ); |
| 167 |
// curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); |
| 168 |
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
| 169 |
// $response = curl_exec($curl); |
| 170 |
// curl_close($curl); |
| 171 |
// wp_send_json( json_decode($response)); |
| 172 |
// wp_die(); |
| 173 |
// } |
| 174 |
public function qcld_sanitize_text_or_array_field($array_or_string) { |
| 175 |
if( is_string($array_or_string) ){ |
| 176 |
$array_or_string = sanitize_text_field($array_or_string); |
| 177 |
}elseif( is_array($array_or_string) ){ |
| 178 |
foreach ( $array_or_string as $key => &$value ) { |
| 179 |
if ( is_array( $value ) ) { |
| 180 |
$value = $this->qcld_sanitize_text_or_array_field($value); |
| 181 |
} |
| 182 |
else { |
| 183 |
$value = sanitize_text_field( $value ); |
| 184 |
} |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
return $array_or_string; |
| 189 |
} |
| 190 |
|
| 191 |
// public function openai_file_upload_callback(){ |
| 192 |
// $uploadedfile = $_FILES['file']; |
| 193 |
// $url = 'https://api.openai.com/v1/files'; |
| 194 |
// $apt_key = "Authorization: Bearer ". get_option('open_ai_api_key'); |
| 195 |
// $curl = curl_init($url); |
| 196 |
// curl_setopt($curl, CURLOPT_URL, $url); |
| 197 |
// curl_setopt($curl, CURLOPT_POST, true); |
| 198 |
// $headers = array( |
| 199 |
// "Content-Type: multipart/form-data", |
| 200 |
// $apt_key, |
| 201 |
// ); |
| 202 |
// if (function_exists('curl_file_create')) { |
| 203 |
// $tmp_file = curl_file_create($uploadedfile['tmp_name'], 'jsonl', $uploadedfile['name']); |
| 204 |
// } else { |
| 205 |
// $tmp_file = open($uploadedfile['tmp_name']); |
| 206 |
// } |
| 207 |
// $data = array('file'=> $tmp_file,'purpose'=> 'fine-tune'); |
| 208 |
// $init = curl_init(); |
| 209 |
// //function parameteres |
| 210 |
// curl_setopt($init, CURLOPT_URL,$url); |
| 211 |
// curl_setopt($init, CURLOPT_HTTPHEADER, $headers); |
| 212 |
// curl_setopt($init, CURLOPT_POSTFIELDS, $data); |
| 213 |
// curl_setopt($init, CURLOPT_RETURNTRANSFER, true); |
| 214 |
// $res = json_decode(curl_exec ($init)); |
| 215 |
|
| 216 |
// curl_close ($init); |
| 217 |
// if(!empty($res->error)){ |
| 218 |
// $response['status'] = 'error'; |
| 219 |
// $response['message'] = $res->error->message; |
| 220 |
// } |
| 221 |
|
| 222 |
// if(!empty($res->status)){ |
| 223 |
// $response['status'] = 'success'; |
| 224 |
// $response['message'] = 'Successfully Created file' . $res->id ; |
| 225 |
|
| 226 |
// } |
| 227 |
// echo wp_send_json([$response]); |
| 228 |
// wp_die(); |
| 229 |
// } |
| 230 |
|
| 231 |
public function openai_finetune_create($file_id,$ft_suffix,$ft_engines){ |
| 232 |
$api_key = get_option('open_ai_api_key'); |
| 233 |
$request_headers = array( |
| 234 |
'Content-Type' => 'application/json', |
| 235 |
'Authorization' => 'Bearer ' . $api_key, |
| 236 |
); |
| 237 |
$qcld_openai_suffix = isset($ft_suffix) ? $ft_suffix : get_option('qcld_openai_suffix'); |
| 238 |
$openai_engines = isset($ft_engines) ? $ft_engines : get_option('openai_engines'); |
| 239 |
$base_engine = explode('-',$openai_engines); |
| 240 |
if( $base_engine[0] == 'gpt'){ |
| 241 |
$url = "https://api.openai.com/v1/fine_tuning/jobs"; |
| 242 |
$response = wp_remote_post( $url, array( |
| 243 |
'headers' => $request_headers, |
| 244 |
'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $openai_engines, 'suffix' => $qcld_openai_suffix ) ), |
| 245 |
'timeout' => 60, |
| 246 |
) ); |
| 247 |
$result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null; |
| 248 |
}else{ |
| 249 |
$url = "https://api.openai.com/v1/fine-tunes"; |
| 250 |
$response = wp_remote_post( $url, array( |
| 251 |
'headers' => $request_headers, |
| 252 |
'body' => wp_json_encode( array('training_file'=>$file_id,'model' => $base_engine[1], 'suffix' => $qcld_openai_suffix ) ), |
| 253 |
'timeout' => 60, |
| 254 |
) ); |
| 255 |
$result = ! is_wp_error( $response ) ? json_decode( wp_remote_retrieve_body( $response ) ) : null; |
| 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 |
$api_key = get_option('open_ai_api_key'); |
| 302 |
$request_headers = array( |
| 303 |
'Content-Type' => 'application/json', |
| 304 |
'Authorization' => 'Bearer ' . $api_key, |
| 305 |
); |
| 306 |
$max_tokens = (int)get_option( 'openai_max_tokens'); |
| 307 |
$temp = (float)get_option( 'openai_temperature'); |
| 308 |
$frequency_penalty= (float)get_option( 'frequency_penalty'); |
| 309 |
$presence_penalty = (float)get_option( 'presence_penalty'); |
| 310 |
$custom_model = get_option( 'qcld_openai_custom_model'); |
| 311 |
$custom_model = explode(":", $custom_model); |
| 312 |
$prompts = $this->get_prompt($keyword); |
| 313 |
|
| 314 |
if ( isset( $custom_model[1] ) && $custom_model[1] !== 'gpt-3.5-turbo-0613' ) { |
| 315 |
$response = wp_remote_post( 'https://api.openai.com/v1/completions', array( |
| 316 |
'headers' => $request_headers, |
| 317 |
'body' => wp_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 |
'timeout' => 60, |
| 329 |
) ); |
| 330 |
if ( is_wp_error( $response ) ) { return ''; } |
| 331 |
$result = str_replace( "#", "", wp_remote_retrieve_body( $response ) ); |
| 332 |
return $result; |
| 333 |
} else { |
| 334 |
$response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array( |
| 335 |
'headers' => $request_headers, |
| 336 |
'body' => wp_json_encode( array( |
| 337 |
'model' => get_option( 'qcld_openai_custom_model'), |
| 338 |
'messages' => [ [ 'role' => 'user', 'content' => $keyword ] ], |
| 339 |
) ), |
| 340 |
'timeout' => 60, |
| 341 |
) ); |
| 342 |
if ( is_wp_error( $response ) ) { return ''; } |
| 343 |
$results = str_replace( "#", "", wp_remote_retrieve_body( $response ) ); |
| 344 |
$decoded = json_decode( $results ); |
| 345 |
return isset( $decoded->choices[0]->message->content ) ? $decoded->choices[0]->message->content : ''; |
| 346 |
} |
| 347 |
} |
| 348 |
public function response_form_file($keyword){ |
| 349 |
$max_tokens = (int)get_option( 'openai_max_tokens'); |
| 350 |
$temp = (float)get_option( 'openai_temperature'); |
| 351 |
$frequency_penalty = (float)get_option( 'frequency_penalty'); |
| 352 |
$presence_penalty = (float)get_option( 'presence_penalty'); |
| 353 |
$engines = explode('-',get_option( 'openai_engines')); |
| 354 |
if($engines[0] != 'gpt'){ |
| 355 |
// $prompts = $this->get_prompt($keyword); |
| 356 |
} |
| 357 |
|
| 358 |
$request_body = [ |
| 359 |
"prompt" => $keyword, |
| 360 |
"model" => get_option( 'qcld_openai_custom_model'), |
| 361 |
"max_tokens" => $max_tokens, |
| 362 |
"temperature" => 0, |
| 363 |
"top_p" => 1, |
| 364 |
"stop" => [], |
| 365 |
"presence_penalty" => 0, |
| 366 |
"frequency_penalty"=> 0, |
| 367 |
"best_of"=> 1, |
| 368 |
]; |
| 369 |
$postFields = wp_json_encode($request_body); |
| 370 |
$OpenAI = new qcld_wp_OpenAI(); |
| 371 |
$result = $OpenAI->get_response($postFields); |
| 372 |
|
| 373 |
return $result; |
| 374 |
} |
| 375 |
public function get_prompt($keyword){ |
| 376 |
$openai_include_keyword = get_option( 'openai_include_keyword'); |
| 377 |
$openai_exclude_keyword = get_option( 'openai_exclude_keyword'); |
| 378 |
$qcld_openai_prompt = get_option('qcld_openai_prompt',true); |
| 379 |
|
| 380 |
} |
| 381 |
public function include_exclude_prompt($keyword){ |
| 382 |
$openai_include_keyword = strtolower(get_option('openai_include_keyword')); |
| 383 |
$openai_exclude_keyword = strtolower(get_option('openai_exclude_keyword')); |
| 384 |
|
| 385 |
if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') == '')){ |
| 386 |
$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; |
| 387 |
return $prompts; |
| 388 |
}else if((get_option('openai_include_keyword') == '') || (get_option('openai_exclude_keyword') != '')){ |
| 389 |
|
| 390 |
$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'; |
| 391 |
return $prompts; |
| 392 |
}else if((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')){ |
| 393 |
$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; |
| 394 |
return $prompts; |
| 395 |
} |
| 396 |
} |
| 397 |
public function qcld_include_keyword_exist( $keyword ){ |
| 398 |
$keyword = isset($keyword) ? $keyword : ''; |
| 399 |
$openai_include_keywords = strtolower(get_option('openai_include_keyword')); |
| 400 |
if(!empty($keyword)){ |
| 401 |
$openai_include_keyword = ( isset( $openai_include_keywords ) ? $openai_include_keywords : ''); |
| 402 |
|
| 403 |
if( !empty($openai_include_keyword)){ |
| 404 |
$include_items = explode(',', $openai_include_keyword); |
| 405 |
if(!empty($include_items)){ |
| 406 |
foreach($include_items as $k => $item){ |
| 407 |
if((strpos($keyword,trim($item)) !== false) && !empty($item)){ |
| 408 |
return true; |
| 409 |
} |
| 410 |
} |
| 411 |
} |
| 412 |
return false; |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
return false; |
| 417 |
|
| 418 |
} |
| 419 |
|
| 420 |
public function qcld_stream_openai_callback() { |
| 421 |
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_chatbot' ) ) { |
| 422 |
echo "data: [ERROR] Security check failed.\n\n"; |
| 423 |
flush(); |
| 424 |
wp_die(); |
| 425 |
} |
| 426 |
if ( get_option( 'is_rate_limiting_enabled' ) == '1' ) { |
| 427 |
do_action( 'rate_limit_checker' ); |
| 428 |
} |
| 429 |
|
| 430 |
if ( function_exists( 'apache_setenv' ) ) { |
| 431 |
@apache_setenv( 'no-gzip', 1 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged |
| 432 |
} |
| 433 |
@ini_set( 'zlib.output_compression', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged |
| 434 |
@ini_set( 'implicit_flush', 1 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged |
| 435 |
while ( ob_get_level() ) { |
| 436 |
ob_end_clean(); |
| 437 |
} |
| 438 |
ob_implicit_flush( 1 ); |
| 439 |
|
| 440 |
header( 'Content-Type: text/event-stream' ); |
| 441 |
header( 'Cache-Control: no-cache' ); |
| 442 |
header( 'Connection: keep-alive' ); |
| 443 |
|
| 444 |
$api_key = trim( get_option( 'open_ai_api_key' ) ); |
| 445 |
$keyword = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : ''; |
| 446 |
|
| 447 |
if ( empty( $api_key ) || empty( $keyword ) ) { |
| 448 |
echo "data: [ERROR] Missing API key or message.\n\n"; |
| 449 |
flush(); |
| 450 |
wp_die(); |
| 451 |
} |
| 452 |
|
| 453 |
$system_content = get_option( 'qcld_openai_system_content', 'You are a helpful assistant.' ); |
| 454 |
|
| 455 |
// RAG integration |
| 456 |
if ( get_option( 'is_page_rag_enabled' ) == '1' ) { |
| 457 |
if ( class_exists( 'Qcld_Bot_Rag' ) ) { |
| 458 |
$rag_context_text = Qcld_Bot_Rag::instance()->run_rag_search( $keyword ); |
| 459 |
if ( ! empty( $rag_context_text ) && $rag_context_text !== 'No knowledge base found.' ) { |
| 460 |
$system_content .= "\n\nRelevant Knowledge Base:\n" . $rag_context_text; |
| 461 |
} |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
// Context awareness |
| 466 |
if ( get_option( 'context_awareness_enabled' ) == '1' ) { |
| 467 |
$site_name = get_bloginfo( 'name' ); |
| 468 |
$site_desc = get_bloginfo( 'description' ); |
| 469 |
$context_bits = []; |
| 470 |
if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; } |
| 471 |
if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; } |
| 472 |
$ref = wp_get_referer(); |
| 473 |
if ( ! $ref && isset( $_SERVER['HTTP_REFERER'] ) ) { |
| 474 |
$ref = esc_url_raw( $_SERVER['HTTP_REFERER'] ); |
| 475 |
} |
| 476 |
if ( $ref ) { |
| 477 |
$context_bits[] = 'URL: ' . $ref; |
| 478 |
$post_id = url_to_postid( $ref ); |
| 479 |
if ( $post_id ) { |
| 480 |
$context_bits[] = 'Page title: ' . get_the_title( $post_id ); |
| 481 |
} |
| 482 |
} |
| 483 |
if ( ! empty( $context_bits ) ) { |
| 484 |
$system_content .= "\n\nContext: " . implode( '. ', $context_bits ); |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
$model = get_option( 'qcld_openai_custom_model' ); |
| 489 |
if ( empty( $model ) ) { |
| 490 |
$model = get_option( 'openai_engines', 'gpt-4o' ); |
| 491 |
} |
| 492 |
|
| 493 |
$messages = [ |
| 494 |
[ 'role' => 'system', 'content' => $system_content ], |
| 495 |
[ 'role' => 'user', 'content' => $keyword ], |
| 496 |
]; |
| 497 |
|
| 498 |
$headers = [ |
| 499 |
'Content-Type: application/json', |
| 500 |
'Authorization: Bearer ' . $api_key, |
| 501 |
]; |
| 502 |
|
| 503 |
$post_data = wp_json_encode( [ |
| 504 |
'model' => $model, |
| 505 |
'messages' => $messages, |
| 506 |
'stream' => true, |
| 507 |
] ); |
| 508 |
|
| 509 |
$ch = curl_init( 'https://api.openai.com/v1/chat/completions' ); |
| 510 |
curl_setopt( $ch, CURLOPT_POST, true ); |
| 511 |
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); |
| 512 |
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data ); |
| 513 |
curl_setopt( $ch, CURLOPT_WRITEFUNCTION, function ( $ch, $chunk ) { |
| 514 |
echo $chunk; |
| 515 |
echo str_repeat( ' ', 1024 ); |
| 516 |
flush(); |
| 517 |
return strlen( $chunk ); |
| 518 |
} ); |
| 519 |
curl_exec( $ch ); |
| 520 |
if ( curl_errno( $ch ) ) { |
| 521 |
echo 'data: [ERROR] ' . curl_error( $ch ) . "\n\n"; |
| 522 |
flush(); |
| 523 |
} |
| 524 |
curl_close( $ch ); |
| 525 |
do_action( 'qcld_openai_user_rate_cal', 1 ); |
| 526 |
exit; |
| 527 |
} |
| 528 |
|
| 529 |
public function qcld_openai_response_callback() { |
| 530 |
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_chatbot' ) ) { |
| 531 |
wp_send_json_error([ |
| 532 |
'status' => 'error', |
| 533 |
'message' => esc_html__( 'Security check failed. Unauthorized request.', 'chatbot' ) |
| 534 |
]); |
| 535 |
wp_die(); |
| 536 |
} |
| 537 |
if (get_option('is_rate_limiting_enabled') == '1') { |
| 538 |
do_action('rate_limit_checker'); |
| 539 |
} |
| 540 |
$response['status'] = 'success'; |
| 541 |
$response['message'] ='A preset message'; |
| 542 |
$OpenAI = new qcld_wp_OpenAI(); |
| 543 |
$gptkeyword = []; |
| 544 |
$keyword = sanitize_text_field(wp_unslash($_POST['keyword'])); |
| 545 |
$relevant_pagelink = $this->relevant_pagelink($keyword); |
| 546 |
|
| 547 |
// Build context-aware system instructions |
| 548 |
$system_content = get_option('qcld_openai_system_content'); |
| 549 |
|
| 550 |
// RAG Integration |
| 551 |
if (get_option('is_page_rag_enabled') == '1') { |
| 552 |
$rag_context_text = Qcld_Bot_Rag::instance()->run_rag_search($keyword); |
| 553 |
if (!empty($rag_context_text) && $rag_context_text != "No knowledge base found.") { |
| 554 |
$rag_context = "Relevant Knowledge Base Information:\n"; |
| 555 |
$rag_context .= $rag_context_text; |
| 556 |
$rag_context .= "\n\nUse the above information to answer the user's question. If the answer is not in the Knowledge Base, rely on your general knowledge but mention that this information is not in the local knowledge base."; |
| 557 |
$system_content .= "\n\n" . $rag_context; |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
if ( get_option('context_awareness_enabled') == '1' ) { |
| 562 |
$site_name = get_bloginfo('name'); |
| 563 |
$site_desc = get_bloginfo('description'); |
| 564 |
|
| 565 |
// Get current page URL and title more reliably |
| 566 |
$current_url = ''; |
| 567 |
$page_title = ''; |
| 568 |
$page_summary = ''; |
| 569 |
|
| 570 |
// Try to get from referrer first |
| 571 |
$ref = wp_get_referer(); |
| 572 |
if ( ! $ref && isset($_SERVER['HTTP_REFERER']) ) { |
| 573 |
$ref = esc_url_raw( $_SERVER['HTTP_REFERER'] ); |
| 574 |
} |
| 575 |
|
| 576 |
if ( $ref ) { |
| 577 |
$current_url = $ref; |
| 578 |
|
| 579 |
// Try to get post/page by URL |
| 580 |
$post_id = url_to_postid( $ref ); |
| 581 |
if ( $post_id ) { |
| 582 |
$page_title = get_the_title( $post_id ); |
| 583 |
$raw_content = get_post_field( 'post_content', $post_id ); |
| 584 |
$text_content = wp_strip_all_tags( $raw_content ); |
| 585 |
$page_summary = wp_trim_words( $text_content, 120, '…' ); |
| 586 |
} else { |
| 587 |
// If not a post/page, try to extract title from URL or use current page |
| 588 |
$parsed_url = wp_parse_url( $ref ); |
| 589 |
if ( isset($parsed_url['path']) ) { |
| 590 |
$path = trim($parsed_url['path'], '/'); |
| 591 |
if ( ! empty($path) ) { |
| 592 |
// Try to get title from current page if we're on it |
| 593 |
if ( is_singular() ) { |
| 594 |
$page_title = get_the_title(); |
| 595 |
$raw_content = get_the_content(); |
| 596 |
$text_content = wp_strip_all_tags( $raw_content ); |
| 597 |
$page_summary = wp_trim_words( $text_content, 120, '…' ); |
| 598 |
} elseif ( is_archive() ) { |
| 599 |
$page_title = get_the_archive_title(); |
| 600 |
} elseif ( is_search() ) { |
| 601 |
$page_title = 'Search Results'; |
| 602 |
} elseif ( is_404() ) { |
| 603 |
$page_title = 'Page Not Found'; |
| 604 |
} |
| 605 |
} |
| 606 |
} |
| 607 |
} |
| 608 |
} else { |
| 609 |
// Fallback to current page info. |
| 610 |
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"); |
| 611 |
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; |
| 612 |
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; |
| 613 |
$current_url = esc_url_raw($scheme . '://' . $host . $request_uri); |
| 614 |
|
| 615 |
if ( is_singular() ) { |
| 616 |
$page_title = get_the_title(); |
| 617 |
$raw_content = get_the_content(); |
| 618 |
$text_content = wp_strip_all_tags( $raw_content ); |
| 619 |
$page_summary = wp_trim_words( $text_content, 120, '…' ); |
| 620 |
} elseif ( is_archive() ) { |
| 621 |
$page_title = get_the_archive_title(); |
| 622 |
} elseif ( is_search() ) { |
| 623 |
$page_title = 'Search Results'; |
| 624 |
} elseif ( is_404() ) { |
| 625 |
$page_title = 'Page Not Found'; |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
$context_bits = array(); |
| 630 |
if ( $site_name ) { $context_bits[] = 'Site: ' . $site_name; } |
| 631 |
if ( $site_desc ) { $context_bits[] = 'Tagline: ' . $site_desc; } |
| 632 |
if ( $page_title ) { $context_bits[] = 'Page title: ' . $page_title; } |
| 633 |
if ( $current_url ) { $context_bits[] = 'URL: ' . $current_url; } |
| 634 |
if ( $page_summary ) { $context_bits[] = 'Page summary: ' . $page_summary; } |
| 635 |
|
| 636 |
if ( ! empty( $context_bits ) ) { |
| 637 |
$context_info = 'Context Information: ' . implode( '. ', $context_bits ) . '. Please use this context to provide more relevant and accurate responses.'; |
| 638 |
$system_content = $system_content . "\n\n" . $context_info; |
| 639 |
} |
| 640 |
} |
| 641 |
|
| 642 |
$relevant_pagelink = array_slice($relevant_pagelink, 0, 5, true); |
| 643 |
|
| 644 |
if( (get_option('page_suggestion_enabled') == '1') && count($relevant_pagelink) > 0 ){ |
| 645 |
|
| 646 |
$relevant_post_link = get_option('qlcd_wp_chatbot_relevant_post_link_openai'); |
| 647 |
|
| 648 |
if(is_array($relevant_post_link )){ |
| 649 |
|
| 650 |
$relevant_pagelinks = '<br><br><p><em>'. implode('', $relevant_post_link) .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink). '</ul>'; |
| 651 |
}else{ |
| 652 |
$relevant_pagelinks = '<br><br><p><em>'. $relevant_post_link .'</em></p><ul style="list-style: disc;padding-left: 10px;">'. implode(" ", $relevant_pagelink) .'</ul>'; |
| 653 |
} |
| 654 |
}else{ |
| 655 |
$relevant_pagelinks = ''; |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
array_push( $gptkeyword, array( |
| 660 |
"role" => "system", |
| 661 |
"content" => $system_content |
| 662 |
)); |
| 663 |
array_push($gptkeyword, array( |
| 664 |
"role" => "user", |
| 665 |
"content" => $keyword |
| 666 |
)); |
| 667 |
if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '1') ){ |
| 668 |
$prompts = $this->include_exclude_prompt($keyword); |
| 669 |
|
| 670 |
$gptkeyword = []; |
| 671 |
array_push($gptkeyword, array( |
| 672 |
"role" => "user", |
| 673 |
"content" => $prompts, |
| 674 |
)); |
| 675 |
}else if(((get_option('openai_include_keyword') != '') || (get_option('openai_exclude_keyword') != '')) && (get_option('qcld_openai_relevant_enabled') == '0')){ |
| 676 |
if($this->qcld_include_keyword_exist($keyword) == false){ |
| 677 |
|
| 678 |
$response['message'] = 'Sorry, No result found!'; |
| 679 |
wp_send_json( $response ); |
| 680 |
}else{ |
| 681 |
array_push($gptkeyword, array( |
| 682 |
"role" => "user", |
| 683 |
"content" => $keyword |
| 684 |
)); |
| 685 |
} |
| 686 |
|
| 687 |
} |
| 688 |
$res = $OpenAI->gptcomplete( |
| 689 |
$gptkeyword |
| 690 |
); |
| 691 |
$mess = json_decode($res); |
| 692 |
$Qcld_Parsedown = new Qcld_Parsedown(); |
| 693 |
$msg = $mess->output[0]->content[0]->text; |
| 694 |
if( $msg == null || empty($msg) ){ |
| 695 |
$msg = $mess->output[1]->content[0]->text; |
| 696 |
} |
| 697 |
$msg = $Qcld_Parsedown->text($msg); |
| 698 |
|
| 699 |
$response['message'] = $msg ; |
| 700 |
if(($response['message'] == 'DUH.') || ($response['message'] == 'DUH')){ |
| 701 |
$response['message'] = 'Sorry, No result found!'; |
| 702 |
}else{ |
| 703 |
$Qcld_Parsedown = new Qcld_Parsedown(); |
| 704 |
$msg = $mess->output[0]->content[0]->text; |
| 705 |
if( $msg == null || empty($msg) ){ |
| 706 |
$msg = $mess->output[1]->content[0]->text; |
| 707 |
} |
| 708 |
$msg = $Qcld_Parsedown->text($msg); |
| 709 |
$response['message'] = $msg . $relevant_pagelinks; |
| 710 |
} |
| 711 |
do_action('qcld_openai_user_rate_cal', 1); |
| 712 |
wp_send_json( $response ); |
| 713 |
//} |
| 714 |
} |
| 715 |
public function openai_settings_option_callback() { |
| 716 |
$nonce = sanitize_text_field(wp_unslash($_POST['nonce'])); |
| 717 |
|
| 718 |
if (! wp_verify_nonce($nonce,'wp_chatbot') || ! current_user_can('manage_options')) { |
| 719 |
wp_send_json(array('success' => false, 'msg' => esc_html__('Failed in Security check', 'chatbot'))); |
| 720 |
wp_die(); |
| 721 |
|
| 722 |
}else{ |
| 723 |
|
| 724 |
$api_key = sanitize_text_field(wp_unslash($_POST['api_key'])); |
| 725 |
$openai_engines = sanitize_text_field(wp_unslash($_POST['openai_engines'])); |
| 726 |
|
| 727 |
$qcld_openai_prompt = isset( $_POST['qcld_openai_prompt'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt'])) : ''; |
| 728 |
|
| 729 |
|
| 730 |
$max_tokens = sanitize_text_field(wp_unslash($_POST['max_tokens'])); |
| 731 |
$qcld_openai_suffix = (!empty($_POST['qcld_openai_suffix'])) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_suffix'])) : ''; |
| 732 |
|
| 733 |
$qcld_openai_custom_model = isset( $_POST['qcld_openai_custom_model'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_custom_model'])) : ''; |
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
$frequency_penalty = sanitize_text_field(wp_unslash($_POST['frequency_penalty'])); |
| 738 |
$presence_penalty = sanitize_text_field(wp_unslash($_POST['presence_penalty'])); |
| 739 |
$temperature = sanitize_text_field(wp_unslash($_POST['temperature'])); |
| 740 |
$ai_enabled = sanitize_text_field(wp_unslash($_POST['ai_enabled'])); |
| 741 |
$suggestion_enabled = sanitize_text_field(wp_unslash($_POST['is_page_suggestion_enabled'])); |
| 742 |
$context_awareness_enabled = sanitize_text_field(wp_unslash($_POST['is_context_awareness_enabled'])); |
| 743 |
$is_page_rag_enabled = sanitize_text_field(wp_unslash($_POST['is_page_rag_enabled'])); |
| 744 |
$is_stream_enabled = isset($_POST['is_stream_enabled']) ? sanitize_text_field(wp_unslash($_POST['is_stream_enabled'])) : '0'; |
| 745 |
|
| 746 |
$is_relevant_enabled = sanitize_text_field(wp_unslash($_POST['is_relevant_enabled'])); |
| 747 |
$file_id = (!empty($_POST['file_id'])) ? sanitize_text_field(wp_unslash($_POST['file_id'])) : ''; |
| 748 |
|
| 749 |
$qcld_openai_prompt_custom = isset( $_POST['qcld_openai_prompt_custom'] ) ? sanitize_text_field(wp_unslash($_POST['qcld_openai_prompt_custom'])) : ''; |
| 750 |
|
| 751 |
$openai_post_types = array(); |
| 752 |
if (isset($_POST['openai_post_type'])) { |
| 753 |
$raw_post_types = wp_unslash($_POST['openai_post_type']); |
| 754 |
if (is_array($raw_post_types)) { |
| 755 |
$openai_post_types = array_map('sanitize_text_field', $raw_post_types); |
| 756 |
} else { |
| 757 |
$openai_post_types = sanitize_text_field($raw_post_types); |
| 758 |
} |
| 759 |
} |
| 760 |
update_option('qcld_openai_relevant_post', $openai_post_types); |
| 761 |
|
| 762 |
$conversation_continuity = sanitize_text_field(wp_unslash($_POST['conversation_continuity'])); |
| 763 |
$qcld_openai_system_content = sanitize_text_field(wp_unslash($_POST['qcld_openai_system_content'])); |
| 764 |
$qcld_openai_append_content = sanitize_text_field(wp_unslash($_POST['qcld_openai_append_content'])); |
| 765 |
|
| 766 |
/* Customized by Kadir on 05-12-2023 : To set empty value for API field */ |
| 767 |
$disable_ss = isset( $_POST['disable_ss'] ) ? sanitize_text_field(wp_unslash($_POST['disable_ss'])) : ''; |
| 768 |
|
| 769 |
|
| 770 |
if($api_key != ''){ |
| 771 |
update_option( 'open_ai_api_key', $api_key ); |
| 772 |
} |
| 773 |
else{ |
| 774 |
delete_option( 'open_ai_api_key'); |
| 775 |
} |
| 776 |
|
| 777 |
/* Ends: Customized by Kadir on 05-12-2023 : To set empty value for API field */ |
| 778 |
|
| 779 |
if($openai_engines != ''){ |
| 780 |
update_option( 'openai_engines', $openai_engines ); |
| 781 |
} |
| 782 |
if($conversation_continuity != ''){ |
| 783 |
update_option( 'conversation_continuity', $conversation_continuity ); |
| 784 |
} |
| 785 |
update_option( 'openai_max_tokens', $max_tokens ); |
| 786 |
|
| 787 |
if($qcld_openai_suffix != ''){ |
| 788 |
update_option('qcld_openai_suffix', $qcld_openai_suffix); |
| 789 |
} |
| 790 |
if($frequency_penalty != ''){ |
| 791 |
update_option( 'frequency_penalty', $frequency_penalty ); |
| 792 |
} |
| 793 |
if($presence_penalty != ''){ |
| 794 |
update_option( 'presence_penalty', $presence_penalty ); |
| 795 |
} |
| 796 |
if($temperature != ''){ |
| 797 |
update_option( 'openai_temperature', $temperature ); |
| 798 |
} |
| 799 |
if($qcld_openai_prompt_custom != ''){ |
| 800 |
update_option('qcld_openai_prompt_custom', $qcld_openai_prompt_custom ); |
| 801 |
} |
| 802 |
update_option('qcld_openai_custom_model',$qcld_openai_custom_model); |
| 803 |
update_option( 'qcld_openai_system_content', stripslashes( $qcld_openai_system_content) ); |
| 804 |
update_option( 'qcld_openai_append_content', stripslashes( $qcld_openai_append_content) ); |
| 805 |
|
| 806 |
update_option('ai_enabled',$ai_enabled); |
| 807 |
update_option('is_stream_enabled', $is_stream_enabled); |
| 808 |
if( $ai_enabled == 1 ){ |
| 809 |
|
| 810 |
update_option('qcld_openrouter_enabled',0); |
| 811 |
update_option('qcld_gemini_enabled',0); |
| 812 |
} |
| 813 |
|
| 814 |
update_option('qcld_openai_relevant_enabled',$is_relevant_enabled); |
| 815 |
update_option('page_suggestion_enabled',$suggestion_enabled); |
| 816 |
update_option('context_awareness_enabled',$context_awareness_enabled); |
| 817 |
update_option('is_page_rag_enabled',$is_page_rag_enabled); |
| 818 |
|
| 819 |
|
| 820 |
if($file_id != ''){ |
| 821 |
update_option('file_id',$file_id); |
| 822 |
} |
| 823 |
$openai_include_keyword = sanitize_text_field(wp_unslash($_POST['openai_include_keyword'])); |
| 824 |
update_option('openai_include_keyword',$openai_include_keyword); |
| 825 |
$openai_exclude_keyword = sanitize_text_field(wp_unslash($_POST['openai_exclude_keyword'])); |
| 826 |
update_option('openai_exclude_keyword',$openai_exclude_keyword); |
| 827 |
|
| 828 |
|
| 829 |
/* Customized by Kadir on 05-12-2023 : To Disable Site Search*/ |
| 830 |
//Disable Site Search |
| 831 |
if( $disable_ss == 1 ){ |
| 832 |
update_option('disable_wp_chatbot_site_search',1); |
| 833 |
update_option('enable_wp_chatbot_post_content', ''); |
| 834 |
} |
| 835 |
/* Ends: Customized by Kadir on 05-12-2023 : To Disable Site Search*/ |
| 836 |
if($qcld_openai_prompt != ''){ |
| 837 |
update_option('qcld_openai_prompt', $qcld_openai_prompt); |
| 838 |
} |
| 839 |
} |
| 840 |
$OpenAI = new qcld_wp_OpenAI(); |
| 841 |
$gptkeyword = array(); |
| 842 |
array_push( |
| 843 |
$gptkeyword, |
| 844 |
array( |
| 845 |
'role' => 'user', |
| 846 |
'content' => 'If you get this query respond in plain text: "Congrats! You are connected to AI."', |
| 847 |
) |
| 848 |
); |
| 849 |
$res = $OpenAI->gptcomplete( |
| 850 |
$gptkeyword |
| 851 |
); |
| 852 |
|
| 853 |
if ( empty( json_decode( $res )->error ) ) { |
| 854 |
$mess = json_decode( $res ); |
| 855 |
$msg = preg_replace( "/\r\n|\r|\n/", '<br/>', $mess->output[0]->content[0]->text ); |
| 856 |
wp_send_json( |
| 857 |
array( |
| 858 |
'success' => true, |
| 859 |
'title' => esc_html__( 'success', 'chatbot' ), |
| 860 |
'icon' => esc_html__( 'success', 'chatbot' ), |
| 861 |
'msg' => esc_html( $msg ), |
| 862 |
) |
| 863 |
); |
| 864 |
} else { |
| 865 |
|
| 866 |
wp_send_json( |
| 867 |
array( |
| 868 |
'success' => true, |
| 869 |
'title' => esc_html__( 'Error', 'chatbot' ), |
| 870 |
'icon' => esc_html__( 'error', 'chatbot' ), |
| 871 |
'msg' => esc_html( json_decode( $res )->error->message ), |
| 872 |
) |
| 873 |
); |
| 874 |
} |
| 875 |
|
| 876 |
// echo wp_json_encode($ai_enabled);wp_die(); |
| 877 |
|
| 878 |
} |
| 879 |
public function rag_settings_option_callback() |
| 880 |
{ |
| 881 |
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; |
| 882 |
if (!wp_verify_nonce($nonce, 'wp_chatbot') || !current_user_can('manage_options')) { |
| 883 |
wp_send_json_error(array('message' => esc_html__('Security check failed', 'chatbot'))); |
| 884 |
wp_die(); |
| 885 |
} |
| 886 |
if( (get_option('is_page_rag_enabled') == '1' && get_option('open_ai_api_key')) || (get_option('qcld_gemini_rag_enabled') == '1' && get_option('qcld_gemini_api_key'))){ |
| 887 |
|
| 888 |
|
| 889 |
$rag_embed_pages = sanitize_text_field(wp_unslash($_POST['rag_embed_pages']) ?? 0); |
| 890 |
$rag_embed_posts = sanitize_text_field(wp_unslash($_POST['rag_embed_posts']) ?? 0); |
| 891 |
$rag_embed_str = sanitize_text_field(wp_unslash($_POST['rag_embed_str']) ?? 0); |
| 892 |
$rag_auto_sync_enabled = sanitize_text_field(wp_unslash($_POST['rag_auto_sync_enabled']) ?? 0); |
| 893 |
|
| 894 |
$rag_embed_cpts = isset($_POST['rag_embed_cpts']) ? wp_unslash($_POST['rag_embed_cpts']) : []; |
| 895 |
if(is_array($rag_embed_cpts)){ |
| 896 |
$rag_embed_cpts = array_map('sanitize_text_field', $rag_embed_cpts); |
| 897 |
} |
| 898 |
|
| 899 |
if (isset($_POST['is_page_rag_enabled'])) { |
| 900 |
$is_rag_enabled = sanitize_text_field(wp_unslash($_POST['is_page_rag_enabled'])); |
| 901 |
update_option('is_page_rag_enabled', $is_rag_enabled); |
| 902 |
if($is_rag_enabled == 1){ |
| 903 |
update_option('is_asst_enabled', 0); |
| 904 |
} |
| 905 |
} |
| 906 |
|
| 907 |
update_option('rag_embed_pages', $rag_embed_pages); |
| 908 |
update_option('rag_embed_str', $rag_embed_str); |
| 909 |
update_option('rag_embed_posts', $rag_embed_posts); |
| 910 |
update_option('rag_auto_sync_enabled', $rag_auto_sync_enabled); |
| 911 |
update_option('rag_embed_cpts', $rag_embed_cpts); |
| 912 |
|
| 913 |
wp_send_json( array('status' => 'success') ); |
| 914 |
}else{ |
| 915 |
if( !get_option('open_ai_api_key') || !get_option('qcld_gemini_api_key') ){ |
| 916 |
wp_send_json_success(array('status' => 'error', 'message' => esc_html__('RAG cannot be enabled without an API key.', 'chatbot'))); |
| 917 |
}else if( get_option('is_page_rag_enabled') != '1' && get_option('qcld_gemini_rag_enabled') != '1' ){ |
| 918 |
wp_send_json_success(array('status' => 'error', 'message' => esc_html__('Please enable RAG in settings to save RAG related options.', 'chatbot'))); |
| 919 |
} |
| 920 |
wp_die(); |
| 921 |
} |
| 922 |
} |
| 923 |
public function qcld_update_settings_option_callback(){ |
| 924 |
// Verify nonce for CSRF protection |
| 925 |
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; |
| 926 |
if (!wp_verify_nonce($nonce, 'wp_chatbot') || !current_user_can('manage_options')) { |
| 927 |
wp_send_json_error(array('message' => esc_html__('Security check failed', 'chatbot'))); |
| 928 |
wp_die(); |
| 929 |
} |
| 930 |
|
| 931 |
// Check user capability - only administrators can modify settings |
| 932 |
if (!current_user_can('manage_options')) { |
| 933 |
wp_send_json_error(array('message' => esc_html__('Unauthorized access', 'chatbot'))); |
| 934 |
wp_die(); |
| 935 |
} |
| 936 |
|
| 937 |
// Proceed with option updates |
| 938 |
update_option('disable_wp_chatbot_site_search', 1); |
| 939 |
update_option('enable_wp_chatbot_post_content', ''); |
| 940 |
|
| 941 |
// Send success response |
| 942 |
wp_send_json_success(array('message' => esc_html__('Settings updated successfully', 'chatbot'))); |
| 943 |
wp_die(); |
| 944 |
} |
| 945 |
public function qcpd_remove_wa_stopwords($query, $stopwords){ |
| 946 |
|
| 947 |
return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query); |
| 948 |
|
| 949 |
} |
| 950 |
public function openai_troubleshooting() { |
| 951 |
$nonce = sanitize_text_field(wp_unslash($_POST['nonce'])); |
| 952 |
$OpenAI = new qcld_wp_OpenAI(); |
| 953 |
if ( ! wp_verify_nonce( $nonce, 'wp_chatbot' ) ) { |
| 954 |
wp_send_json( |
| 955 |
array( |
| 956 |
'success' => false, |
| 957 |
'msg' => esc_html__( 'Failed in Security check', 'chatbot' ), |
| 958 |
) |
| 959 |
); |
| 960 |
wp_die(); |
| 961 |
|
| 962 |
} elseif ( ! current_user_can( 'manage_options' ) ) { |
| 963 |
wp_send_json( |
| 964 |
array( |
| 965 |
'success' => false, |
| 966 |
'msg' => esc_html__( 'Unauthorized user', 'chatbot' ), |
| 967 |
) |
| 968 |
); |
| 969 |
wp_die(); |
| 970 |
} else { |
| 971 |
$gptkeyword = array(); |
| 972 |
array_push( |
| 973 |
$gptkeyword, |
| 974 |
array( |
| 975 |
'role' => 'user', |
| 976 |
'content' => 'If you get this query respond in plain text: "Congrats! You are connected to AI."', |
| 977 |
) |
| 978 |
); |
| 979 |
$res = $OpenAI->gptcomplete( |
| 980 |
$gptkeyword |
| 981 |
); |
| 982 |
|
| 983 |
if ( empty( json_decode( $res )->error ) ) { |
| 984 |
$mess = json_decode( $res ); |
| 985 |
$msg = preg_replace( "/\r\n|\r|\n/", '<br/>', $mess->output[0]->content[0]->text ); |
| 986 |
wp_send_json( |
| 987 |
array( |
| 988 |
'success' => true, |
| 989 |
'title' => esc_html__( 'success', 'chatbot' ), |
| 990 |
'icon' => esc_html__( 'success', 'chatbot' ), |
| 991 |
'msg' => esc_html( $msg ), |
| 992 |
) |
| 993 |
); |
| 994 |
} else { |
| 995 |
|
| 996 |
wp_send_json( |
| 997 |
array( |
| 998 |
'success' => true, |
| 999 |
'title' => esc_html__( 'Error', 'chatbot' ), |
| 1000 |
'icon' => esc_html__( 'error', 'chatbot' ), |
| 1001 |
'msg' => esc_html( json_decode( $res )->error->message ), |
| 1002 |
) |
| 1003 |
); |
| 1004 |
} |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
public function wpbot_wizard_save_callback() |
| 1009 |
{ |
| 1010 |
$nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : ''; |
| 1011 |
|
| 1012 |
if (! wp_verify_nonce($nonce, 'wp_chatbot')) { |
| 1013 |
wp_send_json_error(esc_html__('Failed in Security check', 'chatbot')); |
| 1014 |
wp_die(); |
| 1015 |
} |
| 1016 |
|
| 1017 |
if (!current_user_can('manage_options')) { |
| 1018 |
wp_send_json_error(esc_html__('Insufficient permissions', 'chatbot')); |
| 1019 |
wp_die(); |
| 1020 |
} |
| 1021 |
|
| 1022 |
$is_skipped = isset($_POST['is_skipped']) ? intval($_POST['is_skipped']) : 0; |
| 1023 |
|
| 1024 |
if ($is_skipped) { |
| 1025 |
wp_send_json_success(); |
| 1026 |
wp_die(); |
| 1027 |
} |
| 1028 |
|
| 1029 |
// 1. Save AI Provider and API key |
| 1030 |
$provider = isset($_POST['ai_provider']) ? sanitize_text_field($_POST['ai_provider']) : ''; |
| 1031 |
$api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : ''; |
| 1032 |
|
| 1033 |
if ($provider === 'openai') { |
| 1034 |
update_option('open_ai_api_key', $api_key); |
| 1035 |
} elseif ($provider === 'gemini') { |
| 1036 |
update_option('qcld_gemini_api_key', $api_key); |
| 1037 |
} elseif ($provider === 'grok') { |
| 1038 |
update_option('qcld_grok_api_key', $api_key); |
| 1039 |
} elseif ($provider === 'openrouter') { |
| 1040 |
update_option('qcld_openrouter_api_key', $api_key); |
| 1041 |
} |
| 1042 |
|
| 1043 |
// 2. Enable AI for selected provider automatically |
| 1044 |
// Reset all providers first |
| 1045 |
update_option('ai_enabled', 0); |
| 1046 |
update_option('qcld_gemini_enabled', 0); |
| 1047 |
update_option('qcld_grok_enabled', 0); |
| 1048 |
update_option('qcld_openrouter_enabled', 0); |
| 1049 |
update_option('enable_wp_chatbot_dailogflow', 0); |
| 1050 |
|
| 1051 |
if ($provider === 'openai') { |
| 1052 |
update_option('ai_enabled', 1); |
| 1053 |
} elseif ($provider === 'gemini') { |
| 1054 |
update_option('qcld_gemini_enabled', 1); |
| 1055 |
} elseif ($provider === 'grok') { |
| 1056 |
update_option('qcld_grok_enabled', 1); |
| 1057 |
} elseif ($provider === 'openrouter') { |
| 1058 |
update_option('qcld_openrouter_enabled', 1); |
| 1059 |
} |
| 1060 |
|
| 1061 |
// 3. Auto-enable Streaming by default |
| 1062 |
update_option('is_stream_enabled', 1); |
| 1063 |
|
| 1064 |
// 4. Auto-enable RAG by default (globally & for provider-specific config) |
| 1065 |
update_option('is_page_rag_enabled', 1); |
| 1066 |
update_option('qcld_gemini_rag_enabled', ($provider === 'gemini') ? 1 : 0); |
| 1067 |
update_option('qcld_grok_rag_enabled', ($provider === 'grok') ? 1 : 0); |
| 1068 |
update_option('qcld_openrouter_rag_enabled', ($provider === 'openrouter') ? 1 : 0); |
| 1069 |
|
| 1070 |
// 5. Knowledge Base settings (default Top K to 5) |
| 1071 |
update_option('rag_top_k', 5); |
| 1072 |
|
| 1073 |
// Auto-initialize system content defaults if empty |
| 1074 |
if (empty(get_option('qcld_openai_system_content'))) { |
| 1075 |
update_option('qcld_openai_system_content', 'You are a helpful and intelligent assistant for a WordPress chatbot. Always reply to the user query accurately, clearly, and briefly.'); |
| 1076 |
} |
| 1077 |
if (empty(get_option('qcld_gemini_system_content'))) { |
| 1078 |
update_option('qcld_gemini_system_content', 'You are a helpful assistant.'); |
| 1079 |
} |
| 1080 |
if (empty(get_option('qcld_grok_system_content'))) { |
| 1081 |
update_option('qcld_grok_system_content', 'You are a helpful and intelligent assistant for the website "' . site_url() . '". Use live website data and the provided context to respond accurately and briefly. Stay relevant and do not introduce additional topics.'); |
| 1082 |
} |
| 1083 |
|
| 1084 |
// 6. Embed sources |
| 1085 |
$rag_embed_pages = isset($_POST['rag_embed_pages']) ? intval($_POST['rag_embed_pages']) : 0; |
| 1086 |
update_option('rag_embed_pages', $rag_embed_pages); |
| 1087 |
|
| 1088 |
$rag_embed_posts = isset($_POST['rag_embed_posts']) ? intval($_POST['rag_embed_posts']) : 0; |
| 1089 |
update_option('rag_embed_posts', $rag_embed_posts); |
| 1090 |
|
| 1091 |
$rag_embed_cpts = isset($_POST['rag_embed_cpts']) ? array_map('sanitize_text_field', $_POST['rag_embed_cpts']) : array(); |
| 1092 |
update_option('rag_embed_cpts', $rag_embed_cpts); |
| 1093 |
|
| 1094 |
// Mark wizard as completed permanently in DB |
| 1095 |
update_option('wpbot_ai_setup_wizard_done', 1); |
| 1096 |
|
| 1097 |
wp_send_json_success(esc_html__('AI Setup configuration saved successfully.', 'chatbot')); |
| 1098 |
wp_die(); |
| 1099 |
} |
| 1100 |
|
| 1101 |
public function wpbot_wizard_verify_key_callback() |
| 1102 |
{ |
| 1103 |
$nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : ''; |
| 1104 |
|
| 1105 |
if (! wp_verify_nonce($nonce, 'wp_chatbot')) { |
| 1106 |
wp_send_json_error(esc_html__('Failed in Security check', 'chatbot')); |
| 1107 |
wp_die(); |
| 1108 |
} |
| 1109 |
|
| 1110 |
if (!current_user_can('manage_options')) { |
| 1111 |
wp_send_json_error(esc_html__('Insufficient permissions', 'chatbot')); |
| 1112 |
wp_die(); |
| 1113 |
} |
| 1114 |
|
| 1115 |
$provider = isset($_POST['ai_provider']) ? sanitize_text_field($_POST['ai_provider']) : ''; |
| 1116 |
$api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : ''; |
| 1117 |
|
| 1118 |
if ($provider === 'openai') { |
| 1119 |
$url = 'https://api.openai.com/v1/models'; |
| 1120 |
$args = array( |
| 1121 |
'headers' => array( |
| 1122 |
'Authorization' => 'Bearer ' . $api_key, |
| 1123 |
), |
| 1124 |
'timeout' => 15, |
| 1125 |
); |
| 1126 |
} elseif ($provider === 'gemini') { |
| 1127 |
$url = 'https://generativelanguage.googleapis.com/v1beta/models?key=' . $api_key; |
| 1128 |
$args = array( |
| 1129 |
'timeout' => 15, |
| 1130 |
); |
| 1131 |
} elseif ($provider === 'grok') { |
| 1132 |
$url = 'https://api.x.ai/v1/models'; |
| 1133 |
$args = array( |
| 1134 |
'headers' => array( |
| 1135 |
'Authorization' => 'Bearer ' . $api_key, |
| 1136 |
), |
| 1137 |
'timeout' => 15, |
| 1138 |
); |
| 1139 |
} elseif ($provider === 'openrouter') { |
| 1140 |
$url = 'https://openrouter.ai/api/v1/models'; |
| 1141 |
$args = array( |
| 1142 |
'headers' => array( |
| 1143 |
'Authorization' => 'Bearer ' . $api_key, |
| 1144 |
), |
| 1145 |
'timeout' => 15, |
| 1146 |
); |
| 1147 |
} |
| 1148 |
|
| 1149 |
$response = wp_remote_get($url, $args); |
| 1150 |
|
| 1151 |
if (is_wp_error($response)) { |
| 1152 |
wp_send_json_error($response->get_error_message()); |
| 1153 |
wp_die(); |
| 1154 |
} |
| 1155 |
|
| 1156 |
$code = wp_remote_retrieve_response_code($response); |
| 1157 |
if ($code === 200) { |
| 1158 |
wp_send_json_success(); |
| 1159 |
} else { |
| 1160 |
$body = wp_remote_retrieve_body($response); |
| 1161 |
$data = json_decode($body, true); |
| 1162 |
$msg = ''; |
| 1163 |
if (isset($data['error']['message'])) { |
| 1164 |
$msg = $data['error']['message']; |
| 1165 |
} elseif (isset($data['error']['metadata']['message'])) { |
| 1166 |
$msg = $data['error']['metadata']['message']; |
| 1167 |
} elseif (isset($data['error'])) { |
| 1168 |
$msg = is_string($data['error']) ? $data['error'] : json_encode($data['error']); |
| 1169 |
} else { |
| 1170 |
$msg = 'HTTP Status ' . $code; |
| 1171 |
} |
| 1172 |
wp_send_json_error($msg); |
| 1173 |
} |
| 1174 |
wp_die(); |
| 1175 |
} |
| 1176 |
} |
| 1177 |
|
| 1178 |
/** |
| 1179 |
* @return qcld_wpopenai_addon |
| 1180 |
*/ |
| 1181 |
if(!function_exists('qcld_wpopenai_addons')){ |
| 1182 |
function qcld_openais() { |
| 1183 |
$qcld_wpopenai_addon = new qcld_wpopenai_addons(); |
| 1184 |
return $qcld_wpopenai_addon->instance(); |
| 1185 |
|
| 1186 |
} |
| 1187 |
} |
| 1188 |
|
| 1189 |
//fire off the plugin |
| 1190 |
qcld_openais(); |
| 1191 |
|
| 1192 |
} |