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