PluginProbe ʕ •ᴥ•ʔ
Check & Log Email – Easy Email Testing & Mail logging / 2.0.9
Check & Log Email – Easy Email Testing & Mail logging v2.0.9
1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 2.0 2.0.1 2.0.10 2.0.11 2.0.12 2.0.13 2.0.13.1 2.0.13.2 2.0.14 2.0.2 2.0.3 2.0.4 2.0.5 2.0.5.1 2.0.6 2.0.7 2.0.8 2.0.9 trunk 0.5.7 0.6.0 0.6.1 0.6.2 1.0.0 1.0.1 1.0.10 1.0.11 1.0.12 1.0.12.1 1.0.13 1.0.13.1 1.0.2 1.0.3
check-email / include / helper-function.php
check-email / include Last commit date
Core 9 months ago Util 9 months ago Check_Email_Encode_Tab.php 9 months ago Check_Email_Notify_Tab.php 9 months ago Check_Email_SMTP_Tab.php 9 months ago class-check-email-header-parser.php 9 months ago class-check-email-log-autoloader.php 9 months ago class-check-email-newsletter.php 9 months ago deactivate-feedback.php 9 months ago helper-function.php 9 months ago install.php 9 months ago
helper-function.php
1309 lines
1 <?php
2
3 /**
4 * Helper Functions
5 *
6 * @package check-mail
7 * @subpackage Helper/Templates
8 * @copyright Copyright (c) 2016, René Hermenau
9 * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
10 * @since 1.4.0
11 */
12 // Exit if accessed directly
13 if( !defined( 'ABSPATH' ) )
14 exit;
15
16 /**
17 * Helper method to check if user is in the plugins page.
18 *
19 * @author René Hermenau
20 * @since 1.4.0
21 *
22 * @return bool
23 */
24
25 /**
26 * display deactivation logic on plugins page
27 *
28 * @since 1.4.0
29 */
30 function ck_mail_is_plugins_page() {
31
32 if(function_exists('get_current_screen')){
33 $screen = get_current_screen();
34 if(is_object($screen)){
35 if($screen->id == 'plugins' || $screen->id == 'plugins-network'){
36 return true;
37 }
38 }
39 }
40 return false;
41 }
42
43 add_filter('admin_footer', 'ck_mail_add_deactivation_feedback_modal');
44
45 function ck_mail_add_deactivation_feedback_modal() {
46
47 if( is_admin() && ck_mail_is_plugins_page() ) {
48
49 require_once CK_MAIL_PATH ."/include/deactivate-feedback.php";
50 }
51
52 }
53
54 /**
55 * send feedback via email
56 *
57 * @since 1.4.0
58 */
59 function ck_mail_send_feedback() {
60 // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Reason: in form variable.
61 if( isset( $_POST['data'] ) ) {
62 // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Reason: in form variable.
63 parse_str( sanitize_text_field( wp_unslash($_POST['data'])), $form );
64 }
65
66 if( !isset( $form['ck_mail_security_nonce'] ) || isset( $form['ck_mail_security_nonce'] ) && !wp_verify_nonce( sanitize_text_field( $form['ck_mail_security_nonce'] ), 'ck_mail_ajax_check_nonce' ) ) {
67 echo esc_html__('security_nonce_not_verified', 'check-email');
68 die();
69 }
70 if ( !current_user_can( 'manage_options' ) ) {
71 die();
72 }
73
74 $text = '';
75 if( isset( $form['ck_mail_disable_text'] ) ) {
76 if (is_array($form['ck_mail_disable_text'])) {
77 $text = implode( " ", $form['ck_mail_disable_text'] );
78 }
79 }
80
81 $headers = array();
82
83 $from = isset( $form['ck_mail_disable_from'] ) ? $form['ck_mail_disable_from'] : '';
84 if( $from ) {
85 $headers[] = "From: $from";
86 $headers[] = "Reply-To: $from";
87 }
88
89 $subject = isset( $form['ck_mail_disable_reason'] ) ? $form['ck_mail_disable_reason'] : '(no reason given)';
90
91 if($subject == 'technical issue'){
92
93 $subject = 'Check & Log Email '.$subject;
94 $text = trim($text);
95
96 if(!empty($text)){
97
98 $text = 'technical issue description: '.$text;
99
100 }else{
101
102 $text = 'no description: '.$text;
103 }
104
105 }else{
106 $subject = 'Check & Log Email';
107 }
108
109 $success = wp_mail( 'team@magazine3.in', $subject, $text, $headers );
110
111 echo 'sent';
112 die();
113 }
114 add_action( 'wp_ajax_ck_mail_send_feedback', 'ck_mail_send_feedback' );
115
116
117 function ck_mail_enqueue_makebetter_email_js() {
118
119 if ( is_admin() && ck_mail_is_plugins_page() ) {
120
121 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
122
123 wp_register_script( 'ck_mail_make_better_js', CK_MAIL_URL . 'assets/js/admin/feedback'. $suffix .'.js', array( 'jquery' ), CK_MAIL_VERSION, true);
124 $data = array(
125 'ajax_url' => admin_url( 'admin-ajax.php' ),
126 'ck_mail_security_nonce' => wp_create_nonce('ck_mail_ajax_check_nonce'),
127 );
128
129 $data = apply_filters( 'ck_mail_localize_filter', $data, 'eztoc_admin_data' );
130
131 wp_localize_script( 'ck_mail_make_better_js', 'cn_ck_mail_admin_data', $data );
132 wp_enqueue_script( 'ck_mail_make_better_js' );
133 wp_enqueue_style( 'ck_mail_make_better_css', CK_MAIL_URL . 'assets/css/admin/feedback'. $suffix .'.css', array(), CK_MAIL_VERSION );
134
135 }
136
137 }
138 add_action( 'admin_enqueue_scripts', 'ck_mail_enqueue_makebetter_email_js' );
139
140
141 add_action('wp_ajax_ck_mail_subscribe_newsletter','ck_mail_subscribe_for_newsletter');
142
143 function ck_mail_subscribe_for_newsletter() {
144 if ( ! isset( $_POST['ck_mail_security_nonce'] ) ){
145 echo esc_html__('security_nonce_not_verified', 'check-email');
146 die();
147 }
148 if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ck_mail_security_nonce'] ) ), 'ck_mail_ajax_check_nonce' ) ) {
149 echo esc_html__('security_nonce_not_verified', 'check-email');
150 die();
151 }
152 if ( !current_user_can( 'manage_options' ) ) {
153 die();
154 }
155 if (isset( $_POST['name'] ) && isset( $_POST['email'] ) && isset( $_POST['website'] )) {
156 $api_url = 'http://magazine3.company/wp-json/api/central/email/subscribe';
157
158 $api_params = array(
159 'name' => sanitize_text_field(wp_unslash($_POST['name'])),
160 'email'=> sanitize_email(wp_unslash($_POST['email'])),
161 'website'=> sanitize_text_field(wp_unslash($_POST['website'])),
162 'type'=> 'checkmail'
163 );
164 wp_remote_post( $api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
165 }
166 wp_die();
167 }
168
169 function ck_mail_forward_mail($atts) {
170 if ( isset( $atts['to'] ) ) {
171 $to = $atts['to'];
172 if ( ! is_array( $to ) ) {
173 $to = explode( ',', $to );
174 }
175 }
176
177
178 if ( isset( $atts['subject'] ) ) {
179 $subject = $atts['subject'];
180 }
181
182 if ( isset( $atts['message'] ) ) {
183 $message = $atts['message'];
184 }
185
186 if ( isset( $atts['headers'] ) ) {
187 $headers = $atts['headers'];
188 }
189
190 if ( isset( $atts['attachments'] ) ) {
191 $attachments = $atts['attachments'];
192 }
193
194
195 $subject = esc_html__('Forward Email Check & Log ', 'check-email').$subject;
196
197 if ( ! is_array( $attachments ) ) {
198 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
199 }
200 global $phpmailer;
201 if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) ) {
202 require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
203 require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
204 require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
205 $phpmailer = new PHPMailer\PHPMailer\PHPMailer( true );
206
207 $phpmailer::$validator = static function ( $email ) {
208 return (bool) is_email( $email );
209 };
210 }
211
212 // Headers.
213 $cc = array();
214 $bcc = array();
215 $reply_to = array();
216
217 if ( empty( $headers ) ) {
218 $headers = array();
219 } else {
220 if ( ! is_array( $headers ) ) {
221 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
222 } else {
223 $tempheaders = $headers;
224 }
225 $headers = array();
226
227 // If it's actually got contents.
228 if ( ! empty( $tempheaders ) ) {
229 // Iterate through the raw headers.
230 foreach ( (array) $tempheaders as $header ) {
231 if ( ! str_contains( $header, ':' ) ) {
232 if ( false !== stripos( $header, 'boundary=' ) ) {
233 $parts = preg_split( '/boundary=/i', trim( $header ) );
234 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
235 }
236 continue;
237 }
238 // Explode them out.
239 list( $name, $content ) = explode( ':', trim( $header ), 2 );
240
241 // Cleanup crew.
242 $name = trim( $name );
243 $content = trim( $content );
244
245 switch ( strtolower( $name ) ) {
246 // Mainly for legacy -- process a "From:" header if it's there.
247 case 'from':
248 $bracket_pos = strpos( $content, '<' );
249 if ( false !== $bracket_pos ) {
250 // Text before the bracketed email is the "From" name.
251 if ( $bracket_pos > 0 ) {
252 $from_name = substr( $content, 0, $bracket_pos );
253 $from_name = str_replace( '"', '', $from_name );
254 $from_name = trim( $from_name );
255 }
256
257 $from_email = substr( $content, $bracket_pos + 1 );
258 $from_email = str_replace( '>', '', $from_email );
259 $from_email = trim( $from_email );
260
261 // Avoid setting an empty $from_email.
262 } elseif ( '' !== trim( $content ) ) {
263 $from_email = trim( $content );
264 }
265 break;
266 case 'content-type':
267 if ( str_contains( $content, ';' ) ) {
268 list( $type, $charset_content ) = explode( ';', $content );
269 $content_type = trim( $type );
270 if ( false !== stripos( $charset_content, 'charset=' ) ) {
271 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
272 } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
273 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
274 $charset = '';
275 }
276
277 // Avoid setting an empty $content_type.
278 } elseif ( '' !== trim( $content ) ) {
279 $content_type = trim( $content );
280 }
281 break;
282 case 'cc':
283 $cc = array_merge( (array) $cc, explode( ',', $content ) );
284 break;
285 case 'bcc':
286 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
287 break;
288 case 'reply-to':
289 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
290 break;
291 default:
292 // Add it to our grand headers array.
293 $headers[ trim( $name ) ] = trim( $content );
294 break;
295 }
296 }
297 }
298 }
299
300 // Empty out the values that may be set.
301 $phpmailer->clearAllRecipients();
302 $phpmailer->clearAttachments();
303 $phpmailer->clearCustomHeaders();
304 $phpmailer->clearReplyTos();
305 $phpmailer->Body = '';
306 $phpmailer->AltBody = '';
307
308 // Set "From" name and email.
309
310 // If we don't have a name from the input headers.
311 if ( ! isset( $from_name ) ) {
312 $from_name = 'WordPress';
313 }
314 if ( ! isset( $from_email ) ) {
315 // Get the site domain and get rid of www.
316 $sitename = wp_parse_url( network_home_url(), PHP_URL_HOST );
317 $from_email = 'wordpress@';
318
319 if ( null !== $sitename ) {
320 if ( str_starts_with( $sitename, 'www.' ) ) {
321 $sitename = substr( $sitename, 4 );
322 }
323
324 $from_email .= $sitename;
325 }
326 }
327
328 try {
329 $phpmailer->setFrom( $from_email, $from_name, false );
330 } catch ( PHPMailer\PHPMailer\Exception $e ) {
331 // error_log(esc_html__('Error in forwar email check & log : ', 'check-email').$e->getMessage());
332 return false;
333 }
334
335 // Set mail's subject and body.
336 $phpmailer->Subject = $subject;
337 $phpmailer->Body = $message;
338
339 // Set destination addresses, using appropriate methods for handling addresses.
340 $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' );
341
342 foreach ( $address_headers as $address_header => $addresses ) {
343 if ( empty( $addresses ) ) {
344 continue;
345 }
346
347 foreach ( (array) $addresses as $address ) {
348 try {
349 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>".
350 $recipient_name = '';
351
352 if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) {
353 if ( count( $matches ) === 3 ) {
354 $recipient_name = $matches[1];
355 $address = $matches[2];
356 }
357 }
358
359 switch ( $address_header ) {
360 case 'to':
361 $phpmailer->addAddress( $address, $recipient_name );
362 break;
363 case 'cc':
364 $phpmailer->addCc( $address, $recipient_name );
365 break;
366 case 'bcc':
367 $phpmailer->addBcc( $address, $recipient_name );
368 break;
369 case 'reply_to':
370 $phpmailer->addReplyTo( $address, $recipient_name );
371 break;
372 }
373 } catch ( PHPMailer\PHPMailer\Exception $e ) {
374 continue;
375 }
376 }
377 }
378
379 // Set to use PHP's mail().
380 $phpmailer->isMail();
381
382 // Set Content-Type and charset.
383
384 // If we don't have a Content-Type from the input headers.
385 if ( ! isset( $content_type ) ) {
386 $content_type = 'text/html';
387 }
388
389
390 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
391
392 $phpmailer->ContentType = $content_type;
393
394 // Set whether it's plaintext, depending on $content_type.
395 if ( 'text/html' === $content_type ) {
396 $phpmailer->isHTML( true );
397 }
398
399 // If we don't have a charset from the input headers.
400 if ( ! isset( $charset ) ) {
401 $charset = get_bloginfo( 'charset' );
402 }
403
404
405 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
406
407 // Set custom headers.
408 if ( ! empty( $headers ) ) {
409 foreach ( (array) $headers as $name => $content ) {
410 // Only add custom headers not added automatically by PHPMailer.
411 if ( ! in_array( $name, array( 'MIME-Version', 'X-Mailer' ), true ) ) {
412 try {
413 $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
414 } catch ( PHPMailer\PHPMailer\Exception $e ) {
415 continue;
416 }
417 }
418 }
419
420 if ( false !== stripos( $content_type, 'multipart' ) && ! empty( $boundary ) ) {
421 $phpmailer->addCustomHeader( sprintf( 'Content-Type: %s; boundary="%s"', $content_type, $boundary ) );
422 }
423 }
424
425 if ( ! empty( $attachments ) ) {
426 foreach ( $attachments as $filename => $attachment ) {
427 $filename = is_string( $filename ) ? $filename : '';
428
429 try {
430 $phpmailer->addAttachment( $attachment, $filename );
431 } catch ( PHPMailer\PHPMailer\Exception $e ) {
432 continue;
433 }
434 }
435 }
436
437 /**
438 * Fires after PHPMailer is initialized.
439 *
440 * @since 2.2.0
441 *
442 * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference).
443 */
444 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
445
446 $mail_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
447
448 // Send!
449 try {
450 $send = $phpmailer->send();
451 return $send;
452 } catch ( PHPMailer\PHPMailer\Exception $e ) {
453 // error_log(esc_html__('Error in forwar email send check & log : ', 'check-email').$e->getMessage());
454 return false;
455 }
456 }
457
458 function ck_mail_create_error_logs() {
459
460 global $wpdb;
461
462 $table_name = $wpdb->prefix . 'check_email_error_logs';
463 $charset_collate = $wpdb->get_charset_collate();
464 // phpcs:disable.
465 if ( $wpdb->get_var( $wpdb->prepare( "show tables like %s",$wpdb->esc_like( $table_name )) ) != $table_name ) {
466
467 $sql = "CREATE TABLE IF NOT EXISTS `$table_name` (
468 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
469 `check_email_log_id` INT DEFAULT NULL,
470 `content` TEXT DEFAULT NULL,
471 `initiator` TEXT DEFAULT NULL,
472 `event_type` TINYINT UNSIGNED NOT NULL DEFAULT '0',
473 `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
474 PRIMARY KEY (id)
475 )
476 ENGINE='InnoDB'
477 {$charset_collate};";
478
479 $wpdb->query($sql);
480 }
481 // phpcs:enable.
482 }
483
484 function ck_mail_create_spam_analyzer_table() {
485
486 global $wpdb;
487
488 $table_name = $wpdb->prefix . 'check_email_spam_analyzer';
489 $charset_collate = $wpdb->get_charset_collate();
490 // phpcs:disable.
491 if ( $wpdb->get_var( $wpdb->prepare( "show tables like %s",$wpdb->esc_like( $table_name )) ) != $table_name ) {
492
493 $sql = "CREATE TABLE IF NOT EXISTS `$table_name` (
494 `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
495 `html_content` LONGTEXT DEFAULT NULL,
496 `spam_assassin` LONGTEXT DEFAULT NULL,
497 `authenticated` LONGTEXT DEFAULT NULL,
498 `block_listed` TEXT DEFAULT NULL,
499 `broken_links` TEXT DEFAULT NULL,
500 `final_score` TEXT DEFAULT NULL,
501 `test_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
502 `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
503 PRIMARY KEY (`id`)
504 )
505 ENGINE='InnoDB'
506 {$charset_collate};";
507
508 $wpdb->query($sql);
509 }
510 // phpcs:enable.
511 }
512
513 function ck_mail_insert_spam_analyzer($data_to_insert) {
514
515 global $wpdb;
516
517 $table_name = $wpdb->prefix . 'check_email_spam_analyzer';
518 $wpdb->insert( $table_name, $data_to_insert ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
519 }
520 function ck_mail_insert_error_logs($data_to_insert) {
521
522 global $wpdb;
523
524 $table_name = $wpdb->prefix . 'check_email_error_logs';
525 $wpdb->insert( $table_name, $data_to_insert ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
526 }
527
528 function ck_mail_local_file_get_contents($file_path){
529
530 // Include WordPress Filesystem API
531 if ( ! function_exists( 'WP_Filesystem' ) ) {
532 require_once( ABSPATH . 'wp-admin/includes/file.php' );
533 }
534
535 // Initialize the API
536 global $wp_filesystem;
537 if ( ! WP_Filesystem() ) {
538 return false;
539 }
540 // Check if the file exists
541 if ( $wp_filesystem->exists( $file_path ) ) {
542 // Read the file content
543 $file_content = $wp_filesystem->get_contents( $file_path );
544 return $file_content;
545 } else {
546 return false;
547 }
548
549 }
550
551 function ck_mail_update_network_settings() {
552 // Check nonce
553 check_ajax_referer( 'ck_mail_ajax_check_nonce', 'nonce' );
554
555 // Check if user is allowed to manage network options
556 if ( ! current_user_can( 'manage_check_email' ) ) {
557 wp_send_json_error(esc_html__('Unauthorized user', 'check-email') );
558 return;
559 }
560 if ( isset( $_POST['check-email-log-global'] ) ) {
561 $all_fields = array_map('sanitize_text_field', wp_unslash($_POST['check-email-log-global']));
562
563 // Sanitize all the key
564 if ( ! empty( $all_fields ) ) {
565 foreach ($all_fields as $key => $value) {
566 $all_fields[sanitize_key( $key ) ] = sanitize_text_field( $value );
567 }
568 $all_fields['enable_smtp'] = 1;
569
570 if (!isset($all_fields['enable_global'])) {
571 $all_fields['enable_global'] = 0;
572 }
573 $old_settings = get_site_option('check-email-log-global-smtp');
574
575 if ( ! empty( $old_settings ) && is_array( $old_settings ) ) {
576 $updated_settings = array_merge( $old_settings, $all_fields );
577 } else {
578 $updated_settings = $all_fields;
579 }
580 update_site_option( 'check-email-log-global-smtp', $updated_settings );
581 if ( isset($all_fields['mailer'] ) == 'outlook' && isset( $_POST['check-email-outlook-options'] ) ) {
582 $outlook_fields = array_map('sanitize_text_field', wp_unslash($_POST['check-email-outlook-options']));
583 if(isset($outlook_fields['client_id']) && !empty($outlook_fields['client_id'])){
584 $outlook_option['client_id'] = base64_encode($outlook_fields['client_id']);
585 }
586 if(isset($outlook_fields['client_secret']) && !empty($outlook_fields['client_secret'])){
587 $outlook_option['client_secret'] = base64_encode($outlook_fields['client_secret']);
588 }
589 $auth = new CheckEmail\Core\Auth( 'outlook' );
590 $auth->update_mailer_option( $outlook_option );
591 }
592 wp_send_json_success();
593 }
594 } else {
595 wp_send_json_error(esc_html__('Invalid input', 'check-email') );
596 }
597 }
598
599 add_action( 'wp_ajax_update_network_settings', 'ck_mail_update_network_settings' );
600
601 function ck_mail_check_dns() {
602 // Check nonce
603 if ( isset( $_POST['ck_mail_security_nonce'] ) ) {
604 if ( !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ck_mail_security_nonce'] ) ), 'ck_mail_security_nonce' ) ){
605 die( '-1' );
606 }
607
608 // Check if user is allowed to manage network options
609 if ( ! current_user_can( 'manage_check_email' ) ) {
610 wp_send_json_error(esc_html__('Unauthorized user', 'check-email') );
611 return;
612 }
613 // $api_url = 'http://127.0.0.1:8000/custom-api/check-dns';
614 $api_url = 'https://enchain.tech/custom-api/check-dns';
615 $domain = null;
616 if ( isset( $_POST['domain'] ) ) {
617 $domain = sanitize_text_field( wp_unslash( $_POST['domain'] ) );
618 }
619 $api_params = array(
620 'domain' => $domain,
621 );
622
623 $response = wp_remote_post( $api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
624
625 if ( ! is_wp_error( $response ) ) {
626 $response = wp_remote_retrieve_body( $response );
627 $response = json_decode( $response, true );
628 if (isset($response['is_error'])) {
629 $result = $response;
630 }else{
631 $result['is_error'] = 0;
632 $result['data'] = $response;
633 }
634 echo wp_json_encode( $result );
635 } else {
636 $error_message = $response->get_error_message();
637 echo wp_json_encode( array( 'response' => $error_message ) );
638 }
639 }
640 wp_die();
641 }
642
643 function ck_email_verify($email) {
644 $spoof_valid = 1;
645 $dns_valid = 1;
646 $email_valid = 1;
647 if (class_exists('\Egulias\EmailValidator\EmailValidator')) {
648 $validator = new \Egulias\EmailValidator\EmailValidator();
649 // ietf.org has MX records signaling a server with email capabilities
650 $email_valid = $validator->isValid($email, new \Egulias\EmailValidator\Validation\RFCValidation());
651 $dns_valid = $validator->isValid($email, new \Egulias\EmailValidator\Validation\DNSCheckValidation());
652 $spoof_valid = $validator->isValid($email, new \Egulias\EmailValidator\Validation\Extra\SpoofCheckValidation());
653 }
654 $response['status'] = true;
655 $response['spoof_valid'] = ($spoof_valid) ? 1 : 0;
656 $response['dns_valid'] = ($dns_valid) ? 1 : 0;
657 $response['email_valid'] = ($email_valid) ? 1 : 0;
658 return $response;
659 }
660
661 add_action( 'wp_ajax_check_dns', 'ck_mail_check_dns' );
662
663 function ck_mail_check_email_analyze() {
664 // Check nonce
665 if (isset($_POST['ck_mail_security_nonce'])) {
666 if ( !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ck_mail_security_nonce'] ) ), 'ck_mail_security_nonce' ) ){
667 die( '-1' );
668 }
669 if ( ! current_user_can( 'manage_check_email' ) ) {
670 wp_send_json_error(esc_html__('Unauthorized user', 'check-email') );
671 return;
672 }
673 // $api_url = 'http://127.0.0.1:8000/custom-api/email-analyze';
674 $api_url = 'https://enchain.tech/custom-api/email-analyze';
675 $current_user = wp_get_current_user();
676 $email = $current_user->user_email;
677 if ( !empty( $email ) ) {
678 $to = 'plugintest@check-email.tech';
679 $title = esc_html__("Test email to analyze check email", "check-email");
680 $body = esc_html__('This test email will analyze score', "check-email");
681 $site_name = get_bloginfo('name');
682 $headers = [
683 'Content-Type: text/html; charset=UTF-8',
684 'From: '.$site_name .'<'.$email.'>'
685 ];
686 wp_mail($to, $title, $body, $headers);
687 }
688 $api_params = array(
689 'email' => $email,
690 );
691
692 if (function_exists('ck_mail_create_spam_analyzer_table') ) {
693 ck_mail_create_spam_analyzer_table();
694 }
695
696 $response = wp_remote_post( $api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
697
698 if ( ! is_wp_error( $response ) ) {
699 $response = wp_remote_retrieve_body( $response );
700 $response = json_decode( $response, true );
701 if (isset($response['is_error']) && $response['is_error'] == 1) {
702 $result = $response;
703 }else{
704 $result['is_error'] = 0;
705 $result['data'] = $response;
706 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated , WordPress.Security.ValidatedSanitizedInput.MissingUnslash , WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
707 $ip_address = $_SERVER['SERVER_ADDR']; // Replace with your target IP
708 $blocklist = is_ip_blocked($ip_address);
709 $result['blocklist'] = $blocklist;
710 $result['ip_address'] = $ip_address;
711 $spam_final_score = 0;
712 $block_final_score = 0;
713 $auth_final_score = 0;
714 $link_final_score = 0;
715 if ( isset( $response['spamcheck_result'] )) {
716 $spam_score = $response['spamcheck_result']['score'];
717 if ($spam_score > 0) {
718 $spam_final_score = 2.5;
719 } else if ($spam_score < 0 && $spam_score > -5) {
720 $spam_final_score = 1.5;
721 } else if ($spam_score < -5) {
722 $spam_final_score = 0;
723 }
724 }
725 $block_count = 0;
726 foreach ($blocklist as $key => $value) {
727 if($value['status']){
728 $block_count +=1;
729 }
730 }
731 if ($block_count == 0) {
732 $block_final_score = 2.5;
733 } else if ($block_count > 0 && $block_count <= 12) {
734 $block_final_score = 1.5;
735 } else if ($block_count > 12) {
736 $block_final_score = 0;
737 }
738 if ( isset( $response['authenticated'] )) {
739 $auth_count = 0;
740 foreach ($response['authenticated'] as $key => $value) {
741 if( ! $value['status'] ){
742 $auth_count +=1;
743 }
744 }
745 if ($auth_count == 0) {
746 $auth_final_score = 2.5;
747 } else if ($auth_count > 0 && $auth_count < 3) {
748 $auth_final_score = 1.5;
749 } else if ($auth_count >= 3) {
750 $auth_final_score = 0;
751 }
752 }
753 if ( isset( $response['links'] ) ) {
754 $link_count = 0;
755 foreach ($response['links'] as $key => $value) {
756 if( $value['status'] > 200 ){
757 $link_count +=1;
758 }
759 }
760 if ($link_count > 0) {
761 $link_final_score = 0;
762 } else {
763 $link_final_score = 2.5;
764 }
765 }
766 $final_score = ($link_final_score + $auth_final_score + $block_final_score + $spam_final_score);
767 $spam_score_get = get_option('check_email_spam_score_' . $current_user->user_email,[]);
768 $current_date_time = current_time('Y-m-d H:i:s');
769 $spam_score_get[$current_date_time] = array('score' => $final_score, 'datetime' => $current_date_time);
770 $spam_score = array_reverse($spam_score_get);
771 $n = 1;
772 foreach (array_reverse($spam_score_get) as $key => $value) {
773 if( $n > 15 ){
774 unset($spam_score[$key]);
775 }
776 $n++;
777 }
778 update_option('check_email_spam_score_' . $current_user->user_email, $spam_score);
779 $result['previous_spam_score'] = $spam_score;
780 $result['previous_email_result'] = ck_email_verify($email);
781 $data_to_insert = array(
782 'html_content' => wp_json_encode($response['html_tab']),
783 'spam_assassin' => wp_json_encode(array('data'=> $response['spamcheck_result'],'spam_final_score' => $spam_final_score)),
784 'authenticated' => wp_json_encode(array('data'=> $response['authenticated'],'auth_final_score' => $auth_final_score)),
785 'block_listed' => wp_json_encode(array('data'=> $blocklist,'block_final_score' => $block_final_score)),
786 'broken_links' => wp_json_encode(array('data'=> $response['links'],'link_final_score' => $link_final_score)),
787 'final_score' => $final_score,
788 'test_date' => $current_date_time,
789 );
790 if ( function_exists('ck_mail_insert_spam_analyzer') ) {
791 ck_mail_insert_spam_analyzer($data_to_insert);
792 }
793 }
794 echo wp_json_encode( $result );
795 } else {
796 $error_message = $response->get_error_message();
797 echo wp_json_encode( array( 'response' => $error_message ) );
798 }
799 }
800 wp_die();
801 }
802
803 add_action( 'wp_ajax_check_email_analyze', 'ck_mail_check_email_analyze' );
804
805 add_action('wp_ajax_checkmail_save_admin_fcm_token', 'checkmail_save_admin_fcm_token');
806
807 function checkmail_save_admin_fcm_token() {
808 $result['status'] = false;
809 if (!isset($_POST['ck_mail_security_nonce'])) {
810 return;
811 }
812 if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ck_mail_security_nonce'])), 'ck_mail_security_nonce')) {
813 return;
814 }
815 if (isset($_POST['token']) && !empty($_POST['token'])) {
816
817 $current_user = wp_get_current_user();
818
819 if (in_array('administrator', (array) $current_user->roles)) {
820
821 $device_tokens = get_option('checkmail_admin_fcm_token');
822 if (!is_array($device_tokens)) {
823 $device_tokens = [];
824 }
825 $new_token = sanitize_text_field(wp_unslash(($_POST['token'] )));
826
827 if (!in_array($new_token, $device_tokens)) {
828 $device_tokens[] = $new_token;
829 }
830 $device_tokens = array_slice(array_unique($device_tokens), -5);
831 update_option('checkmail_admin_fcm_token', $device_tokens);
832 $result['status'] = true;
833 }
834 }
835 echo wp_json_encode( $result );
836 wp_die();
837 }
838
839
840
841
842 function is_ip_blocked($ip) {
843 $dnsbl_list = [
844 "zen.spamhaus.org",
845 "bl.spamcop.net",
846 "dnsbl.sorbs.net",
847 "b.barracudacentral.org",
848 "spam.dnsbl.sorbs.net",
849 "pbl.spamhaus.org",
850 "xbl.spamhaus.org",
851 "dbl.spamhaus.org",
852 "cbl.abuseat.org",
853 "psbl.surriel.com",
854 "rbl.spamlab.com",
855 "rbl.dns-servicios.com",
856 "dnsbl.spfbl.net",
857 "ipbl.mailspike.net",
858 "aspews.ext.sorbs.net",
859 "ubl.unsubscore.com",
860 "dnsbl.kempt.net",
861 "truncate.gbudb.net",
862 "rbl.efnetrbl.org",
863 "dnsbl-1.uceprotect.net",
864 "all.s5h.net",
865 "dnsbl.inps.de",
866 "dnsbl.dronebl.org",
867 "hostkarma.junkemailfilter.com"
868 ];
869 $reversed_ip = implode(".", array_reverse(explode(".", $ip)));
870 $blocked_on = [];
871
872 foreach ($dnsbl_list as $blocklist) {
873 $query = $reversed_ip . "." . $blocklist;
874 // Perform DNS lookup
875 $outpt = checkdnsrr($query, "A");
876 if ($outpt) {
877 $blocked_on[] = array('status' => 1,'ip' => $blocklist);
878 }else{
879 $blocked_on[] = array('status' => 0,'ip' => $blocklist);
880 }
881 }
882 return $blocked_on;
883 }
884
885
886 // email and phone encoding start
887 /**
888 * Define filter-priority constant, unless it has already been defined.
889 */
890 if ( ! defined( 'CHECK_EMAIL_E_FILTER_PRIORITY' ) ) {
891 define(
892 'CHECK_EMAIL_E_FILTER_PRIORITY',
893 (integer) get_option( 'check_email_e_filter_priority', 2000 )
894 );
895 }
896
897 if ( ! defined( 'CHECK_EMAIL_E_REGEXP' ) ) {
898 define(
899 'CHECK_EMAIL_E_REGEXP',
900 '{
901 (?:mailto:)? # Optional mailto:
902 (?:
903 [-!#$%&*+/=?^_`.{|}~\w\x80-\xFF]+ # Local part before @
904 |
905 ".*?" # Quoted local part
906 )
907 \@ # At sign (@)
908 (?:
909 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ # Domain name
910 |
911 \[[\d.a-fA-F:]+\] # IPv4/IPv6 address
912 )
913 }xi'
914 );
915 }
916
917
918 $encode_options = get_option('check-email-email-encode-options', true);
919 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
920 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
921 if ( $is_enable && $email_using == 'filters' ) {
922 foreach ( array( 'the_content', 'the_excerpt', 'widget_text', 'comment_text', 'comment_excerpt' ) as $filter ) {
923 add_filter( $filter, 'check_email_e_encode_emails', CHECK_EMAIL_E_FILTER_PRIORITY );
924 }
925 }
926 if ( $is_enable && $email_using == 'full_page' ) {
927 add_action( 'wp', 'check_email_full_page_scanner',999 );
928 }
929
930 add_action( 'init', 'check_email_e_register_shortcode', 2000 );
931
932 function check_email_e_register_shortcode() {
933 if ( ! shortcode_exists( 'checkmail-encode' ) ) {
934 add_shortcode( 'checkmail-encode', 'check_email_e_shortcode' );
935 }
936 }
937
938 function check_email_rot47($str) {
939 $rotated = '';
940 foreach (str_split($str) as $char) {
941 $ascii = ord($char);
942 if ($ascii >= 33 && $ascii <= 126) {
943 $rotated .= chr(33 + (($ascii + 14) % 94));
944 } else {
945 $rotated .= $char;
946 }
947 }
948 return $rotated;
949 }
950
951 function check_email_encode_str( $string, $hex = false ) {
952 $encode_options = get_option('check-email-email-encode-options', true);
953 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
954 if (strpos($string, 'mailto:') !== false) {
955 $string = str_replace('mailto:', '', $string);
956 switch ($email_technique) {
957 case 'css_direction':
958 $reversed_email = strrev($string);
959 // Wrap it with the span and necessary CSS
960 return 'mailto:'.esc_html($reversed_email);
961 break;
962 case 'rot_13':
963 $encoded_email = check_email_rot13($string);
964 return 'mailto:'.esc_html($encoded_email);
965 break;
966 case 'rot_47':
967 $encoded_email = check_email_rot47($string);
968 return 'mailto:'.esc_html($encoded_email);
969 break;
970
971 default:
972 # code...
973 break;
974 }
975 }else{
976 switch ($email_technique) {
977 case 'css_direction':
978 $reversed_email = strrev($string);
979 // Wrap it with the span and necessary CSS
980 return ' <span style="direction: rtl; unicode-bidi: bidi-override;">' . esc_html($reversed_email) . '</span>';
981 break;
982 case 'rot_13':
983 $encoded_email = check_email_rot13($string);
984 return ' <span class="check-email-encoded-email" >' . esc_html($encoded_email).' </span>';
985 break;
986 case 'rot_47':
987 $encoded_email = check_email_rot47($string);
988 return ' <span class="check-email-rot47-email" >' . esc_html($encoded_email).' </span>';
989 break;
990
991 default:
992 # code...
993 break;
994 }
995 }
996
997
998 $chars = str_split( $string );
999 $string_length = (int) abs(crc32($string) / strlen($string));
1000 $length = max($string_length, 1);
1001 $seed = random_int($length, PHP_INT_MAX);
1002
1003 foreach ( $chars as $key => $char ) {
1004 $ord = ord( $char );
1005
1006 if ( $ord < 128 ) { // ignore non-ascii chars
1007 $r = ( $seed * ( 1 + $key ) ) % 100; // pseudo "random function"
1008
1009 if ( $r > 75 && $char !== '@' && $char !== '.' ); // plain character (not encoded), except @-signs and dots
1010 else if ( $hex && $r < 25 ) $chars[ $key ] = '%' . bin2hex( $char ); // hex
1011 else if ( $r < 45 ) $chars[ $key ] = '&#x' . dechex( $ord ) . ';'; // hexadecimal
1012 else $chars[ $key ] = "&#{$ord};"; // decimal (ascii)
1013 }
1014 }
1015
1016 return implode( '', $chars );
1017 }
1018
1019 function check_email_e_shortcode( $attributes, $content = '' ) {
1020 $atts = shortcode_atts( array(
1021 'link' => null,
1022 'class' => null,
1023 ), $attributes, 'checkmail-encode' );
1024
1025
1026 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1027
1028 if ( ! empty( $atts[ 'link' ] ) ) {
1029 $link = esc_url( $atts[ 'link' ], null, 'shortcode' );
1030
1031 if ( $link === '' ) {
1032 return $method( $content );
1033 }
1034
1035 if ( empty( $atts[ 'class' ] ) ) {
1036 return sprintf(
1037 '<a href="%s">%s</a>',
1038 $method( $link ),
1039 $method( $content )
1040 );
1041 }
1042
1043 return sprintf(
1044 '<a href="%s" class="%s">%s</a>',
1045 $method( $link ),
1046 esc_attr( $atts[ 'class' ] ),
1047 $method( $content )
1048 );
1049 }
1050
1051 return $method( $content );
1052 }
1053
1054 function check_email_e_encode_emails( $string ) {
1055 if ( ! is_string( $string ) ) {
1056 return $string;
1057 }
1058 // abort if `check_email_e_at_sign_check` is true and `$string` doesn't contain a @-sign
1059 if ( apply_filters( 'check_email_e_at_sign_check', true ) && strpos( $string, '@' ) === false ) {
1060 return $string;
1061 }
1062 // override encoding function with the 'check_email_e_method' filter
1063 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1064
1065 $regexp = apply_filters( 'check_email_e_regexp', CHECK_EMAIL_E_REGEXP );
1066
1067 $callback = function ( $matches ) use ( $method ) {
1068 return $method( $matches[ 0 ] );
1069 };
1070
1071 if ( has_filter( 'check_email_e_callback' ) ) {
1072 $callback = apply_filters( 'check_email_e_callback', $callback, $method );
1073 return preg_replace_callback( $regexp, $callback, $string );
1074 }
1075
1076 return preg_replace_callback( $regexp, $callback, $string );
1077 }
1078
1079 function check_email_full_page_scanner() {
1080 if(!is_admin() ) {
1081 ob_start('check_email_full_page_callback');
1082 }
1083 }
1084 function check_email_full_page_callback($string) {
1085 return check_email_e_encode_emails($string);
1086 }
1087
1088
1089 add_action( 'wp_enqueue_scripts', 'ck_mail_enqueue_encoder_js' );
1090
1091 function ck_mail_enqueue_encoder_js() {
1092 $encode_options = get_option('check-email-email-encode-options', true);
1093 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
1094 if ( $is_enable ) {
1095 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
1096 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
1097
1098 $check_email = wpchill_check_email();
1099 $plugin_dir_url = plugin_dir_url( $check_email->get_plugin_file() );
1100 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1101 wp_register_script( 'checkemail_encoder', $plugin_dir_url . 'assets/js/check-email-front'. $suffix .'.js', array(), $check_email->get_version(), true );
1102 $data = array();
1103 $data['email_using'] = $email_using;
1104 $data['is_enable'] = $is_enable;
1105 $data['email_technique'] = $email_technique;
1106
1107 wp_localize_script( 'checkemail_encoder', 'checkemail_encoder_data', $data );
1108 wp_enqueue_script( 'checkemail_encoder' );
1109 }
1110 }
1111
1112 function check_email_rot13( $string ) {
1113
1114 $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1115 $to = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
1116
1117 return strtr( $string, $from, $to );
1118 }
1119
1120 // email and phone encoding end
1121
1122 function check_email_track_email_open() {
1123 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1124 if (isset($_GET['action']) && $_GET['action'] === 'check_email_track_email_open' && isset($_GET['open_tracking_id']) && isset($_GET['_wpnonce'])) {
1125 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1126 if (!check_email_verify_extended_nonce(sanitize_text_field( wp_unslash($_GET['_wpnonce'])))) {
1127 return false;
1128 }
1129 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1130 $open_tracking_id = absint($_GET['open_tracking_id']);
1131
1132 if ($open_tracking_id) {
1133 global $wpdb;
1134 $table_name = $wpdb->prefix . 'check_email_log';
1135 $query = $wpdb->prepare(
1136 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1137 "SELECT * FROM {$table_name} WHERE open_tracking_id = %s",
1138 $open_tracking_id
1139 );
1140 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
1141 $record = $wpdb->get_row($query);
1142
1143 if ($record) {
1144 $data_to_update = [
1145 'open_count' => $record->open_count + 1
1146 ];
1147 $where = [
1148 'open_tracking_id' => $open_tracking_id,
1149 ];
1150 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
1151 $wpdb->update( $table_name, $data_to_update, $where );
1152 header("Content-Type: image/png");
1153 echo esc_html(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wcAAgMBAptL0ygAAAAASUVORK5CYII='));
1154 exit;
1155 }
1156 }
1157 }
1158
1159 }
1160 add_action('init', 'check_email_track_email_open');
1161
1162 function check_email_generate_extended_nonce($action = -1, $lifetime = WEEK_IN_SECONDS) {
1163 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1164 return wp_create_nonce($action . $i);
1165 }
1166
1167 function check_email_verify_extended_nonce($nonce, $action = -1, $lifetime = WEEK_IN_SECONDS) {
1168 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1169
1170 if (wp_verify_nonce($nonce, $action . $i)) {
1171 return true;
1172 }
1173 if (wp_verify_nonce($nonce, $action . ($i - 1))) {
1174 return true;
1175 }
1176 return false;
1177 }
1178
1179 function check_email_content_with_tracking($open_tracking_id) {
1180 $nonce = check_email_generate_extended_nonce();
1181 $tracking_url = add_query_arg(
1182 array(
1183 '_wpnonce'=>$nonce,
1184 'open_tracking_id' => $open_tracking_id,
1185 'action' => 'check_email_track_email_open',
1186 ),
1187 site_url('/check-email-tracking/')
1188 );
1189 $tracking_url = esc_url_raw($tracking_url);
1190 // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
1191 $email_content = "<img src='$tracking_url' class='check-email-tracking' alt='' width='1' height='1' style='display:none;' />";
1192 return $email_content;
1193 }
1194
1195 if ( is_admin() ) {
1196
1197 function checmail_dashboard_widget() {
1198 echo '<canvas id="checkmail-dashboard-chart" style="width: 100%; height: 250px;"></canvas>';
1199 echo '
1200 <div style="margin-top: 10px; text-align: center; display: flex; justify-content: space-between; align-items: center;">
1201 <div>
1202 <select id="checkmail-dashboard-date-range">
1203 <option value="7">'.esc_html__('Last 7 Days', 'check-email').'</option>
1204 <option value="14">'.esc_html__('Last 14 Days', 'check-email').'</option>
1205 <option value="30">'.esc_html__('Last 30 Days', 'check-email').'</option>
1206 </select>
1207 </div>
1208 <div style="margin-top: 10px; text-align: center; font-size: 14px;">
1209 <p><span style="color: blue; font-weight: bold;" id="js_checkmail_total"></span> |
1210 <span style="color: green; font-weight: bold;" id="js_checkmail_sent"></span> |
1211 <span style="color: red; font-weight: bold;" id="js_checkmail_failed"></span></p>
1212 </div>
1213 </div>
1214 ';
1215 }
1216
1217 function add_checmail_dashboard_widget() {
1218 $option = get_option( 'check-email-log-core' );
1219
1220 if(!isset( $option['enable_dashboard_widget']) || (isset( $option['enable_dashboard_widget']) && $option['enable_dashboard_widget'] ) ){
1221 wp_add_dashboard_widget(
1222 'checmail_dashboard_widget',
1223 esc_html__('Check & Log Email Activity', 'check-email'),
1224 'checmail_dashboard_widget'
1225 );
1226 }
1227 }
1228 add_action('wp_dashboard_setup', 'add_checmail_dashboard_widget');
1229
1230 function custom_dashboard_scripts($hook) {
1231 if ($hook !== 'index.php') return;
1232 $option = get_option( 'check-email-log-core' );
1233 if(!isset( $option['enable_dashboard_widget']) || (isset( $option['enable_dashboard_widget']) && $option['enable_dashboard_widget'] ) ){
1234 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1235 wp_enqueue_script('chartjs', CK_MAIL_URL . 'assets/js/admin/chart.js', [], CK_MAIL_VERSION, true);
1236 wp_register_script('checkmail-dashboard-chart', CK_MAIL_URL . 'assets/js/admin/checkmail-dashboard-chart'. $suffix .'.js', ['jquery','chartjs'], CK_MAIL_VERSION, true);
1237 $data = array(
1238 'ajax_url' => admin_url( 'admin-ajax.php' ),
1239 'ck_mail_security_nonce' => wp_create_nonce('ck_mail_ajax_check_nonce'),
1240 );
1241
1242 wp_localize_script( 'checkmail-dashboard-chart', 'checkmail_chart', $data );
1243 wp_enqueue_script( 'checkmail-dashboard-chart' );
1244 }
1245
1246
1247
1248 }
1249 add_action('admin_enqueue_scripts', 'custom_dashboard_scripts');
1250
1251 function get_email_analytics_data() {
1252 if( !isset( $_GET['ck_mail_security_nonce'] ) || isset( $_GET['ck_mail_security_nonce'] ) && !wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['ck_mail_security_nonce'] ) ), 'ck_mail_ajax_check_nonce' ) ) {
1253 echo esc_html__('security_nonce_not_verified', 'check-email');
1254 die();
1255 }
1256 if ( !current_user_can( 'manage_options' ) ) {
1257 die();
1258 }
1259 global $wpdb;
1260
1261 $table_name = $wpdb->prefix . 'check_email_log';
1262 $ck_days = isset($_GET['ck_days']) ? sanitize_text_field( wp_unslash( $_GET['ck_days'] ) ) : 7;
1263 $query = $wpdb->prepare(
1264 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1265 "SELECT * FROM $table_name WHERE sent_date >= CURDATE() - INTERVAL %d DAY",
1266 $ck_days
1267 );
1268 // phpcs:ignore InterpolatedNotPrepared
1269 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
1270 $results = $wpdb->get_results($query);
1271
1272 $data = [
1273 'labels' => [],
1274 'sent' => [],
1275 'failed' => [],
1276 ];
1277
1278
1279 $daily_counts = [];
1280 foreach ($results as $row) {
1281 $created_at = $row->sent_date;
1282 $status = $row->result;
1283 $date = gmdate('M j', strtotime($created_at));
1284 if (!isset($daily_counts[$date])) {
1285 $daily_counts[$date] = ['sent' => 0, 'failed' => 0];
1286 }
1287 if ($status == 1) {
1288 $daily_counts[$date]['sent']++;
1289 } else {
1290 $daily_counts[$date]['failed']++;
1291 }
1292 }
1293 ksort($daily_counts);
1294 foreach ($daily_counts as $date => $counts) {
1295 $data['labels'][] = $date;
1296 $data['sent'][] = $counts['sent'];
1297 $data['failed'][] = $counts['failed'];
1298 }
1299
1300 $data['total_mail'] = array_sum($data['sent']) + array_sum($data['failed']);
1301 $data['total_failed'] = array_sum($data['failed']);
1302 $data['total_sent'] = array_sum($data['sent']);
1303
1304 wp_send_json($data);
1305 }
1306 add_action('wp_ajax_get_email_analytics', 'get_email_analytics_data');
1307
1308 }
1309