PluginProbe ʕ •ᴥ•ʔ
Check & Log Email – Easy Email Testing & Mail logging / 2.0.5.1
Check & Log Email – Easy Email Testing & Mail logging v2.0.5.1
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 1 year ago Util 1 year ago Check_Email_Encode_Tab.php 1 year ago Check_Email_Notify_Tab.php 1 year ago Check_Email_SMTP_Tab.php 1 year ago class-check-email-header-parser.php 1 year ago class-check-email-log-autoloader.php 1 year ago class-check-email-newsletter.php 1 year ago deactivate-feedback.php 1 year ago helper-function.php 1 year ago install.php 1 year ago
helper-function.php
1307 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,
502 `created_at` TIMESTAMP 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 $body = $body;
682 $site_name = get_bloginfo('name');
683 $headers = [
684 'Content-Type: text/html; charset=UTF-8',
685 'From: '.$site_name .'<'.$email.'>'
686 ];
687 wp_mail($to, $title, $body, $headers);
688 }
689 $api_params = array(
690 'email' => $email,
691 );
692
693 if (function_exists('ck_mail_create_spam_analyzer_table') ) {
694 ck_mail_create_spam_analyzer_table();
695 }
696
697 $response = wp_remote_post( $api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
698
699 if ( ! is_wp_error( $response ) ) {
700 $response = wp_remote_retrieve_body( $response );
701 $response = json_decode( $response, true );
702 if (isset($response['is_error']) && $response['is_error'] == 1) {
703 $result = $response;
704 }else{
705 $result['is_error'] = 0;
706 $result['data'] = $response;
707 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated , WordPress.Security.ValidatedSanitizedInput.MissingUnslash , WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
708 $ip_address = $_SERVER['SERVER_ADDR']; // Replace with your target IP
709 $blocklist = is_ip_blocked($ip_address);
710 $result['blocklist'] = $blocklist;
711 $result['ip_address'] = $ip_address;
712 $spam_final_score = 0;
713 $block_final_score = 0;
714 $auth_final_score = 0;
715 $link_final_score = 0;
716 if ( isset( $response['spamcheck_result'] )) {
717 $spam_score = $response['spamcheck_result']['score'];
718 if ($spam_score > 0) {
719 $spam_final_score = 2.5;
720 } else if ($spam_score < 0 && $spam_score > -5) {
721 $spam_final_score = 1.5;
722 } else if ($spam_score < -5) {
723 $spam_final_score = 0;
724 }
725 }
726 $block_count = 0;
727 foreach ($blocklist as $key => $value) {
728 if($value['status']){
729 $block_count +=1;
730 }
731 }
732 if ($block_count == 0) {
733 $block_final_score = 2.5;
734 } else if ($block_count > 0 && $block_count <= 12) {
735 $block_final_score = 1.5;
736 } else if ($block_count > 12) {
737 $block_final_score = 0;
738 }
739 if ( isset( $response['authenticated'] )) {
740 $auth_count = 0;
741 foreach ($response['authenticated'] as $key => $value) {
742 if( ! $value['status'] ){
743 $auth_count +=1;
744 }
745 }
746 if ($auth_count == 0) {
747 $auth_final_score = 2.5;
748 } else if ($auth_count > 0 && $auth_count < 3) {
749 $auth_final_score = 1.5;
750 } else if ($auth_count >= 3) {
751 $auth_final_score = 0;
752 }
753 }
754 if ( isset( $response['links'] ) ) {
755 $link_count = 0;
756 foreach ($response['links'] as $key => $value) {
757 if( $value['status'] > 200 ){
758 $link_count +=1;
759 }
760 }
761 if ($link_count > 0) {
762 $link_final_score = 0;
763 } else {
764 $link_final_score = 2.5;
765 }
766 }
767 $final_score = ($link_final_score + $auth_final_score + $block_final_score + $spam_final_score);
768 $spam_score_get = get_option('check_email_spam_score_' . $current_user ->user_email,[]);
769 $current_date_time = current_time('Y-m-d H:i:s');
770 $spam_score_get[$current_date_time] = array('score' => $final_score, 'datetime' => $current_date_time);
771 $spam_score = array_reverse($spam_score_get);
772 $n = 1;
773 foreach (array_reverse($spam_score_get) as $key => $value) {
774 if( $n > 15 ){
775 unset($spam_score[$key]);
776 }
777 $n++;
778 }
779 update_option('check_email_spam_score_' . $current_user ->user_email, $spam_score);
780 $result['previous_spam_score'] = $spam_score;
781 $result['previous_email_result'] = ck_email_verify($email);
782 $data_to_insert = array(
783 'html_content' => wp_json_encode($response['html_tab']),
784 'spam_assassin' => wp_json_encode(array('data'=> $response['spamcheck_result'],'spam_final_score' => $spam_final_score)),
785 'authenticated' => wp_json_encode(array('data'=> $response['authenticated'],'auth_final_score' => $auth_final_score)),
786 'block_listed' => wp_json_encode(array('data'=> $blocklist,'block_final_score' => $block_final_score)),
787 'broken_links' => wp_json_encode(array('data'=> $response['links'],'link_final_score' => $link_final_score)),
788 'final_score' => $final_score,
789 'test_date' => $current_date_time,
790 );
791 if ( function_exists('ck_mail_insert_spam_analyzer') ) {
792 ck_mail_insert_spam_analyzer($data_to_insert);
793 }
794 }
795 echo wp_json_encode( $result );
796 } else {
797 $error_message = $response->get_error_message();
798 echo wp_json_encode( array( 'response' => $error_message ) );
799 }
800 }
801 wp_die();
802 }
803
804 add_action( 'wp_ajax_check_email_analyze', 'ck_mail_check_email_analyze' );
805
806 add_action('wp_ajax_checkmail_save_admin_fcm_token', 'checkmail_save_admin_fcm_token');
807
808 function checkmail_save_admin_fcm_token() {
809 $result['status'] = false;
810 if (!isset($_POST['ck_mail_security_nonce'])) {
811 return;
812 }
813 if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ck_mail_security_nonce'])), 'ck_mail_security_nonce')) {
814 return;
815 }
816 if (isset($_POST['token']) && !empty($_POST['token'])) {
817
818 $current_user = wp_get_current_user();
819
820 if (in_array('administrator', (array) $current_user->roles)) {
821
822 $device_tokens = get_option('checkmail_admin_fcm_token');
823 if (!is_array($device_tokens)) {
824 $device_tokens = [];
825 }
826 $new_token = sanitize_text_field(wp_unslash(($_POST['token'] )));
827
828 if (!in_array($new_token, $device_tokens)) {
829 $device_tokens[] = $new_token;
830 }
831 $device_tokens = array_slice(array_unique($device_tokens), -5);
832 update_option('checkmail_admin_fcm_token', $device_tokens);
833 $result['status'] = true;
834 }
835 }
836 echo wp_json_encode( $result );
837 wp_die();
838 }
839
840
841
842
843 function is_ip_blocked($ip) {
844 $dnsbl_list = [
845 "zen.spamhaus.org",
846 "bl.spamcop.net",
847 "dnsbl.sorbs.net",
848 "b.barracudacentral.org",
849 "spam.dnsbl.sorbs.net",
850 "pbl.spamhaus.org",
851 "xbl.spamhaus.org",
852 "dbl.spamhaus.org",
853 "cbl.abuseat.org",
854 "psbl.surriel.com",
855 "rbl.spamlab.com",
856 "rbl.dns-servicios.com",
857 "dnsbl.spfbl.net",
858 "ipbl.mailspike.net",
859 "aspews.ext.sorbs.net",
860 "ubl.unsubscore.com",
861 "dnsbl.kempt.net",
862 "truncate.gbudb.net",
863 "rbl.efnetrbl.org",
864 "dnsbl-1.uceprotect.net",
865 "all.s5h.net",
866 "dnsbl.inps.de",
867 "dnsbl.dronebl.org",
868 "hostkarma.junkemailfilter.com"
869 ];
870 $reversed_ip = implode(".", array_reverse(explode(".", $ip)));
871 $blocked_on = [];
872
873 foreach ($dnsbl_list as $blocklist) {
874 $query = $reversed_ip . "." . $blocklist;
875 // Perform DNS lookup
876 $outpt = checkdnsrr($query, "A");
877 if ($outpt) {
878 $blocked_on[] = array('status' => 1,'ip' => $blocklist);
879 }else{
880 $blocked_on[] = array('status' => 0,'ip' => $blocklist);
881 }
882 }
883 return $blocked_on;
884 }
885
886
887 // email and phone encoding start
888 /**
889 * Define filter-priority constant, unless it has already been defined.
890 */
891 if ( ! defined( 'CHECK_EMAIL_E_FILTER_PRIORITY' ) ) {
892 define(
893 'CHECK_EMAIL_E_FILTER_PRIORITY',
894 (integer) get_option( 'check_email_e_filter_priority', 2000 )
895 );
896 }
897
898 if ( ! defined( 'CHECK_EMAIL_E_REGEXP' ) ) {
899 define(
900 'CHECK_EMAIL_E_REGEXP',
901 '{
902 (?:mailto:)? # Optional mailto:
903 (?:
904 [-!#$%&*+/=?^_`.{|}~\w\x80-\xFF]+ # Local part before @
905 |
906 ".*?" # Quoted local part
907 )
908 \@ # At sign (@)
909 (?:
910 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ # Domain name
911 |
912 \[[\d.a-fA-F:]+\] # IPv4/IPv6 address
913 )
914 }xi'
915 );
916 }
917
918
919 $encode_options = get_option('check-email-email-encode-options', true);
920 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
921 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
922 if ( $is_enable && $email_using == 'filters' ) {
923 foreach ( array( 'the_content', 'the_excerpt', 'widget_text', 'comment_text', 'comment_excerpt' ) as $filter ) {
924 add_filter( $filter, 'check_email_e_encode_emails', CHECK_EMAIL_E_FILTER_PRIORITY );
925 }
926 }
927 if ( $is_enable && $email_using == 'full_page' ) {
928 add_action( 'wp', 'check_email_full_page_scanner',999 );
929 }
930
931 add_action( 'init', 'check_email_e_register_shortcode', 2000 );
932
933 function check_email_e_register_shortcode() {
934 if ( ! shortcode_exists( 'checkmail-encode' ) ) {
935 add_shortcode( 'checkmail-encode', 'check_email_e_shortcode' );
936 }
937 }
938
939 function check_email_rot47($str) {
940 $rotated = '';
941 foreach (str_split($str) as $char) {
942 $ascii = ord($char);
943 if ($ascii >= 33 && $ascii <= 126) {
944 $rotated .= chr(33 + (($ascii + 14) % 94));
945 } else {
946 $rotated .= $char;
947 }
948 }
949 return $rotated;
950 }
951
952 function check_email_encode_str( $string, $hex = false ) {
953 $encode_options = get_option('check-email-email-encode-options', true);
954 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
955 if (strpos($string, 'mailto:') !== false) {
956 $string = str_replace('mailto:', '', $string);
957 switch ($email_technique) {
958 case 'css_direction':
959 $reversed_email = strrev($string);
960 // Wrap it with the span and necessary CSS
961 return 'mailto:'.esc_html($reversed_email);
962 break;
963 case 'rot_13':
964 $encoded_email = check_email_rot13($string);
965 return 'mailto:'.esc_html($encoded_email);
966 break;
967 case 'rot_47':
968 $encoded_email = check_email_rot47($string);
969 return 'mailto:'.esc_html($encoded_email);
970 break;
971
972 default:
973 # code...
974 break;
975 }
976 }else{
977 switch ($email_technique) {
978 case 'css_direction':
979 $reversed_email = strrev($string);
980 // Wrap it with the span and necessary CSS
981 return ' <span style="direction: rtl; unicode-bidi: bidi-override;">' . esc_html($reversed_email) . '</span>';
982 break;
983 case 'rot_13':
984 $encoded_email = check_email_rot13($string);
985 return ' <span class="check-email-encoded-email" >' . esc_html($encoded_email).' </span>';
986 break;
987 case 'rot_47':
988 $encoded_email = check_email_rot47($string);
989 return ' <span class="check-email-rot47-email" >' . esc_html($encoded_email).' </span>';
990 break;
991
992 default:
993 # code...
994 break;
995 }
996 }
997
998
999 $chars = str_split( $string );
1000 $string_length = (int) abs(crc32($string) / strlen($string));
1001 $length = max($string_length, 1);
1002 $seed = openssl_random_pseudo_bytes($length);
1003
1004 foreach ( $chars as $key => $char ) {
1005 $ord = ord( $char );
1006
1007 if ( $ord < 128 ) { // ignore non-ascii chars
1008 $r = ( $seed * ( 1 + $key ) ) % 100; // pseudo "random function"
1009
1010 if ( $r > 75 && $char !== '@' && $char !== '.' ); // plain character (not encoded), except @-signs and dots
1011 else if ( $hex && $r < 25 ) $chars[ $key ] = '%' . bin2hex( $char ); // hex
1012 else if ( $r < 45 ) $chars[ $key ] = '&#x' . dechex( $ord ) . ';'; // hexadecimal
1013 else $chars[ $key ] = "&#{$ord};"; // decimal (ascii)
1014 }
1015 }
1016
1017 return implode( '', $chars );
1018 }
1019
1020 function check_email_e_shortcode( $attributes, $content = '' ) {
1021 $atts = shortcode_atts( array(
1022 'link' => null,
1023 'class' => null,
1024 ), $attributes, 'checkmail-encode' );
1025
1026
1027 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1028
1029 if ( ! empty( $atts[ 'link' ] ) ) {
1030 $link = esc_url( $atts[ 'link' ], null, 'shortcode' );
1031
1032 if ( $link === '' ) {
1033 return $method( $content );
1034 }
1035
1036 if ( empty( $atts[ 'class' ] ) ) {
1037 return sprintf(
1038 '<a href="%s">%s</a>',
1039 $method( $link ),
1040 $method( $content )
1041 );
1042 }
1043
1044 return sprintf(
1045 '<a href="%s" class="%s">%s</a>',
1046 $method( $link ),
1047 esc_attr( $atts[ 'class' ] ),
1048 $method( $content )
1049 );
1050 }
1051
1052 return $method( $content );
1053 }
1054
1055 function check_email_e_encode_emails( $string ) {
1056 if ( ! is_string( $string ) ) {
1057 return $string;
1058 }
1059 // abort if `check_email_e_at_sign_check` is true and `$string` doesn't contain a @-sign
1060 if ( apply_filters( 'check_email_e_at_sign_check', true ) && strpos( $string, '@' ) === false ) {
1061 return $string;
1062 }
1063 // override encoding function with the 'check_email_e_method' filter
1064 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1065
1066 $regexp = apply_filters( 'check_email_e_regexp', CHECK_EMAIL_E_REGEXP );
1067
1068 $callback = function ( $matches ) use ( $method ) {
1069 return $method( $matches[ 0 ] );
1070 };
1071
1072 if ( has_filter( 'check_email_e_callback' ) ) {
1073 $callback = apply_filters( 'check_email_e_callback', $callback, $method );
1074 return preg_replace_callback( $regexp, $callback, $string );
1075 }
1076
1077 return preg_replace_callback( $regexp, $callback, $string );
1078 }
1079
1080 function check_email_full_page_scanner() {
1081 if(!is_admin() ) {
1082 ob_start('check_email_full_page_callback');
1083 }
1084 }
1085 function check_email_full_page_callback($string) {
1086 return check_email_e_encode_emails($string);
1087 }
1088
1089
1090 add_action( 'wp_enqueue_scripts', 'ck_mail_enqueue_encoder_js' );
1091
1092 function ck_mail_enqueue_encoder_js() {
1093 $encode_options = get_option('check-email-email-encode-options', true);
1094 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
1095 if ( $is_enable ) {
1096 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
1097 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
1098
1099 $check_email = wpchill_check_email();
1100 $plugin_dir_url = plugin_dir_url( $check_email->get_plugin_file() );
1101 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1102 wp_register_script( 'checkemail_encoder', $plugin_dir_url . 'assets/js/check-email-front'. $suffix .'.js', array(), $check_email->get_version(), true );
1103 $data = array();
1104 $data['email_using'] = $email_using;
1105 $data['is_enable'] = $is_enable;
1106 $data['email_technique'] = $email_technique;
1107
1108 wp_localize_script( 'checkemail_encoder', 'checkemail_encoder_data', $data );
1109 wp_enqueue_script( 'checkemail_encoder' );
1110 }
1111 }
1112
1113 function check_email_rot13( $string ) {
1114
1115 $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1116 $to = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
1117
1118 return strtr( $string, $from, $to );
1119 }
1120
1121 // email and phone encoding end
1122
1123 function check_email_track_email_open() {
1124 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1125 if (isset($_GET['action']) && $_GET['action'] === 'check_email_track_email_open' && isset($_GET['open_tracking_id']) && isset($_GET['_wpnonce'])) {
1126 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1127 if (!check_email_verify_extended_nonce(sanitize_text_field( wp_unslash($_GET['_wpnonce'])))) {
1128 return false;
1129 }
1130 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1131 $open_tracking_id = absint($_GET['open_tracking_id']);
1132
1133 if ($open_tracking_id) {
1134 global $wpdb;
1135 $table_name = $wpdb->prefix . 'check_email_log';
1136 $query = $wpdb->prepare(
1137 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1138 "SELECT * FROM {$table_name} WHERE open_tracking_id = %s",
1139 $open_tracking_id
1140 );
1141 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
1142 $record = $wpdb->get_row($query);
1143
1144 if ($record) {
1145 $data_to_update = [
1146 'open_count' => $record->open_count + 1
1147 ];
1148 $where = [
1149 'open_tracking_id' => $open_tracking_id,
1150 ];
1151 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
1152 $wpdb->update( $table_name, $data_to_update, $where );
1153 header("Content-Type: image/png");
1154 echo esc_html(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wcAAgMBAptL0ygAAAAASUVORK5CYII='));
1155 exit;
1156 }
1157 }
1158 }
1159
1160 }
1161 add_action('init', 'check_email_track_email_open');
1162
1163 function check_email_generate_extended_nonce($action = -1, $lifetime = WEEK_IN_SECONDS) {
1164 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1165 return wp_create_nonce($action . $i);
1166 }
1167
1168 function check_email_verify_extended_nonce($nonce, $action = -1, $lifetime = WEEK_IN_SECONDS) {
1169 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1170
1171 if (wp_verify_nonce($nonce, $action . $i)) {
1172 return true;
1173 }
1174 if (wp_verify_nonce($nonce, $action . ($i - 1))) {
1175 return true;
1176 }
1177 return false;
1178 }
1179
1180 function check_email_content_with_tracking($open_tracking_id) {
1181 $nonce = check_email_generate_extended_nonce();
1182 $tracking_url = add_query_arg(
1183 array(
1184 '_wpnonce'=>$nonce,
1185 'open_tracking_id' => $open_tracking_id,
1186 'action' => 'check_email_track_email_open',
1187 ),
1188 site_url('/check-email-tracking/')
1189 );
1190 $tracking_url = esc_url_raw($tracking_url);
1191 // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
1192 $email_content = "<img src='$tracking_url' class='check-email-tracking' alt='' width='1' height='1' style='display:none;' />";
1193 return $email_content;
1194 }
1195
1196 if ( is_admin() ) {
1197
1198 function checmail_dashboard_widget() {
1199 echo '<canvas id="checkmail-dashboard-chart" style="width: 100%; height: 250px;"></canvas>';
1200 echo '
1201 <div style="margin-top: 10px; text-align: center; display: flex; justify-content: space-between; align-items: center;">
1202 <div>
1203 <select id="checkmail-dashboard-date-range">
1204 <option value="7">'.esc_html__('Last 7 Days', 'check-email').'</option>
1205 <option value="14">'.esc_html__('Last 14 Days', 'check-email').'</option>
1206 <option value="30">'.esc_html__('Last 30 Days', 'check-email').'</option>
1207 </select>
1208 </div>
1209 <div style="margin-top: 10px; text-align: center; font-size: 14px;">
1210 <p><span style="color: blue; font-weight: bold;" id="js_checkmail_total"></span> |
1211 <span style="color: green; font-weight: bold;" id="js_checkmail_sent"></span> |
1212 <span style="color: red; font-weight: bold;" id="js_checkmail_failed"></span></p>
1213 </div>
1214 </div>
1215 ';
1216 }
1217
1218 function add_checmail_dashboard_widget() {
1219 $option = get_option( 'check-email-log-core' );
1220
1221 if(!isset( $option['enable_dashboard_widget']) || (isset( $option['enable_dashboard_widget']) && $option['enable_dashboard_widget'] ) ){
1222 wp_add_dashboard_widget(
1223 'checmail_dashboard_widget',
1224 esc_html__('Check & Log Email Activity', 'check-email'),
1225 'checmail_dashboard_widget'
1226 );
1227 }
1228 }
1229 add_action('wp_dashboard_setup', 'add_checmail_dashboard_widget');
1230
1231 function custom_dashboard_scripts($hook) {
1232 if ($hook !== 'index.php') return;
1233 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1234 wp_enqueue_script('chartjs', CK_MAIL_URL . 'assets/js/admin/chart.js', [], CK_MAIL_VERSION, true);
1235 wp_register_script('custom-dashboard-chart', CK_MAIL_URL . 'assets/js/admin/checkmail-dashboard-chart'. $suffix .'.js', ['jquery','chartjs'], CK_MAIL_VERSION, true);
1236 $data = array(
1237 'ajax_url' => admin_url( 'admin-ajax.php' ),
1238 'ck_mail_security_nonce' => wp_create_nonce('ck_mail_ajax_check_nonce'),
1239 );
1240
1241 wp_localize_script( 'custom-dashboard-chart', 'checkmail_chart', $data );
1242 wp_enqueue_script( 'custom-dashboard-chart' );
1243
1244
1245
1246 }
1247 add_action('admin_enqueue_scripts', 'custom_dashboard_scripts');
1248
1249 function get_email_analytics_data() {
1250 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' ) ) {
1251 echo esc_html__('security_nonce_not_verified', 'check-email');
1252 die();
1253 }
1254 if ( !current_user_can( 'manage_options' ) ) {
1255 die();
1256 }
1257 global $wpdb;
1258
1259 $table_name = $wpdb->prefix . 'check_email_log';
1260 $ck_days = isset($_GET['ck_days']) ? sanitize_text_field( wp_unslash( $_GET['ck_days'] ) ) : 7;
1261 $query = $wpdb->prepare(
1262 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1263 "SELECT * FROM $table_name WHERE sent_date >= CURDATE() - INTERVAL %d DAY",
1264 $ck_days
1265 );
1266 // phpcs:ignore InterpolatedNotPrepared
1267 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
1268 $results = $wpdb->get_results($query);
1269
1270 $data = [
1271 'labels' => [],
1272 'sent' => [],
1273 'failed' => [],
1274 ];
1275
1276
1277 $daily_counts = [];
1278 foreach ($results as $row) {
1279 $created_at = $row->sent_date;
1280 $status = $row->result;
1281 $date = gmdate('M j', strtotime($created_at));
1282 if (!isset($daily_counts[$date])) {
1283 $daily_counts[$date] = ['sent' => 0, 'failed' => 0];
1284 }
1285 if ($status == 1) {
1286 $daily_counts[$date]['sent']++;
1287 } else {
1288 $daily_counts[$date]['failed']++;
1289 }
1290 }
1291 ksort($daily_counts);
1292 foreach ($daily_counts as $date => $counts) {
1293 $data['labels'][] = $date;
1294 $data['sent'][] = $counts['sent'];
1295 $data['failed'][] = $counts['failed'];
1296 }
1297
1298 $data['total_mail'] = array_sum($data['sent']) + array_sum($data['failed']);
1299 $data['total_failed'] = array_sum($data['failed']);
1300 $data['total_sent'] = array_sum($data['sent']);
1301
1302 wp_send_json($data);
1303 }
1304 add_action('wp_ajax_get_email_analytics', 'get_email_analytics_data');
1305
1306 }
1307