PluginProbe
WPBot – AI ChatBot for Live Support, Lead Generation, AI Services / 8.0.0
WPBot – AI ChatBot for Live Support, Lead Generation, AI Services v8.0.0
8.7.5 8.7.4 8.7.3 8.7.2 8.7.1 8.7.0 8.6.9 8.6.8 8.6.7 8.6.6 8.6.5 8.6.4 8.6.2 8.6.1 8.6.0 8.5.9 8.5.8 8.5.7 8.5.6 8.5.5 8.5.4 8.5.3 8.5.2 8.5.0 8.4.9 All 531 releases
chatbot / includes / class-common-function.php

class-common-function.php in WPBot – AI ChatBot for Live Support, Lead Generation, AI Services 8.0.0, at includes/class-common-function.php

347 lines 13.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Common functions class
4 */
5 class Qcld_WPBot_Common_Functions {
6
7
8 private static $instance = null;
9
10 public static function instance() {
11 if ( is_null( self::$instance ) ) {
12 self::$instance = new self();
13 }
14 return self::$instance;
15 }
16
17 private function __construct() {
18 add_action('wp_ajax_wpbot_save_feedback', array( $this, 'wpbot_save_feedback') );
19 add_action('wp_ajax_nopriv_wpbot_save_feedback', array( $this,'wpbot_save_feedback') );
20 add_action( 'wp_ajax_wpbot_save_report', array( $this, 'wpbot_save_report') );
21 add_action( 'wp_ajax_nopriv_wpbot_save_report', array( $this, 'wpbot_save_report') );
22 add_action('wp_ajax_nopriv_get_relevant_pages', array($this, 'qcld_get_relevant_pages_ajax'));
23 add_action('wp_ajax_rate_limit_settings_option', array($this, 'rate_limit_settings_option_callback'));
24 register_activation_hook(__FILE__, array('qcld_wpopenai_addons', 'schedule_rate_limit_reset_events'));
25 add_filter('cron_schedules', array($this, 'qcld_user_role_rate_cron_schedule'));
26 add_action('rate_limit_checker', array($this, 'rate_limit_checker'));
27 add_action('qcld_openai_user_rate_cal', array($this, 'qcld_openai_user_rate_cal'));
28 add_action('reset_rate_limit_used_counts', [$this, 'reset_rate_limit_used_counts'], 10, 1);
29
30 }
31 /**
32 * Remove stopwords from search query
33 *
34 * @param string $query The search query
35 * @param array $stopwords Array of stopwords to remove
36 * @return string Query with stopwords removed
37 */
38 public static function qcpd_remove_wa_stopwords($query, $stopwords) {
39 return preg_replace('/\b('.implode('|',$stopwords).')\b/','',$query);
40 }
41
42 /**
43 * Get relevant page links based on search query
44 *
45 * @param string $search_query The search query
46 * @return array Array of relevant page links
47 */
48 public static function qcpd_relevant_pagelink($search_query) {
49 $stopwords = explode(',', get_option('qlcd_wp_chatbot_stop_words'));
50
51 $finalQueryWordsWithoutStopWords = self::qcpd_remove_wa_stopwords(strtolower($search_query), $stopwords);
52
53 $cleanWordsWithoutPunctuationMarks = preg_replace('/[\p{P}]/u', '', $finalQueryWordsWithoutStopWords);
54
55 $q = trim($cleanWordsWithoutPunctuationMarks);
56
57 $links = [];
58
59 $post_type_array = get_option('qcld_openai_relevant_post');
60
61 $the_query = new WP_Query(array(
62 'post_status' => 'publish',
63 'posts_per_page' => 5,
64 's' => esc_attr($q),
65 'post_type' => $post_type_array
66 ));
67
68 if($the_query->have_posts()) {
69 while($the_query->have_posts()) {
70 $the_query->the_post();
71
72 $url = esc_url(get_permalink());
73 $link = '<a href=' . $url . ' target="_blank">' . get_the_title() . '</a>';
74 array_push($links, $link);
75 }
76 wp_reset_postdata();
77 }
78
79 $links = array_unique($links);
80 return $links;
81 }
82
83
84 public function wpbot_save_feedback() {
85 global $wpdb;
86
87 $table = $wpdb->prefix . 'wpbot_chat_report';
88
89 $user_id = intval($_POST['user_id']);
90 $conversation_id= intval($_POST['conversation_id']);
91 $message = sanitize_text_field($_POST['message']);
92 $feedback = sanitize_text_field($_POST['feedback']); // "like" or "dislike"
93 $meta_info = sanitize_textarea_field($_POST['meta_info']);
94 $date = current_time('mysql');
95
96 $inserted = $wpdb->insert($table, array(
97 'user_id' => $user_id,
98 'conversation_id'=> $conversation_id,
99 'message' => $message,
100 'feedback' => $feedback,
101 'meta_info' => $meta_info,
102 'created_at' => $date
103 ));
104
105 if ($inserted !== false) {
106 wp_send_json_success(array('message' => 'Feedback saved.'));
107 } else {
108 wp_send_json_error(array('message' => 'Failed to save feedback.'));
109 }
110 }
111
112 /**
113 * Save report func
114 *
115 */
116
117
118 public function wpbot_save_report() {
119 global $wpdb;
120 $table_report = $wpdb->prefix . 'wpbot_chat_report';
121
122 $email = sanitize_email( $_POST['email'] );
123 $message = sanitize_textarea_field( $_POST['message'] );
124 $report_text = sanitize_textarea_field( $_POST['report_text'] );
125
126 $wpdb->insert(
127 $table_report,
128 [
129 'user_id' => get_current_user_id(), // or match from wpbot_user.
130 'message' => $message,
131 'meta_info' => maybe_serialize( [ 'email' => $email, 'report_text' => $report_text ] ),
132 ],
133 [ '%d', '%s', '%s' ]
134 );
135
136 // Send report email to admin
137 $admin_email = get_option( 'admin_email' );
138 $subject = "New Chat Report";
139 $body = "Reported Message:\n{$message}\n\nReport Text:\n{$report_text}\n\nUser Email: {$email}";
140 wp_mail( $admin_email, $subject, $body );
141
142 wp_send_json_success();
143 }
144 public function rate_limit_settings_option_callback()
145 {
146 // Check is admin
147 if (! current_user_can('manage_options')) {
148 wp_send_json_error('Unauthorized');
149 wp_die();
150 }
151 // Save the rate limiting enabled/disabled setting
152 if (isset($_POST['is_rate_limiting_enabled'])) {
153 $is_rate_limiting_enabled = intval($_POST['is_rate_limiting_enabled']);
154 update_option('is_rate_limiting_enabled', $is_rate_limiting_enabled);
155 }
156 // Save the rate limits for each role
157 if (isset($_POST['rate_limits']) && is_array($_POST['rate_limits'])) {
158 foreach ($_POST['rate_limits'] as $role => $limit) {
159 $option_name = 'rate_limit_' . sanitize_text_field($role);
160 $limit_value = intval($limit);
161 update_option($option_name, $limit_value);
162 $timeframe = isset($_POST['rate_limit_timeframes'][$role]) ? sanitize_text_field($_POST['rate_limit_timeframes'][$role]) : '24';
163 $timeframe = intval($timeframe * 3600); // Convert hours to seconds
164 update_option('rate_limit_timeframe_' . $role, $timeframe); // Convert hours to seconds
165 $timeframe = get_option('rate_limit_timeframe_' . $role, true);
166 }
167 $timeframe = isset($_POST['rate_limit_timeframes']['guest']) ? sanitize_text_field($_POST['rate_limit_timeframes']['guest']) : '24';
168 $timeframe = intval($timeframe * 3600); // Convert hours to seconds
169 update_option('rate_limit_timeframe_' . 'guest', $timeframe);
170 }
171 // In your rate_limit_settings_option_callback(), after updating options:
172 $this->schedule_rate_limit_reset_events();
173 wp_send_json_success('Settings saved');
174 wp_die();
175 }
176 public function qcld_user_role_rate_cron_schedule($schedules)
177 {
178 $roles = wp_roles()->roles;
179 foreach ($roles as $role => $details) {
180 $timeframe = intval(get_option('rate_limit_timeframe_' . $role, true));
181 // Minimum 3600 seconds
182 $schedules['session_schedules_rate_limit_' . $role] = array(
183 'interval' => $timeframe,
184 'display' => esc_attr('session_schedules_rate_limit_' . $role, 'wpchatbot'),
185 );
186 // Schedule the cron job for each role if not already scheduled);
187 }
188 return $schedules;
189 }
190 // wpshedule event to reset the rate limit used counts
191 public function schedule_rate_limit_reset_events()
192 {
193 // Ensure WordPress cron functions are available
194 if (! function_exists('wp_schedule_event')) {
195 require_once ABSPATH . 'wp-includes/wp-cron.php';
196 }
197 $roles = wp_roles()->roles;
198 foreach ($roles as $role => $d) {
199 // Unschedule all existing events for this role
200 $timestamp = wp_next_scheduled('reset_rate_limit_used_counts', array($role));
201 while ($timestamp) {
202 wp_unschedule_event($timestamp, 'reset_rate_limit_used_counts', array($role));
203 $timestamp = wp_next_scheduled('reset_rate_limit_used_counts', array($role));
204 }
205 // Schedule new event with updated interval
206 wp_schedule_event(time(), 'session_schedules_rate_limit_' . $role, 'reset_rate_limit_used_counts', array($role));
207 }
208 }
209 public function qcld_wpsession_cron_deactivation()
210 {
211 $timestamp = wp_next_scheduled('reset_rate_limit_used_counts');
212 wp_unschedule_event($timestamp, 'reset_rate_limit_used_counts');
213 }
214 public function rate_limit_checker()
215 {
216 $qlcd_wp_chatbot_ai_rate_limiting_message = qcld_wb_chatbot_func_str_replace(
217 maybe_unserialize(get_option('qlcd_wp_chatbot_ai_rate_limiting_message', true))
218 );
219 if (get_option('is_stream_enabled') == 1) {
220 $response = array(
221 'status' => 'error',
222 'message' => esc_html__((is_array($qlcd_wp_chatbot_ai_rate_limiting_message) && !empty($qlcd_wp_chatbot_ai_rate_limiting_message[0]) ? $qlcd_wp_chatbot_ai_rate_limiting_message[0] : 'Rate limit exceeded. Please try again later.'), 'wpchatbot'),
223
224 );
225 } else {
226 $response = array(
227 'status' => 'success',
228 'message' => esc_html__((is_array($qlcd_wp_chatbot_ai_rate_limiting_message) && !empty($qlcd_wp_chatbot_ai_rate_limiting_message[0]) ? $qlcd_wp_chatbot_ai_rate_limiting_message[0] : 'Rate limit exceeded. Please try again later.'), 'wpchatbot'),
229 );
230 }
231 if (is_user_logged_in()) {
232 $user = wp_get_current_user();
233 if (! empty($user->roles) && is_array($user->roles)) {
234 $role = $user->roles[0];
235 $option_name = 'rate_limit_' . $role;
236 $limit = get_option($option_name);
237 $rate_limit = get_user_meta(get_current_user_id(), 'qcld_openai_user_rate_limit', true);
238 if (($limit >= $rate_limit) || $limit == 0) {
239 return; // allowed
240 } else {
241 if (get_option('is_stream_enabled') == 1) {
242 wp_send_json($response); //Proper JSON with header.
243 } else {
244 echo json_encode($response);
245 wp_die();
246 }
247 }
248 }
249 } else {
250 $option_name = 'rate_limit_guest';
251 $limit = get_option($option_name);
252
253 if (session_status() == PHP_SESSION_NONE) {
254 session_start();
255 }
256
257 $guest_rate_limit = isset($_SESSION['guest_rate_limit']) ? intval($_SESSION['guest_rate_limit']) : 0;
258
259 if ($limit >= $guest_rate_limit || $limit == 0) {
260 return; // allowed
261 } else {
262 if (get_option('is_stream_enabled') == 1) {
263 wp_send_json($response); //Proper JSON with header.
264 } else {
265 echo json_encode($response);
266 // Return role if limit exceeded
267 wp_die();
268 }
269 }
270 }
271 }
272
273 public function reset_rate_limit_used_counts($role)
274 {
275 if (empty($role)) {
276 return;
277 }
278 error_log('Resetting rate limit used counts for role: ');
279 // loop through each role
280 // for each role get all users with that role
281 $roles = wp_roles()->roles;
282 foreach ($roles as $list_roll => $details) {
283 if ($list_roll != $role) {
284 continue;
285 } else {
286 $option_name = 'rate_limit_' . $role;
287 $limit = get_option($option_name); // Default to if not set
288 $users = get_users(array('role' => $role));
289 foreach ($users as $user) {
290 update_user_meta($user->ID, 'qcld_openai_user_rate_limit', 0);
291 }
292 }
293 }
294 }
295 public function qcld_openai_user_rate_cal($update)
296 {
297 if (is_user_logged_in()) {
298 $rate_limit = get_user_meta(get_current_user_id(), 'qcld_openai_user_rate_limit', true);
299 if ($update != '') {
300 $rate_limit = intval($rate_limit) + intval($update);
301 }
302 update_user_meta(get_current_user_id(), 'qcld_openai_user_rate_limit', $rate_limit);
303 return;
304 } else {
305 // for guest users we will use session to store the rate limit
306 // if session is not started then start it
307 if (session_status() == PHP_SESSION_NONE) {
308 session_start();
309 }
310 // we will use guest_id to identify the guest user
311 if (! isset($_SESSION['guest_id'])) {
312 $user_ip = $_SERVER['REMOTE_ADDR'];
313 $session_id = md5($user_ip . time());
314 $_SESSION['guest_id'] = $session_id;
315 $_SESSION['guest_id_time'][$session_id] = time();
316 get_option('rate_', 10);
317 // if guest_id_time is set and it is older than 24 hours then unset the guest_id
318 // we will store the time when the guest_id was created in session
319 $timeframe = get_option('rate_limit_timeframe_guest', true);
320 $timeframe = intval($timeframe) * 3600; // convert hours to seconds
321 if (isset($_SESSION['guest_id_time'][$session_id]) && (time() - $_SESSION['guest_id_time'][$session_id]) > $timeframe) {
322 unset($_SESSION['guest_id']);
323 unset($_SESSION['guest_id_time']);
324 }
325 // we will store the time when the guest_id was created in session
326 $_SESSION['guest_id_time'][$session_id] = time();
327 $_SESSION['guest_rate_limit'] = 0;
328 }
329 // update the rate limit
330 // if update is not empty then add it to the existing rate limit else set it
331 if ($update != '') {
332 $guest_rate_limit = isset($_SESSION['guest_rate_limit']) ? intval($_SESSION['guest_rate_limit']) : 0;
333 // add the update to the existing rate limit
334 // set the rate limit in session
335 $_SESSION['guest_rate_limit'] = $guest_rate_limit + $update;
336 return;
337 }
338 }
339 }
340
341 }
342
343 /**
344 * Instantiate the class
345 */
346 Qcld_WPBot_Common_Functions::instance();
347