table_name = $wpdb->prefix . 'adminease_email_log'; $this->settings = Plugin::get_settings( 'debug' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] ); add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] ); if( !empty( $this->settings['enable_email_log'] ) ) { if( !empty( $this->settings['email_log_disable_sending'] ) ) { add_filter( 'pre_wp_mail', [ $this, 'block_and_log_email' ], 10, 2 ); } else { add_action( 'phpmailer_init', [ $this, 'capture_email_before_send' ], 10, 1 ); add_action( 'wp_mail_succeeded', [ $this, 'log_successful_email' ], 10, 1 ); add_action( 'wp_mail_failed', [ $this, 'log_failed_email' ], 10, 1 ); } add_action( 'adminease_cleanup_email_logs', [ $this, 'cleanup_old_logs' ] ); add_action( 'wp_ajax_adminease_get_email_log', [ $this, 'ajax_get_email_log' ] ); add_action( 'wp_ajax_adminease_clear_email_log', [ $this, 'ajax_clear_email_log' ] ); add_action( 'wp_ajax_adminease_resend_email', [ $this, 'ajax_resend_email' ] ); add_action( 'wp_ajax_adminease_export_email_log', [ $this, 'ajax_export_email_log' ] ); add_action( 'wp_ajax_adminease_bulk_delete_emails', [ $this, 'ajax_bulk_delete_emails' ] ); add_action( 'wp_ajax_adminease_bulk_resend_emails', [ $this, 'ajax_bulk_resend_emails' ] ); add_action( 'admin_bar_menu', [ $this, 'add_admin_bar_indicator' ], 999 ); add_action( 'wp_head', [ $this, 'add_admin_bar_styles' ] ); add_action( 'admin_head', [ $this, 'add_admin_bar_styles' ] ); if( !wp_next_scheduled( 'adminease_cleanup_email_logs' ) ) { wp_schedule_event( time(), 'hourly', 'adminease_cleanup_email_logs' ); } } } /** * Updates the settings fields array with additional configuration options for the AdminEase plugin. * * @param array $fields Associative array of existing settings fields. * * @return array Modified settings fields array. */ public function adminease_settings_fields( array $fields ): array { $max_entries = apply_filters( 'adminease_default_email_log_max_entries', $this->settings['email_log_max_entries'] ?? '1000' ); $fields['debug']['fields'][] = [ 'type' => 'switch', 'id' => 'enable-email-log', 'name' => 'adminease[debug][enable_email_log]', 'value' => $this->settings['enable_email_log'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Email Log', 'adminease' ), 'description' => __( "Complete email logging system. Track every email sent from your WordPress site including recipient, subject, content, and delivery status. Debug email delivery issues, monitor notifications, and ensure critical emails reach their destination. Perfect for troubleshooting SMTP configurations and auditing site communications.", 'adminease' ), 'child_fields' => [ [ 'type' => 'switch', 'id' => 'email-log-store-full-body', 'name' => 'adminease[debug][email_log_store_full_body]', 'value' => $this->settings['email_log_store_full_body'] ?? true, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Store Full Email Body', 'adminease' ), 'description' => __( 'Store complete email content (may increase database size).', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'switch', 'id' => 'email-log-failed-only', 'name' => 'adminease[debug][email_log_failed_only]', 'value' => $this->settings['email_log_failed_only'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log Failed Emails Only', 'adminease' ), 'description' => __( 'Only log emails that fail to send (useful for debugging).', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'switch', 'id' => 'email-log-auto-load', 'name' => 'adminease[debug][email_log_auto_load]', 'value' => $this->settings['email_log_auto_load'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Load Email Log', 'adminease' ), 'field_description' => __( 'Automatically load the email log when the AdminEase admin page is opened.', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'switch', 'id' => 'email-log-auto-refresh', 'name' => '', 'value' => 0, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Refresh Email Log', 'adminease' ), 'description' => __( 'Automatically reload the email log at a chosen interval. State resets on page reload.', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'select', 'id' => 'email-log-auto-refresh-interval', 'name' => 'adminease[debug][email_log_auto_refresh_interval]', 'value' => $this->settings['email_log_auto_refresh_interval'] ?? '15', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Email Log Auto-Refresh Interval', 'adminease' ), 'description' => __( 'How often to reload the email log when auto-refresh is on.', 'adminease' ), 'options' => [ /* translators: %d: number of seconds for the auto-refresh interval */ '5' => sprintf( __( 'Every %d seconds', 'adminease' ), 5 ), /* translators: %d: number of seconds for the auto-refresh interval */ '10' => sprintf( __( 'Every %d seconds', 'adminease' ), 10 ), /* translators: %d: number of seconds for the auto-refresh interval */ '15' => sprintf( __( 'Every %d seconds', 'adminease' ), 15 ), /* translators: %d: number of seconds for the auto-refresh interval */ '30' => sprintf( __( 'Every %d seconds', 'adminease' ), 30 ), /* translators: %d: number of seconds for the auto-refresh interval */ '60' => sprintf( __( 'Every %d seconds', 'adminease' ), 60 ), ], 'attributes' => [ 'data-parent' => 'email-log-auto-refresh', ], ], [ 'type' => 'switch', 'id' => 'email-log-ajax', 'name' => 'adminease[debug][email_log_ajax]', 'value' => $this->settings['email_log_ajax'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log AJAX-Triggered Emails', 'adminease' ), 'description' => __( 'Enable logging of emails triggered by AJAX requests.', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'switch', 'id' => 'email-log-disable-sending', 'name' => 'adminease[debug][email_log_disable_sending]', 'value' => $this->settings['email_log_disable_sending'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Disable Email Sending (Log Only Mode)', 'adminease' ), 'description' => __( 'When enabled, all outgoing emails will be blocked but still logged. Useful for debugging and testing. ⚠️ No emails will be delivered while this is active.', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'number', 'id' => 'email-log-max-entries', 'name' => 'adminease[debug][email_log_max_entries]', 'value' => $max_entries, 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Maximum Log Entries', 'adminease' ), 'description' => __( 'Maximum number of entries to keep in the log (100-100000).', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', 'min' => '100', 'max' => $max_entries, ], ], [ 'type' => 'select', 'id' => 'email-log-auto-clear', 'name' => 'adminease[debug][email_log_auto_clear]', 'value' => $this->settings['email_log_auto_clear'] ?? '7_days', 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto Clear Logs After', 'adminease' ), 'description' => __( 'Automatically delete logs older than this period.', 'adminease' ), 'options' => [ '1_hour' => __( '1 Hour', 'adminease' ), '24_hours' => __( '24 Hours', 'adminease' ), '7_days' => __( '7 Days', 'adminease' ), '30_days' => __( '30 Days', 'adminease' ), 'never' => __( 'Never', 'adminease' ), ], 'attributes' => [ 'data-parent' => 'enable-email-log', ], ], [ 'type' => 'textarea', 'id' => 'email-log-exclude-addresses', 'name' => 'adminease[debug][email_log_exclude_addresses]', 'value' => str_replace( ' ', PHP_EOL, ( $this->settings['email_log_exclude_addresses'] ?? '' ) ), 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Exclude Email Addresses', 'adminease' ), 'description' => __( 'Enter email addresses to exclude from logging (one per line).', 'adminease' ), 'attributes' => [ 'data-parent' => 'enable-email-log', 'rows' => '4', ], ], ], ]; return $fields; } /** * Enqueues the necessary scripts and styles for the admin page. * * @param string $hook The current admin page hook suffix. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'EmailLog', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseEmailLog.css', [ ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseEmailLog.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'EmailLog', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseEmailLog.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseEmailLog.js' ), true ); $security = [ 'refreshEmailLog' => wp_create_nonce( 'adminease_refresh_email_log' ), 'clearEmailLog' => wp_create_nonce( 'adminease_clear_email_log' ), 'resendEmail' => wp_create_nonce( 'adminease_resend_email' ), 'exportEmailLog' => wp_create_nonce( 'adminease_export_email_log' ), 'bulkDelete' => wp_create_nonce( 'adminease_bulk_delete_emails' ), 'bulkResend' => wp_create_nonce( 'adminease_bulk_resend_emails' ), ]; $i18n = [ 'confirmClearEmailLog' => esc_html__( 'Are you sure you want to clear all email logs?', 'adminease' ), 'confirmResendEmail' => esc_html__( 'Are you sure you want to resend this email?', 'adminease' ), 'confirmBulkDelete' => esc_html__( 'Are you sure you want to delete the selected emails?', 'adminease' ), 'confirmBulkResend' => esc_html__( 'Are you sure you want to resend the selected failed emails?', 'adminease' ), 'selectEmailsFirst' => esc_html__( 'Please select at least one email.', 'adminease' ), 'emailLogEmpty' => esc_html__( 'No emails logged yet. Enable the feature and emails will appear here.', 'adminease' ), 'emailLogCleared' => esc_html__( 'Email log cleared successfully.', 'adminease' ), 'emailResent' => esc_html__( 'Email resent successfully.', 'adminease' ), 'emailsDeleted' => esc_html__( 'Selected emails deleted successfully.', 'adminease' ), 'emailsResent' => esc_html__( 'Selected emails resent successfully.', 'adminease' ), 'emailLogLoadFailed' => esc_html__( 'Failed to load email log.', 'adminease' ), 'emailLogRefreshError' => esc_html__( 'Failed to refresh email log.', 'adminease' ), 'clearEmailLogFailed' => esc_html__( 'Failed to clear email log.', 'adminease' ), 'resendEmailFailed' => esc_html__( 'Failed to resend email.', 'adminease' ), 'bulkDeleteFailed' => esc_html__( 'Failed to delete selected emails.', 'adminease' ), 'bulkResendFailed' => esc_html__( 'Failed to resend selected emails.', 'adminease' ), /* translators: 1: current page, 2: total pages */ 'paginationInfo' => esc_html__( 'Page %1$s of %2$s', 'adminease' ), /* translators: 1: start number, 2: end number, 3: total count */ 'emailCount' => esc_html__( 'Showing %1$s-%2$s of %3$s emails', 'adminease' ), 'emailLogRefreshedEmpty' => esc_html__( 'Email log refreshed. No emails found.', 'adminease' ), 'networkError' => esc_html__( 'Network error', 'adminease' ), 'btnProcessing' => esc_html__( 'Processing…', 'adminease' ), 'btnComplete' => esc_html__( 'Complete!', 'adminease' ), 'byteUnits' => [ esc_html__( 'B', 'adminease' ), esc_html__( 'KB', 'adminease' ), esc_html__( 'MB', 'adminease' ), esc_html__( 'GB', 'adminease' ), ], 'emailDetailLabels' => [ 'emailInfo' => esc_html__( 'Email Information', 'adminease' ), 'timestamp' => esc_html__( 'Timestamp', 'adminease' ), 'to' => esc_html__( 'To', 'adminease' ), 'from' => esc_html__( 'From', 'adminease' ), 'subject' => esc_html__( 'Subject', 'adminease' ), 'status' => esc_html__( 'Status', 'adminease' ), 'type' => esc_html__( 'Type', 'adminease' ), 'messageBody' => esc_html__( 'Message Body', 'adminease' ), 'htmlPreview' => esc_html__( 'HTML Preview', 'adminease' ), 'plainText' => esc_html__( 'Plain Text', 'adminease' ), 'headers' => esc_html__( 'Headers', 'adminease' ), 'attachments' => esc_html__( 'Attachments', 'adminease' ), 'errorMessage' => esc_html__( 'Error Message', 'adminease' ), 'contextInfo' => esc_html__( 'Context Information', 'adminease' ), 'userId' => esc_html__( 'User ID', 'adminease' ), 'context' => esc_html__( 'Triggered By', 'adminease' ), ], ]; wp_localize_script( ADMINEASE_NAME . 'EmailLog', ADMINEASE_NAME . 'EmailLogAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => $security, 'i18n' => $i18n, 'autoLoad' => !empty( $this->settings['email_log_auto_load'] ), 'pluginUrl' => esc_url_raw( ADMINEASE_PLUGIN_URL ), ] ); } /** * Handles the saving of AdminEase settings and updates internal properties accordingly. * * @param array $sanitized_settings Associative array containing sanitized settings. * * @return void */ public function adminease_settings_saved( array $sanitized_settings ): void { $this->settings = $sanitized_settings['debug'] ?? []; if( !empty( $sanitized_settings['debug']['enable_email_log'] ) ) { $this->create_table(); } } /** * Handles the after render logic for the specified field. * * @param array $field The field information. * * @return void */ public function adminease_after_field_render( array $field ) { if( 'enable-email-log' !== $field['id'] ) { return; } $settings = $this->settings; include_once ADMINEASE_DIR . 'partials/email-log.php'; } /** * Capture email data before it's sent. * * @param PHPMailer $phpmailer PHPMailer instance. * * @return void */ public function capture_email_before_send( $phpmailer ): void { if( !$this->should_log_email( $phpmailer ) ) { return; } $this->current_email_data = $this->get_email_data( $phpmailer ); } /** * Log successful email. * * @param array $mail_info Email information. * * @return void */ public function log_successful_email( $mail_info ): void { if( !empty( $this->settings['email_log_failed_only'] ) ) { return; } if( empty( $this->current_email_data ) ) { return; } if( empty( $this->current_email_data['subject'] ) && !empty( $mail_info['subject'] ) ) { $this->current_email_data['subject'] = $mail_info['subject']; } $this->current_email_data['status'] = 'sent'; $this->insert_log_entry( $this->current_email_data ); $this->enforce_max_entries(); $this->current_email_data = []; } /** * Log failed email. * * @param WP_Error $error Error object. * * @return void */ public function log_failed_email( $error ): void { if( empty( $this->current_email_data ) ) { return; } $error_data = $error->get_error_data(); if( empty( $this->current_email_data['subject'] ) && !empty( $error_data['subject'] ) ) { $this->current_email_data['subject'] = $error_data['subject']; } $this->current_email_data['status'] = 'failed'; $this->current_email_data['error_message'] = $error->get_error_message(); $this->insert_log_entry( $this->current_email_data ); $this->enforce_max_entries(); $this->current_email_data = []; } /** * Block and log email when disable sending mode is active. * * @param null|bool $return Short-circuit return value. * @param array $atts Array of wp_mail() arguments. * * @return bool False to prevent email from being sent. */ public function block_and_log_email( $return, $atts ): bool { if( !$this->should_log_email_from_atts( $atts ) ) { return false; } $email_data = $this->build_email_data_from_atts( $atts ); $email_data['status'] = 'blocked'; $this->insert_log_entry( $email_data ); $this->enforce_max_entries(); return false; } /** * Determines whether the email should be logged. * * @param PHPMailer $phpmailer PHPMailer instance. * * @return bool True if the email should be logged, false otherwise. */ private function should_log_email( $phpmailer ): bool { if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { if( empty( $this->settings['email_log_ajax'] ) ) { return false; } } $excluded_addresses = !empty( $this->settings['email_log_exclude_addresses'] ) ? $this->settings['email_log_exclude_addresses'] : ''; if( !empty( $excluded_addresses ) ) { $excluded_addresses_array = array_map( 'trim', explode( " ", $excluded_addresses ) ); foreach( $phpmailer->getToAddresses() as $to ) { if( in_array( $to[0], $excluded_addresses_array, true ) ) { return false; } } } return true; } /** * Determines whether the email should be logged from wp_mail atts. * * @param array $atts Array of wp_mail() arguments. * * @return bool True if the email should be logged, false otherwise. */ private function should_log_email_from_atts( array $atts ): bool { if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { if( empty( $this->settings['email_log_ajax'] ) ) { return false; } } $excluded_addresses = !empty( $this->settings['email_log_exclude_addresses'] ) ? $this->settings['email_log_exclude_addresses'] : ''; if( !empty( $excluded_addresses ) ) { $excluded_addresses_array = array_map( 'trim', explode( " ", $excluded_addresses ) ); $to_addresses = is_array( $atts['to'] ) ? $atts['to'] : [ $atts['to'] ]; foreach( $to_addresses as $to ) { if( preg_match( '/<(.+?)>/', $to, $matches ) ) { $email = $matches[1]; } else { $email = $to; } if( in_array( trim( $email ), $excluded_addresses_array, true ) ) { return false; } } } return true; } /** * Build email data array from wp_mail() atts. * * @param array $atts Array of wp_mail() arguments. * * @return array Email data array. */ private function build_email_data_from_atts( array $atts ): array { $to_addresses = is_array( $atts['to'] ) ? $atts['to'] : [ $atts['to'] ]; $to_address = implode( ', ', $to_addresses ); $from_address = $this->extract_from_address( $atts['headers'] ); $subject = $atts['subject']; $message = ''; $store_full_body = !empty( $this->settings['email_log_store_full_body'] ); if( $store_full_body ) { $message = $atts['message']; } $headers = $this->format_headers_from_atts( $atts['headers'] ); $attachments = []; if( !empty( $atts['attachments'] ) ) { $attachment_list = is_array( $atts['attachments'] ) ? $atts['attachments'] : [ $atts['attachments'] ]; foreach( $attachment_list as $attachment ) { $attachments[] = [ 'path' => $attachment, 'name' => basename( $attachment ), ]; } } $email_type = $this->detect_email_type_from_subject( $subject ); return [ 'timestamp' => current_time( 'mysql' ), 'to_address' => $to_address, 'from_address' => $from_address, 'subject' => $subject, 'message' => $message, 'headers' => $headers, 'attachments' => wp_json_encode( $attachments ), 'status' => 'pending', 'email_type' => $email_type, 'user_id' => get_current_user_id(), 'context' => $this->get_email_context(), ]; } /** * Extract From address from headers. * * @param string|array $headers Email headers. * * @return string From address. */ private function extract_from_address( $headers ): string { $from_address = 'wordpress@' . wp_parse_url( home_url(), PHP_URL_HOST ); if( empty( $headers ) ) { return $from_address; } if( is_array( $headers ) ) { $headers = implode( "\n", $headers ); } if( preg_match( '/From:\s*(.+)/i', $headers, $matches ) ) { $from_address = trim( $matches[1] ); } return $from_address; } /** * Format headers from wp_mail atts. * * @param string|array $headers Email headers. * * @return string Formatted headers. */ private function format_headers_from_atts( $headers ): string { if( empty( $headers ) ) { return ''; } if( is_array( $headers ) ) { return implode( "\n", $headers ); } return $headers; } /** * Detect email type from subject string. * * @param string $subject Email subject. * * @return string Email type. */ private function detect_email_type_from_subject( string $subject ): string { $backtrace_type = $this->detect_email_type_from_backtrace(); if( '' !== $backtrace_type ) { return $backtrace_type; } $subject_lower = strtolower( $subject ); if( strpos( $subject_lower, 'password' ) !== false && strpos( $subject_lower, 'reset' ) !== false ) { return 'password_reset'; } if( strpos( $subject_lower, 'registration' ) !== false || strpos( $subject_lower, 'account' ) !== false ) { return 'user_registration'; } if( strpos( $subject_lower, 'comment' ) !== false ) { return 'comment_notification'; } if( strpos( $subject_lower, 'order' ) !== false || strpos( $subject_lower, 'receipt' ) !== false ) { return 'woocommerce_order'; } if( strpos( $subject_lower, 'admin' ) !== false ) { return 'admin_notification'; } return 'custom'; } /** * Get email data from PHPMailer instance. * * @param PHPMailer $phpmailer PHPMailer instance. * * @return array Email data. */ private function get_email_data( $phpmailer ): array { $to_addresses = []; foreach( $phpmailer->getToAddresses() as $to ) { $to_addresses[] = $to[0]; } $from_address = $phpmailer->From; if( !empty( $phpmailer->FromName ) ) { $from_address = $phpmailer->FromName . ' <' . $phpmailer->From . '>'; } $attachments = []; foreach( $phpmailer->getAttachments() as $attachment ) { $attachments[] = [ 'path' => $attachment[0], 'name' => $attachment[2], ]; } $message = ''; $store_full_body = !empty( $this->settings['email_log_store_full_body'] ); if( $store_full_body ) { if( $phpmailer->ContentType === 'text/html' || !empty( $phpmailer->AltBody ) ) { $message = $phpmailer->Body; } else { $message = $phpmailer->Body; } } return [ 'timestamp' => current_time( 'mysql' ), 'to_address' => implode( ', ', $to_addresses ), 'from_address' => $from_address, 'subject' => $phpmailer->Subject, 'message' => $message, 'headers' => $this->format_headers( $phpmailer ), 'attachments' => wp_json_encode( $attachments ), 'status' => 'pending', 'email_type' => $this->detect_email_type( $phpmailer ), 'user_id' => get_current_user_id(), 'context' => $this->get_email_context(), ]; } /** * Format PHPMailer headers for storage. * * @param PHPMailer $phpmailer PHPMailer instance. * * @return string Formatted headers. */ private function format_headers( $phpmailer ): string { $headers = []; $headers[] = 'Content-Type: ' . $phpmailer->ContentType; $headers[] = 'From: ' . $phpmailer->From; if( !empty( $phpmailer->getReplyToAddresses() ) ) { foreach( $phpmailer->getReplyToAddresses() as $reply_to ) { $headers[] = 'Reply-To: ' . $reply_to[0]; } } if( !empty( $phpmailer->getCcAddresses() ) ) { $cc = []; foreach( $phpmailer->getCcAddresses() as $cc_address ) { $cc[] = $cc_address[0]; } $headers[] = 'Cc: ' . implode( ', ', $cc ); } if( !empty( $phpmailer->getBccAddresses() ) ) { $bcc = []; foreach( $phpmailer->getBccAddresses() as $bcc_address ) { $bcc[] = $bcc_address[0]; } $headers[] = 'Bcc: ' . implode( ', ', $bcc ); } return implode( "\n", $headers ); } /** * Detect the type of email being sent. * * @param PHPMailer $phpmailer PHPMailer instance. * * @return string Email type. */ private function detect_email_type( $phpmailer ): string { $backtrace_type = $this->detect_email_type_from_backtrace(); if( '' !== $backtrace_type ) { return $backtrace_type; } $subject = strtolower( $phpmailer->Subject ); if( strpos( $subject, 'password' ) !== false && strpos( $subject, 'reset' ) !== false ) { return 'password_reset'; } if( strpos( $subject, 'registration' ) !== false || strpos( $subject, 'account' ) !== false ) { return 'user_registration'; } if( strpos( $subject, 'comment' ) !== false ) { return 'comment_notification'; } if( strpos( $subject, 'order' ) !== false || strpos( $subject, 'receipt' ) !== false ) { return 'woocommerce_order'; } if( strpos( $subject, 'admin' ) !== false ) { return 'admin_notification'; } return 'custom'; } /** * Detect email type from the PHP call stack. * * Checks the backtrace for known plugin email class names so that type * detection works regardless of subject language or customisation. * Returns an empty string when nothing is recognised, allowing callers to * fall back to subject-based detection. * * @return string Email type, or empty string if not detected. */ private function detect_email_type_from_backtrace(): string { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); foreach( $backtrace as $trace ) { $class = $trace['class'] ?? ''; if( '' === $class ) { continue; } if( 'WC_Email_Customer_New_Account' === $class ) { return 'user_registration'; } if( 'WC_Email_Customer_Reset_Password' === $class ) { return 'password_reset'; } if( 0 === strpos( $class, 'WC_Email' ) ) { return 'woocommerce_order'; } } return ''; } /** * Get email context (triggering source). * * @return string Context description. */ private function get_email_context(): string { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); $specific_context = $this->detect_specific_context( $backtrace ); if( $specific_context ) { return $specific_context; } foreach( $backtrace as $trace ) { if( isset( $trace['file'] ) ) { $file = $trace['file']; if( strpos( $file, ADMINEASE_DIR ) !== false ) { continue; } if( strpos( $file, WP_PLUGIN_DIR ) !== false ) { $plugin_path = str_replace( WP_PLUGIN_DIR . '/', '', $file ); $plugin_slug = explode( '/', $plugin_path )[0]; $plugin_name = $this->get_plugin_name( $plugin_slug ); return $plugin_name ? 'Plugin: ' . $plugin_name : 'Plugin: ' . $plugin_slug; } if( strpos( $file, get_template_directory() ) !== false || strpos( $file, get_stylesheet_directory() ) !== false ) { return 'Theme: ' . wp_get_theme()->get( 'Name' ); } if( strpos( $file, ABSPATH . 'wp-includes' ) !== false || strpos( $file, ABSPATH . 'wp-admin' ) !== false ) { return 'WordPress Core'; } } } return 'Unknown'; } /** * Detect specific email contexts from backtrace. * * @param array $backtrace Debug backtrace array. * * @return string|null Specific context if detected, null otherwise. */ private function detect_specific_context( array $backtrace ): ?string { foreach( $backtrace as $trace ) { $class = $trace['class'] ?? ''; $function = $trace['function'] ?? ''; $file = $trace['file'] ?? ''; if( strpos( $class, 'Elementor' ) !== false && strpos( $file, 'elementor' ) !== false ) { if( strpos( $class, 'Form' ) !== false || strpos( $function, 'form' ) !== false ) { return 'Elementor Form Submission'; } return 'Elementor'; } if( strpos( $class, 'WC_' ) !== false || strpos( $class, 'WooCommerce' ) !== false ) { if( strpos( $class, 'Email' ) !== false || strpos( $function, 'email' ) !== false ) { if( strpos( $class, 'Order' ) !== false ) { return 'WooCommerce Order Email'; } return 'WooCommerce Email'; } return 'WooCommerce'; } if( strpos( $class, 'WPCF7' ) !== false || strpos( $file, 'contact-form-7' ) !== false ) { return 'Contact Form 7 Submission'; } if( strpos( $class, 'GF' ) !== false || strpos( $file, 'gravityforms' ) !== false ) { if( strpos( $function, 'notification' ) !== false ) { return 'Gravity Forms Notification'; } return 'Gravity Forms'; } if( strpos( $class, 'WPForms' ) !== false || strpos( $file, 'wpforms' ) !== false ) { return 'WPForms Submission'; } if( strpos( $class, 'NF_' ) !== false || strpos( $file, 'ninja-forms' ) !== false ) { return 'Ninja Forms Submission'; } if( strpos( $class, 'EDD_' ) !== false || strpos( $file, 'easy-digital-downloads' ) !== false ) { if( strpos( $function, 'purchase' ) !== false ) { return 'EDD Purchase Receipt'; } return 'Easy Digital Downloads'; } if( strpos( $class, 'BP_' ) !== false || strpos( $file, 'buddypress' ) !== false ) { return 'BuddyPress Notification'; } if( strpos( $class, 'BBP_' ) !== false || strpos( $file, 'bbpress' ) !== false ) { return 'bbPress Notification'; } if( $function === 'retrieve_password' || $function === 'reset_password' ) { return 'WordPress Password Reset'; } if( $function === 'wp_new_user_notification' || $function === 'register_new_user' ) { return 'WordPress User Registration'; } if( $function === 'wp_notify_postauthor' || $function === 'wp_notify_moderator' ) { return 'WordPress Comment Notification'; } if( strpos( $class, 'WPMailSMTP' ) !== false || strpos( $file, 'wp-mail-smtp' ) !== false ) { return 'WP Mail SMTP'; } } return null; } /** * Get plugin name from plugin slug. * * @param string $plugin_slug Plugin folder slug. * * @return string|null Plugin name or null if not found. */ private function get_plugin_name( string $plugin_slug ): ?string { if( !function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $all_plugins = get_plugins(); foreach( $all_plugins as $plugin_file => $plugin_data ) { if( strpos( $plugin_file, $plugin_slug . '/' ) === 0 ) { return $plugin_data['Name']; } } return null; } /** * Inserts a log entry into the database. * * @param array $data Associative array containing log entry data. * * @return void */ private function insert_log_entry( array $data ): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Real-time logging requires direct insert $wpdb->insert( $this->table_name, [ 'timestamp' => $data['timestamp'], 'to_address' => $data['to_address'], 'from_address' => $data['from_address'], 'subject' => $data['subject'], 'message' => $data['message'], 'headers' => $data['headers'], 'attachments' => $data['attachments'], 'status' => $data['status'], 'error_message' => $data['error_message'] ?? null, 'email_type' => $data['email_type'], 'user_id' => $data['user_id'] > 0 ? $data['user_id'] : null, 'context' => $data['context'], ], [ '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', ] ); } /** * Enforces the maximum number of entries in the log table. * * @return void */ private function enforce_max_entries(): void { global $wpdb; $max_entries = $this->get_max_entries(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Count check for log maintenance $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); if( $count > $max_entries ) { $delete_count = $count - $max_entries; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Log cleanup operation $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} ORDER BY timestamp ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $delete_count ) ); } } /** * Retrieves the maximum number of entries allowed. * * @return int The maximum number of entries. */ private function get_max_entries(): int { return !empty( $this->settings['email_log_max_entries'] ) ? (int) $this->settings['email_log_max_entries'] : 1000; } /** * Cleans up old logs from the database based on the configured auto-clear period. * * @return void */ public function cleanup_old_logs(): void { $auto_clear = $this->get_auto_clear_period(); if( 'never' === $auto_clear ) { return; } global $wpdb; $time_map = [ '1_hour' => 3600, '24_hours' => 86400, '7_days' => 604800, '30_days' => 2592000, ]; $seconds = $time_map[ $auto_clear ] ?? 604800; $cutoff_time = gmdate( 'Y-m-d H:i:s', time() - $seconds ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Scheduled log cleanup operation $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "DELETE FROM {$this->table_name} WHERE timestamp < %s", $cutoff_time ) ); } /** * Retrieves a list of emails from the database. * * @param array $args Query arguments. * * @return array Array of emails. */ public function get_emails( array $args = [] ): array { global $wpdb; $defaults = [ 'per_page' => 50, 'page' => 1, 'status' => '', 'type' => '', 'search' => '', 'orderby' => 'timestamp', 'order' => 'DESC', ]; $args = wp_parse_args( $args, $defaults ); $allowed_orderby = [ 'timestamp', 'to_address', 'subject', 'status', 'email_type' ]; $orderby = in_array( $args['orderby'], $allowed_orderby, true ) ? $args['orderby'] : 'timestamp'; $order = strtoupper( $args['order'] ) === 'ASC' ? 'ASC' : 'DESC'; $per_page = (int) $args['per_page']; $offset = ( (int) $args['page'] - 1 ) * $per_page; $where = []; $where_values = []; if( !empty( $args['status'] ) ) { $where[] = 'status = %s'; $where_values[] = $args['status']; } if( !empty( $args['type'] ) ) { $where[] = 'email_type = %s'; $where_values[] = $args['type']; } if( !empty( $args['search'] ) ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $where[] = '(to_address LIKE %s OR subject LIKE %s OR message LIKE %s)'; $where_values[] = $like; $where_values[] = $like; $where_values[] = $like; } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; $params = array_merge( $where_values, [ $per_page, $offset ] ); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT * FROM {$this->table_name} $where_clause ORDER BY $orderby $order LIMIT %d OFFSET %d", $params ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return $wpdb->get_results( $query, ARRAY_A ); } /** * Retrieves the total count of emails. * * @param array $args Query arguments. * * @return int Total count. */ public function get_total_count( array $args = [] ): int { global $wpdb; $where = []; $where_values = []; if( !empty( $args['status'] ) ) { $where[] = 'status = %s'; $where_values[] = $args['status']; } if( !empty( $args['type'] ) ) { $where[] = 'email_type = %s'; $where_values[] = $args['type']; } if( !empty( $args['search'] ) ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $where[] = '(to_address LIKE %s OR subject LIKE %s OR message LIKE %s)'; $where_values[] = $like; $where_values[] = $like; $where_values[] = $like; } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; if( empty( $where ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} $where_clause", $where_values ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return (int) $wpdb->get_var( $query ); } /** * Clears all email logs. * * @return bool True if successful, false otherwise. */ public function clear_emails(): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Intentional log clearing return false !== $wpdb->query( "TRUNCATE TABLE {$this->table_name}" ); } /** * Retrieves the auto-clear period. * * @return string The auto-clear period value. */ private function get_auto_clear_period(): string { return !empty( $this->settings['email_log_auto_clear'] ) ? $this->settings['email_log_auto_clear'] : '7_days'; } /** * AJAX handler to get email log. * * @return void */ public function ajax_get_email_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_refresh_email_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $page = isset( $_POST['page'] ) ? (int) $_POST['page'] : 1; $per_page = isset( $_POST['per_page'] ) ? (int) $_POST['per_page'] : 50; $status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : ''; $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : ''; $search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : ''; $args = [ 'page' => $page, 'per_page' => $per_page, 'status' => $status, 'type' => $type, 'search' => $search, ]; $emails = $this->get_emails( $args ); $total = $this->get_total_count( $args ); $date_format = get_option( 'date_format' ); $time_format = get_option( 'time_format' ); $datetime_format = $date_format . ' ' . $time_format; foreach( $emails as &$email ) { $email['formatted_time'] = date_i18n( $datetime_format, strtotime( $email['timestamp'] ) ); if( !empty( $email['user_id'] ) ) { $user = get_userdata( (int) $email['user_id'] ); $email['username_text'] = $user ? $user->user_login : esc_html__( 'Unknown', 'adminease' ); $email['user_edit_url'] = $user ? get_edit_user_link( $user->ID ) : ''; } else { $email['username_text'] = esc_html__( 'System', 'adminease' ); $email['user_edit_url'] = ''; } } wp_send_json_success( [ 'table_html' => $this->render_email_log_table( $emails ), 'total' => $total, 'page' => $page, 'per_page' => $per_page, ] ); } /** * Renders an HTML table displaying email log data. * * @param array $emails Array of email log entries. * * @return string The rendered HTML table. */ public function render_email_log_table( array $emails ): string { if( empty( $emails ) ) { return ''; } ob_start(); ?> get_status_class( $email['status'] ?? 'unknown' ); $type_class = $this->get_type_class( $email['email_type'] ?? 'custom' ); $subject = $email['subject'] ?? ''; $short_subject = mb_strlen( $subject ) > 50 ? mb_substr( $subject, 0, 50 ) . '...' : $subject; $to_address = $email['to_address'] ?? ''; $short_to = mb_strlen( $to_address ) > 30 ? mb_substr( $to_address, 0, 30 ) . '...' : $to_address; ?>
'pwp-badge-success', 'failed' => 'pwp-badge-fail', 'blocked' => 'pwp-badge-citron', ]; return $classes[ $status ] ?? 'pwp-badge-muted'; } /** * Get CSS class for email type. * * @param string $type Email type. * * @return string CSS class. */ private function get_type_class( string $type ): string { $classes = [ 'password_reset' => 'pwp-badge-citron', 'user_registration' => 'pwp-badge-success', 'comment_notification' => 'pwp-badge-muted', 'woocommerce_order' => 'pwp-badge-success', 'admin_notification' => 'pwp-badge-info', 'custom' => 'pwp-badge-muted', ]; return $classes[ $type ] ?? 'pwp-badge-muted'; } /** * Add admin bar indicator when email sending is disabled. * * @param WP_Admin_Bar $wp_admin_bar WordPress admin bar instance. * * @return void */ public function add_admin_bar_indicator( WP_Admin_Bar $wp_admin_bar ): void { if( !current_user_can( 'manage_options' ) ) { return; } if( empty( $this->settings['email_log_disable_sending'] ) ) { return; } $style = 'position: relative; top: 5px; display: inline; width: 20px; height: 20px;'; $logo_url = ADMINEASE_PLUGIN_URL . 'assets/img/adminease-logo.png?ver=' . filemtime( ADMINEASE_DIR . 'assets/img/adminease-logo.png' ); $img = ''; $wp_admin_bar->add_node( [ 'id' => 'adminease-email-disabled', /* translators: Email log disabled indicator */ 'title' => sprintf( esc_html__( '%s Emails Disabled', 'adminease' ), $img ), 'href' => admin_url( 'admin.php?page=adminease#tab-debug' ), ] ); } /** * Add inline CSS for admin bar indicator. * * @return void */ public function add_admin_bar_styles(): void { if( !current_user_can( 'manage_options' ) ) { return; } if( empty( $this->settings['email_log_disable_sending'] ) ) { return; } echo ''; } /** * AJAX handler to clear email log. * * @return void */ public function ajax_clear_email_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_clear_email_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $result = $this->clear_emails(); if( $result ) { wp_send_json_success( esc_html__( 'Email log cleared successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'clear_failed', __( 'Failed to clear email log.', 'adminease' ) ) ); } } /** * AJAX handler to resend email. * * @return void */ public function ajax_resend_email(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_resend_email' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $email_id = isset( $_POST['email_id'] ) ? (int) $_POST['email_id'] : 0; if( empty( $email_id ) ) { wp_send_json_error( new WP_Error( 'invalid_id', __( 'Invalid email ID.', 'adminease' ) ) ); } global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Fetching single email for resend $email = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $email_id ), ARRAY_A ); if( empty( $email ) ) { wp_send_json_error( new WP_Error( 'email_not_found', __( 'Email not found.', 'adminease' ) ) ); } if( !empty( $this->settings['email_log_disable_sending'] ) ) { wp_send_json_error( new WP_Error( 'email_sending_disabled', __( 'Email sending is currently disabled. Please disable the "Disable Email Sending (Log Only Mode)" feature in Debug settings before resending emails.', 'adminease' ) ) ); } $headers = explode( "\n", $email['headers'] ); $result = wp_mail( $email['to_address'], $email['subject'], $email['message'], $headers ); if( $result ) { wp_send_json_success( esc_html__( 'Email resent successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'resend_failed', __( 'Failed to resend email.', 'adminease' ) ) ); } } /** * AJAX handler to export email log. * * @return void */ public function ajax_export_email_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_export_email_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $format = isset( $_POST['format'] ) ? sanitize_text_field( wp_unslash( $_POST['format'] ) ) : 'csv'; $emails = $this->get_emails( [ 'per_page' => 10000 ] ); if( 'csv' === $format ) { $csv = $this->generate_csv( $emails ); wp_send_json_success( [ 'data' => $csv, 'filename' => 'email-log-' . gmdate( 'Y-m-d' ) . '.csv' ] ); } else { wp_send_json_success( [ 'data' => wp_json_encode( $emails ), 'filename' => 'email-log-' . gmdate( 'Y-m-d' ) . '.json' ] ); } } /** * Generate CSV from emails. * * @param array $emails Array of emails. * * @return string CSV string. */ private function generate_csv( array $emails ): string { $csv = "Timestamp,To,From,Subject,Status,Type,Error Message\n"; foreach( $emails as $email ) { $csv .= sprintf( '"%s","%s","%s","%s","%s","%s","%s"' . "\n", $email['timestamp'], str_replace( '"', '""', $email['to_address'] ), str_replace( '"', '""', $email['from_address'] ), str_replace( '"', '""', $email['subject'] ), $email['status'], $email['email_type'], str_replace( '"', '""', $email['error_message'] ?? '' ) ); } return $csv; } /** * Create the database table if it does not already exist. * * @return void */ public function create_table(): void { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$this->table_name} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, timestamp datetime NOT NULL, to_address text NOT NULL, from_address varchar(255) DEFAULT NULL, subject text DEFAULT NULL, message longtext DEFAULT NULL, headers text DEFAULT NULL, attachments text DEFAULT NULL, status varchar(20) DEFAULT 'sent', error_message text DEFAULT NULL, email_type varchar(50) DEFAULT NULL, user_id bigint(20) unsigned DEFAULT NULL, context varchar(255) DEFAULT NULL, PRIMARY KEY (id), KEY timestamp (timestamp), KEY status (status), KEY email_type (email_type), KEY user_id (user_id) ) {$charset_collate};"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * Drop the database table if it exists. * * @return void */ public function drop_table(): void { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Intentional schema change $wpdb->query( "DROP TABLE IF EXISTS {$this->table_name}" ); } /** * AJAX handler to bulk delete emails. * * @return void */ public function ajax_bulk_delete_emails(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_bulk_delete_emails' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $email_ids = isset( $_POST['email_ids'] ) ? array_map( 'intval', (array) $_POST['email_ids'] ) : []; if( empty( $email_ids ) ) { wp_send_json_error( new WP_Error( 'invalid_ids', __( 'No email IDs provided.', 'adminease' ) ) ); } global $wpdb; $placeholders = implode( ',', array_fill( 0, count( $email_ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk delete operation $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} WHERE id IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $email_ids ) ); if( false !== $deleted ) { wp_send_json_success( esc_html__( 'Selected emails deleted successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'delete_failed', __( 'Failed to delete selected emails.', 'adminease' ) ) ); } } /** * AJAX handler to bulk resend emails. * * @return void */ public function ajax_bulk_resend_emails(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_bulk_resend_emails' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $email_ids = isset( $_POST['email_ids'] ) ? array_map( 'intval', (array) $_POST['email_ids'] ) : []; if( empty( $email_ids ) ) { wp_send_json_error( new WP_Error( 'invalid_ids', __( 'No email IDs provided.', 'adminease' ) ) ); } global $wpdb; $placeholders = implode( ',', array_fill( 0, count( $email_ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk fetch for resend $emails = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE id IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $email_ids ), ARRAY_A ); if( empty( $emails ) ) { wp_send_json_error( new WP_Error( 'no_emails_to_resend', __( 'No emails found to resend.', 'adminease' ) ) ); } if( !empty( $this->settings['email_log_disable_sending'] ) ) { wp_send_json_error( new WP_Error( 'email_sending_disabled', __( 'Email sending is currently disabled. Please disable the "Disable Email Sending (Log Only Mode)" feature in Debug settings before resending emails.', 'adminease' ) ) ); } $success_count = 0; $error_count = 0; foreach( $emails as $email ) { $headers = explode( "\n", $email['headers'] ); $result = wp_mail( $email['to_address'], $email['subject'], $email['message'], $headers ); if( $result ) { $success_count ++; } else { $error_count ++; } } if( $success_count > 0 ) { /* translators: %d: number of emails resent */ $message = sprintf( _n( '%d email resent successfully.', '%d emails resent successfully.', $success_count, 'adminease' ), $success_count ); wp_send_json_success( $message ); } else { wp_send_json_error( new WP_Error( 'resend_failed', __( 'Failed to resend selected emails.', 'adminease' ) ) ); } } }