PluginProbe ʕ •ᴥ•ʔ
Check & Log Email – Easy Email Testing & Mail logging / 2.0.13.1
Check & Log Email – Easy Email Testing & Mail logging v2.0.13.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 2 months ago Util 2 months ago Check_Email_Encode_Tab.php 2 months ago Check_Email_Notify_Tab.php 2 months ago Check_Email_SMTP_Tab.php 2 months ago class-check-email-header-parser.php 2 months ago class-check-email-log-autoloader.php 2 months ago class-check-email-newsletter.php 2 months ago deactivate-feedback.php 2 months ago helper-function.php 2 months ago install.php 2 months ago
helper-function.php
1318 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://spamanalyser.check-email.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 \@ # At sign (@)
910 (?:
911 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ # Domain name
912 |
913 \[[\d.a-fA-F:]+\] # IPv4/IPv6 address
914 )
915 }xi'
916 );
917 }
918
919 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
920 $encode_options = get_option('check-email-email-encode-options', true);
921 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
922 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
923 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
924 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
925 if ( $is_enable && $email_using == 'filters' ) {
926 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
927 foreach ( array( 'the_content', 'the_excerpt', 'widget_text', 'comment_text', 'comment_excerpt' ) as $filter ) {
928 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
929 add_filter( $filter, 'check_email_e_encode_emails', CHECK_EMAIL_E_FILTER_PRIORITY );
930 }
931 }
932 if ( $is_enable && $email_using == 'full_page' ) {
933 add_action( 'wp', 'check_email_full_page_scanner',999 );
934 }
935
936 add_action( 'init', 'check_email_e_register_shortcode', 2000 );
937 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
938 function check_email_e_register_shortcode() {
939 if ( ! shortcode_exists( 'checkmail-encode' ) ) {
940 add_shortcode( 'checkmail-encode', 'check_email_e_shortcode' );
941 }
942 }
943 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
944 function check_email_rot47($str) {
945 $rotated = '';
946 foreach (str_split($str) as $char) {
947 $ascii = ord($char);
948 if ($ascii >= 33 && $ascii <= 126) {
949 $rotated .= chr(33 + (($ascii + 14) % 94));
950 } else {
951 $rotated .= $char;
952 }
953 }
954 return $rotated;
955 }
956 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
957 function check_email_encode_str( $string, $hex = false ) {
958 $encode_options = get_option('check-email-email-encode-options', true);
959 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
960 if (strpos($string, 'mailto:') !== false) {
961 $string = str_replace('mailto:', '', $string);
962 switch ($email_technique) {
963 case 'css_direction':
964 $reversed_email = strrev($string);
965 // Wrap it with the span and necessary CSS
966 return 'mailto:'.esc_html($reversed_email);
967 break;
968 case 'rot_13':
969 $encoded_email = check_email_rot13($string);
970 return 'mailto:'.esc_html($encoded_email);
971 break;
972 case 'rot_47':
973 $encoded_email = check_email_rot47($string);
974 return 'mailto:'.esc_html($encoded_email);
975 break;
976
977 default:
978 # code...
979 break;
980 }
981 }else{
982 switch ($email_technique) {
983 case 'css_direction':
984 $reversed_email = strrev($string);
985 // Wrap it with the span and necessary CSS
986 return ' <span style="direction: rtl; unicode-bidi: bidi-override;">' . esc_html($reversed_email) . '</span>';
987 break;
988 case 'rot_13':
989 $encoded_email = check_email_rot13($string);
990 return ' <span class="check-email-encoded-email" >' . esc_html($encoded_email).' </span>';
991 break;
992 case 'rot_47':
993 $encoded_email = check_email_rot47($string);
994 return ' <span class="check-email-rot47-email" >' . esc_html($encoded_email).' </span>';
995 break;
996
997 default:
998 # code...
999 break;
1000 }
1001 }
1002
1003
1004 $chars = str_split( $string );
1005 $string_length = (int) abs(crc32($string) / strlen($string));
1006 $length = max($string_length, 1);
1007 $seed = random_int($length, PHP_INT_MAX);
1008
1009 foreach ( $chars as $key => $char ) {
1010 $ord = ord( $char );
1011
1012 if ( $ord < 128 ) { // ignore non-ascii chars
1013 $r = ( $seed * ( 1 + $key ) ) % 100; // pseudo "random function"
1014
1015 if ( $r > 75 && $char !== '@' && $char !== '.' ); // plain character (not encoded), except @-signs and dots
1016 else if ( $hex && $r < 25 ) $chars[ $key ] = '%' . bin2hex( $char ); // hex
1017 else if ( $r < 45 ) $chars[ $key ] = '&#x' . dechex( $ord ) . ';'; // hexadecimal
1018 else $chars[ $key ] = "&#{$ord};"; // decimal (ascii)
1019 }
1020 }
1021
1022 return implode( '', $chars );
1023 }
1024 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1025 function check_email_e_shortcode( $attributes, $content = '' ) {
1026 $atts = shortcode_atts( array(
1027 'link' => null,
1028 'class' => null,
1029 ), $attributes, 'checkmail-encode' );
1030
1031 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
1032 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1033
1034 if ( ! empty( $atts[ 'link' ] ) ) {
1035 $link = esc_url( $atts[ 'link' ], null, 'shortcode' );
1036
1037 if ( $link === '' ) {
1038 return $method( $content );
1039 }
1040
1041 if ( empty( $atts[ 'class' ] ) ) {
1042 return sprintf(
1043 '<a href="%s">%s</a>',
1044 $method( $link ),
1045 $method( $content )
1046 );
1047 }
1048
1049 return sprintf(
1050 '<a href="%s" class="%s">%s</a>',
1051 $method( $link ),
1052 esc_attr( $atts[ 'class' ] ),
1053 $method( $content )
1054 );
1055 }
1056
1057 return $method( $content );
1058 }
1059 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1060 function check_email_e_encode_emails( $string ) {
1061 if ( ! is_string( $string ) ) {
1062 return $string;
1063 }
1064 // abort if `check_email_e_at_sign_check` is true and `$string` doesn't contain a @-sign
1065 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
1066 if ( apply_filters( 'check_email_e_at_sign_check', true ) && strpos( $string, '@' ) === false ) {
1067 return $string;
1068 }
1069 // override encoding function with the 'check_email_e_method' filter
1070 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
1071 $method = apply_filters( 'check_email_e_method', 'check_email_encode_str' );
1072 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
1073 $regexp = apply_filters( 'check_email_e_regexp', CHECK_EMAIL_E_REGEXP );
1074
1075 $callback = function ( $matches ) use ( $method ) {
1076 return $method( $matches[ 0 ] );
1077 };
1078
1079 if ( has_filter( 'check_email_e_callback' ) ) {
1080 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
1081 $callback = apply_filters( 'check_email_e_callback', $callback, $method );
1082 return preg_replace_callback( $regexp, $callback, $string );
1083 }
1084
1085 return preg_replace_callback( $regexp, $callback, $string );
1086 }
1087 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1088 function check_email_full_page_scanner() {
1089 if(!is_admin() ) {
1090 ob_start('check_email_full_page_callback');
1091 }
1092 }
1093 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1094 function check_email_full_page_callback($string) {
1095 return check_email_e_encode_emails($string);
1096 }
1097
1098
1099 add_action( 'wp_enqueue_scripts', 'ck_mail_enqueue_encoder_js' );
1100 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1101 function ck_mail_enqueue_encoder_js() {
1102 $encode_options = get_option('check-email-email-encode-options', true);
1103 $is_enable = ( isset( $encode_options['is_enable'] ) ) ? $encode_options['is_enable'] : 0;
1104 if ( $is_enable ) {
1105 $email_using = ( isset( $encode_options['email_using'] ) ) ? $encode_options['email_using'] : "";
1106 $email_technique = ( isset( $encode_options['email_technique'] ) ) ? $encode_options['email_technique'] : "";
1107
1108 $check_email = wpchill_check_email();
1109 $plugin_dir_url = plugin_dir_url( $check_email->get_plugin_file() );
1110 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1111 wp_register_script( 'checkemail_encoder', $plugin_dir_url . 'assets/js/check-email-front'. $suffix .'.js', array(), $check_email->get_version(), true );
1112 $data = array();
1113 $data['email_using'] = $email_using;
1114 $data['is_enable'] = $is_enable;
1115 $data['email_technique'] = $email_technique;
1116
1117 wp_localize_script( 'checkemail_encoder', 'checkemail_encoder_data', $data );
1118 wp_enqueue_script( 'checkemail_encoder' );
1119 }
1120 }
1121 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1122 function check_email_rot13( $string ) {
1123
1124 $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1125 $to = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
1126
1127 return strtr( $string, $from, $to );
1128 }
1129
1130 // email and phone encoding end
1131 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1132 function check_email_track_email_open() {
1133 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1134 if (isset($_GET['action']) && $_GET['action'] === 'check_email_track_email_open' && isset($_GET['open_tracking_id']) && isset($_GET['_wpnonce'])) {
1135 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1136 if (!check_email_verify_extended_nonce(sanitize_text_field( wp_unslash($_GET['_wpnonce'])))) {
1137 return false;
1138 }
1139 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1140 $open_tracking_id = absint($_GET['open_tracking_id']);
1141
1142 if ($open_tracking_id) {
1143 global $wpdb;
1144 $table_name = $wpdb->prefix . 'check_email_log';
1145 $query = $wpdb->prepare(
1146 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1147 "SELECT * FROM {$table_name} WHERE open_tracking_id = %s",
1148 $open_tracking_id
1149 );
1150 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter
1151 $record = $wpdb->get_row($query);
1152
1153 if ($record) {
1154 $data_to_update = [
1155 'open_count' => $record->open_count + 1
1156 ];
1157 $where = [
1158 'open_tracking_id' => $open_tracking_id,
1159 ];
1160 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
1161 $wpdb->update( $table_name, $data_to_update, $where );
1162 header("Content-Type: image/png");
1163 echo esc_html(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wcAAgMBAptL0ygAAAAASUVORK5CYII='));
1164 exit;
1165 }
1166 }
1167 }
1168
1169 }
1170 add_action('init', 'check_email_track_email_open');
1171 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1172 function check_email_generate_extended_nonce($action = -1, $lifetime = WEEK_IN_SECONDS) {
1173 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1174 return wp_create_nonce($action . $i);
1175 }
1176 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1177 function check_email_verify_extended_nonce($nonce, $action = -1, $lifetime = WEEK_IN_SECONDS) {
1178 $i = wp_nonce_tick() - (floor(time() / $lifetime) - floor(time() / (DAY_IN_SECONDS * 2)));
1179
1180 if (wp_verify_nonce($nonce, $action . $i)) {
1181 return true;
1182 }
1183 if (wp_verify_nonce($nonce, $action . ($i - 1))) {
1184 return true;
1185 }
1186 return false;
1187 }
1188 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1189 function check_email_content_with_tracking($open_tracking_id) {
1190 $nonce = check_email_generate_extended_nonce();
1191 $tracking_url = add_query_arg(
1192 array(
1193 '_wpnonce'=>$nonce,
1194 'open_tracking_id' => $open_tracking_id,
1195 'action' => 'check_email_track_email_open',
1196 ),
1197 site_url('/check-email-tracking/')
1198 );
1199 $tracking_url = esc_url_raw($tracking_url);
1200 // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
1201 $email_content = "<img src='$tracking_url' class='check-email-tracking' alt='' width='1' height='1' style='display:none;' />";
1202 return $email_content;
1203 }
1204
1205 if ( is_admin() ) {
1206 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1207 function checmail_dashboard_widget() {
1208 echo '<canvas id="checkmail-dashboard-chart" style="width: 100%; height: 250px;"></canvas>';
1209 echo '
1210 <div style="margin-top: 10px; text-align: center; display: flex; justify-content: space-between; align-items: center;">
1211 <div>
1212 <select id="checkmail-dashboard-date-range">
1213 <option value="7">'.esc_html__('Last 7 Days', 'check-email').'</option>
1214 <option value="14">'.esc_html__('Last 14 Days', 'check-email').'</option>
1215 <option value="30">'.esc_html__('Last 30 Days', 'check-email').'</option>
1216 </select>
1217 </div>
1218 <div style="margin-top: 10px; text-align: center; font-size: 14px;">
1219 <p><span style="color: blue; font-weight: bold;" id="js_checkmail_total"></span> |
1220 <span style="color: green; font-weight: bold;" id="js_checkmail_sent"></span> |
1221 <span style="color: red; font-weight: bold;" id="js_checkmail_failed"></span></p>
1222 </div>
1223 </div>
1224 ';
1225 }
1226 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1227 function check_email_add_checmail_dashboard_widget() {
1228 $option = get_option( 'check-email-log-core' );
1229
1230 if(!isset( $option['enable_dashboard_widget']) || (isset( $option['enable_dashboard_widget']) && $option['enable_dashboard_widget'] ) ){
1231 wp_add_dashboard_widget(
1232 'checmail_dashboard_widget',
1233 esc_html__('Check & Log Email Activity', 'check-email'),
1234 'checmail_dashboard_widget'
1235 );
1236 }
1237 }
1238 add_action('wp_dashboard_setup', 'check_email_add_checmail_dashboard_widget');
1239 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1240 function check_email_custom_dashboard_scripts($hook) {
1241 if ($hook !== 'index.php') return;
1242 $option = get_option( 'check-email-log-core' );
1243 if(!isset( $option['enable_dashboard_widget']) || (isset( $option['enable_dashboard_widget']) && $option['enable_dashboard_widget'] ) ){
1244 $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
1245 wp_enqueue_script('chartjs', CK_MAIL_URL . 'assets/js/admin/chart.js', [], CK_MAIL_VERSION, true);
1246 wp_register_script('checkmail-dashboard-chart', CK_MAIL_URL . 'assets/js/admin/checkmail-dashboard-chart'. $suffix .'.js', ['jquery','chartjs'], CK_MAIL_VERSION, true);
1247 $data = array(
1248 'ajax_url' => admin_url( 'admin-ajax.php' ),
1249 'ck_mail_security_nonce' => wp_create_nonce('ck_mail_ajax_check_nonce'),
1250 );
1251
1252 wp_localize_script( 'checkmail-dashboard-chart', 'checkmail_chart', $data );
1253 wp_enqueue_script( 'checkmail-dashboard-chart' );
1254 }
1255
1256
1257
1258 }
1259 add_action('admin_enqueue_scripts', 'check_email_custom_dashboard_scripts');
1260 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
1261 function check_email_get_email_analytics_data() {
1262 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' ) ) {
1263 echo esc_html__('security_nonce_not_verified', 'check-email');
1264 die();
1265 }
1266 if ( !current_user_can( 'manage_options' ) ) {
1267 die();
1268 }
1269 global $wpdb;
1270
1271 $table_name = $wpdb->prefix . 'check_email_log';
1272 $ck_days = isset($_GET['ck_days']) ? sanitize_text_field( wp_unslash( $_GET['ck_days'] ) ) : 7;
1273 $query = $wpdb->prepare(
1274 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1275 "SELECT * FROM $table_name WHERE sent_date >= CURDATE() - INTERVAL %d DAY",
1276 $ck_days
1277 );
1278 // phpcs:ignore InterpolatedNotPrepared
1279 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
1280 $results = $wpdb->get_results($query);
1281
1282 $data = [
1283 'labels' => [],
1284 'sent' => [],
1285 'failed' => [],
1286 ];
1287
1288
1289 $daily_counts = [];
1290 foreach ($results as $row) {
1291 $created_at = $row->sent_date;
1292 $status = $row->result;
1293 $date = gmdate('M j', strtotime($created_at));
1294 if (!isset($daily_counts[$date])) {
1295 $daily_counts[$date] = ['sent' => 0, 'failed' => 0];
1296 }
1297 if ($status == 1) {
1298 $daily_counts[$date]['sent']++;
1299 } else {
1300 $daily_counts[$date]['failed']++;
1301 }
1302 }
1303 ksort($daily_counts);
1304 foreach ($daily_counts as $date => $counts) {
1305 $data['labels'][] = $date;
1306 $data['sent'][] = $counts['sent'];
1307 $data['failed'][] = $counts['failed'];
1308 }
1309
1310 $data['total_mail'] = array_sum($data['sent']) + array_sum($data['failed']);
1311 $data['total_failed'] = array_sum($data['failed']);
1312 $data['total_sent'] = array_sum($data['sent']);
1313
1314 wp_send_json($data);
1315 }
1316 add_action('wp_ajax_get_email_analytics', 'check_email_get_email_analytics_data');
1317
1318 }