rl-warmup-plugin/includes/rl-mailwarmer-ajax.php

927 lines
No EOL
32 KiB
PHP

<?php
/**
* AJAX endpoints for domain, campaign, and email account management
*/
// DOMAIN MANAGEMENT AJAX ENDPOINTS
/**
* Create or update a domain via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_save_domain', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'domain_form_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$current_user_id = get_current_user_id();
$post_title = strtolower(sanitize_text_field($_POST['domain_name']));
$cloudflare_email = isset($_POST['cloudflare_api_email']) ? sanitize_email($_POST['cloudflare_api_email']) : '';
$cloudflare_key = isset($_POST['cloudflare_api_key']) ? sanitize_text_field($_POST['cloudflare_api_key']) : '';
$domain_in_use = isset($_POST['domain_in_use']) ? $_POST['domain_in_use'] : '';
$update_dns = isset($_POST['update_dns']) ? $_POST['update_dns'] : '';
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
$new_post = ($post_id == 0);
// Check for existing domain with same name for new posts
if ($new_post) {
$args = [
'post_type' => 'domain',
'post_status' => 'any',
'title' => $post_title,
'fields' => 'ids',
'posts_per_page' => 1
];
$query = new WP_Query($args);
if ($query->have_posts()) {
wp_send_json_error(['message' => __('Domain already exists.', 'rl-mailwarmer')]);
return;
}
}
// Prepare post data
$post_data = array(
'post_title' => $post_title,
'post_type' => 'domain',
'post_status' => 'publish'
);
if ($post_id) {
$post_data['ID'] = $post_id;
$post_id = wp_update_post($post_data);
} else {
$post_id = wp_insert_post($post_data);
}
if (is_wp_error($post_id)) {
wp_send_json_error(['message' => $post_id->get_error_message()]);
return;
}
// Update meta fields
update_post_meta($post_id, 'cloudflare_api_email', $cloudflare_email);
update_post_meta($post_id, 'cloudflare_api_key', $cloudflare_key);
update_post_meta($post_id, 'domain_in_use', $domain_in_use);
if ($new_post) {
// Set owner to current user for new domains
update_post_meta($post_id, 'owner_id', $current_user_id);
// Run domain health check for new domains
RL_MailWarmer_Domain_Helper::save_domain_health_report($post_id);
}
// Handle DNS updates if requested
if ($update_dns) {
$results = RL_MailWarmer_Domain_Helper::fix_deliverability_dns_issues($post_id);
}
// Handle MX records based on domain usage
if (!$domain_in_use) {
$server = get_field('defaut_mailferno_mx', 'option');
$update_MX_result = RL_MailWarmer_Domain_Helper::update_mx_record($post_id, $server->post_title, 0, $ttl = 3600);
}
// Return success response with post ID and permalink
wp_send_json_success([
'message' => $new_post ? __('Domain added successfully.', 'rl-mailwarmer') : __('Domain updated successfully.', 'rl-mailwarmer'),
'post_id' => $post_id,
'permalink' => get_permalink($post_id)
]);
});
/**
* Delete a domain via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_delete_domain', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'domain_delete_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
if (!$post_id) {
wp_send_json_error(__('Invalid domain ID', 'rl-mailwarmer'));
return;
}
// Verify post type and user permissions
$post = get_post($post_id);
if (!$post || $post->post_type !== 'domain') {
wp_send_json_error(__('Invalid domain', 'rl-mailwarmer'));
return;
}
// Verify ownership
$owner_id = get_post_meta($post_id, 'owner_id', true);
if ($owner_id != get_current_user_id() && !current_user_can('manage_options')) {
wp_send_json_error(__('Permission denied', 'rl-mailwarmer'));
return;
}
// Delete the domain
$result = wp_delete_post($post_id, true);
if (!$result) {
wp_send_json_error(__('Failed to delete domain', 'rl-mailwarmer'));
return;
}
wp_send_json_success(['message' => __('Domain deleted successfully', 'rl-mailwarmer')]);
});
add_action('wp_ajax_rl_mailwarmer_check_domain_health', function () {
// log_to_file("wp_ajax_rl_mailwarmer_check_domain_health called");
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'check_domain_health_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Get the domain post ID
$post_id = intval($_POST['post_id']);
if (!$post_id) {
wp_send_json_error(__('Invalid post ID', 'rl-mailwarmer'));
}
// log_to_file("wp_ajax_rl_mailwarmer_check_domain_health - Creating Domain Health Report for $post_id");
// Call the save_domain_health_report function
try {
// log_to_file("Creating new Domain Health Report for $post_id");
$report_post_id = RL_MailWarmer_Domain_Helper::save_domain_health_report($post_id);
if (is_wp_error($report_post_id)) {
wp_send_json_error($report_post_id->get_error_message());
// log_to_file("wp_ajax_rl_mailwarmer_check_domain_health - Error creating Domain Health Report: " . $report_post_id->get_error_message());
}
wp_send_json_success($report_post_id);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
// log_to_file("wp_ajax_rl_mailwarmer_check_domain_health - EXCEPTION while creating Domain Health Report: " . $e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_update_mx_record', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'update_mx_record_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// log_to_file("wp_ajax_rl_mailwarmer_update_mx_record - Running");
// Get input values
$post_id = intval($_POST['post_id']);
$action = sanitize_text_field($_POST['action_type']);
$content = sanitize_text_field($_POST['content']);
$priority = intval(sanitize_text_field($_POST['priority']));
$ttl = intval($_POST['ttl']);
if (!$post_id || !$content || !$action) {
wp_send_json_error(__('Missing required fields', 'rl-mailwarmer'));
}
$domain = RL_MailWarmer_Domain_Helper::get_domain_post($post_id);
// log_to_file("wp_ajax_rl_mailwarmer_update_mx_record - Post ID: $post_id $content $action $priority $ttl");
// Call the update_mx_record function
try {
log_to_file("wp_ajax_rl_mailwarmer_update_mx_record - Before");
$result = RL_MailWarmer_Domain_Helper::update_mx_record($domain, $content, $priority, $ttl, $action);
log_to_file("wp_ajax_rl_mailwarmer_update_mx_record - After");
if ($result) {
wp_send_json_success(__('MX record updated successfully.', 'rl-mailwarmer'));
} else {
wp_send_json_error(__('Failed to update MX record.', 'rl-mailwarmer'));
}
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_update_spf_record', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'update_spf_record_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// log_to_file("wp_ajax_rl_mailwarmer_update_spf_record - Running");
// Get input values
$post_id = intval($_POST['post_id']);
$host = sanitize_text_field($_POST['host']);
$action = sanitize_text_field($_POST['action_type']);
$all_policy = sanitize_text_field($_POST['all_policy']);
$ttl = intval($_POST['ttl']);
if (!$post_id || !$host || !$action) {
wp_send_json_error(__('Missing required fields', 'rl-mailwarmer'));
}
$domain = RL_MailWarmer_Domain_Helper::get_domain_post($post_id);
// log_to_file("wp_ajax_rl_mailwarmer_update_spf_record - Post ID: $post_id $host $action $all_policy $ttl");
// Call the update_spf_record function
try {
// log_to_file("wp_ajax_rl_mailwarmer_update_spf_record - Before");
$result = RL_MailWarmer_Domain_Helper::update_spf_record($domain, $host, $action, $all_policy, $ttl);
// log_to_file("wp_ajax_rl_mailwarmer_update_spf_record - After");
if ($result) {
wp_send_json_success(__('SPF record updated successfully.', 'rl-mailwarmer'));
} else {
wp_send_json_error(__('Failed to update SPF record.', 'rl-mailwarmer'));
}
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_update_dmarc_record', function () {
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'update_dmarc_record_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
$post_id = intval($_POST['post_id']);
if (!$post_id) {
wp_send_json_error(__('Invalid post ID', 'rl-mailwarmer'));
}
$params = array_filter([
'p' => sanitize_text_field($_POST['policy']),
'sp' => sanitize_text_field($_POST['sp']),
'pct' => intval($_POST['pct']),
'aspf' => sanitize_text_field($_POST['aspf']),
'adkim' => sanitize_text_field($_POST['adkim']),
'rua' => sanitize_email($_POST['rua']) ? 'mailto:' . sanitize_email($_POST['rua']) : null,
'ruf' => sanitize_email($_POST['ruf']) ? 'mailto:' . sanitize_email($_POST['ruf']) : null,
'fo' => sanitize_text_field($_POST['fo']),
'rf' => sanitize_text_field($_POST['rf']),
'ri' => intval($_POST['ri']),
]);
try {
$result = RL_MailWarmer_Domain_Helper::update_dmarc_record($post_id, $params);
if ($result) {
wp_send_json_success(__('DMARC record updated successfully.', 'rl-mailwarmer'));
} else {
wp_send_json_error(__('Failed to update DMARC record.', 'rl-mailwarmer'));
}
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_update_dkim_record', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'update_dkim_record_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Get input values
$post_id = intval($_POST['post_id']);
$selector = sanitize_text_field($_POST['selector']);
$action = sanitize_text_field($_POST['action_type']);
$value = sanitize_textarea_field($_POST['value']);
$ttl = intval($_POST['ttl']);
if (!$post_id || !$selector || !$action) {
wp_send_json_error(__('Missing required fields', 'rl-mailwarmer'));
}
// Call the update_dkim_record function
try {
$result = RL_MailWarmer_Domain_Helper::update_dkim_record($post_id, $selector, $action, $value, $ttl);
if ($result) {
wp_send_json_success(__('DKIM record updated successfully.', 'rl-mailwarmer'));
} else {
wp_send_json_error(__('Failed to update DKIM record.', 'rl-mailwarmer'));
}
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_fix_dns_issues', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'fix_deliverability_dns_issues_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Get the domain post ID
$post_id = intval($_POST['post_id']);
if (!$post_id) {
wp_send_json_error(__('Invalid post ID', 'rl-mailwarmer'));
}
// Call the fix_deliverability_dns_issues function
try {
$results = RL_MailWarmer_Domain_Helper::fix_deliverability_dns_issues($post_id);
wp_send_json_success($results);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_create_dns_backup', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'create_dns_backup_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Get the domain post ID
$post_id = intval($_POST['post_id']);
if (!$post_id) {
wp_send_json_error(__('Invalid post ID', 'rl-mailwarmer'));
}
$domain = get_post($post_id);
// Call the create_dns_backup function
try {
$backup_id = RL_MailWarmer_Domain_Helper::export_dns_zone($domain);
if (is_wp_error($backup_id)) {
wp_send_json_error($backup_id->get_error_message());
}
wp_send_json_success($backup_id);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
// CAMPAIGN MANAGEMENT AJAX ENDPOINTS
/**
* Create or update a campaign via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_save_campaign', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'campaign_form_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$current_user_id = get_current_user_id();
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
$new_post = ($post_id == 0);
$calculate_timeline = isset($_POST['calculate_timeline']) ? true : false;
$target_profession = false;
$target_profession_other = false;
// Prepare post data
$post_data = array(
'post_title' => sanitize_text_field($_POST['campaign_name']),
'post_type' => 'campaign',
'post_status' => 'publish'
);
if ($post_id) {
$post_data['ID'] = $post_id;
$post_id = wp_update_post($post_data);
} else {
$post_id = wp_insert_post($post_data);
// Generate tracking ID for new campaigns
RL_MailWarmer_Campaign_Helper::generate_campaign_tracking_id($post_id);
}
if (is_wp_error($post_id)) {
wp_send_json_error(['message' => $post_id->get_error_message()]);
return;
}
// Update campaign enabled status
$campaign_enabled = isset($_POST['enabled']) ? true : false;
update_post_meta($post_id, 'enabled', $campaign_enabled);
// Update ACF fields
$acf_fields = [
'domain_id',
'email_accounts',
'start_date',
'warmup_period',
'starting_volume',
'target_volume',
'weekend_reduction_factor',
'target_profession',
'target_profession_other',
'campaign_conversation_topics'
];
foreach ($acf_fields as $field) {
if (isset($_POST[$field])) {
switch ($field) {
case 'email_accounts':
$campaign_email_accounts = $_POST[$field];
$is_limited = false;
// Check if any email account has limited access
foreach ($campaign_email_accounts as $account_id) {
$limited_access = get_post_meta($account_id, 'limited_access', true);
if ($limited_access === true || $limited_access === '1') {
$is_limited = true;
break;
}
}
// Update campaign_limited flag
update_post_meta($post_id, 'campaign_limited', $is_limited);
update_field($field, $campaign_email_accounts, $post_id);
break;
case 'domain_id':
try {
update_field('domain', $_POST['domain_id'], $post_id);
} catch (Exception $e) {
wp_send_json_error(['message' => $e->getMessage()]);
return;
}
break;
case 'target_profession':
$target_profession = $_POST[$field];
break;
case 'target_profession_other':
$target_profession_other = $_POST[$field];
break;
default:
update_field($field, sanitize_text_field($_POST[$field]), $post_id);
break;
}
}
}
if ($target_profession_other) {
$target_profession = $target_profession_other;
}
// If no target profession is set, choose one from the default profession pool.
if ( ! $target_profession ) {
$professions = rl_get_textarea_meta_as_array('option', 'default_profession_pool');
if ( ! empty($professions) ) {
// Assign a random profession from the list
$target_profession = $professions[array_rand($professions)];
}
}
// Set campaign owner
update_post_meta($post_id, 'owner_id', $current_user_id);
// Calculate timeline if needed
if ($new_post || $calculate_timeline) {
RL_MailWarmer_DB_Helper::delete_all_conversations_messages($post_id);
RL_MailWarmer_Campaign_Helper::calculate_campaign_timeline($post_id);
}
// Return success response
wp_send_json_success([
'message' => $new_post ? __('Campaign added successfully.', 'rl-mailwarmer') : __('Campaign updated successfully.', 'rl-mailwarmer'),
'post_id' => $post_id,
'permalink' => get_permalink($post_id)
]);
});
/**
* Delete a campaign via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_delete_campaign', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'campaign_delete_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
if (!$post_id) {
wp_send_json_error(__('Invalid campaign ID', 'rl-mailwarmer'));
return;
}
// Verify post type
$post = get_post($post_id);
if (!$post || $post->post_type !== 'campaign') {
wp_send_json_error(__('Invalid campaign', 'rl-mailwarmer'));
return;
}
// Verify ownership
$owner_id = get_post_meta($post_id, 'owner_id', true);
if ($owner_id != get_current_user_id() && !current_user_can('manage_options')) {
wp_send_json_error(__('Permission denied', 'rl-mailwarmer'));
return;
}
// Delete campaign messages and timeline first
RL_MailWarmer_DB_Helper::delete_all_conversations_messages($post_id);
// Delete the campaign
$result = wp_delete_post($post_id, true);
if (!$result) {
wp_send_json_error(__('Failed to delete campaign', 'rl-mailwarmer'));
return;
}
wp_send_json_success(['message' => __('Campaign deleted successfully', 'rl-mailwarmer')]);
});
// EMAIL ACCOUNT MANAGEMENT AJAX ENDPOINTS
/**
* Create or update an email account via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_save_email_account', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'email_form_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$current_user_id = get_current_user_id();
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
$post_title = strtolower(sanitize_email($_POST['email_address']));
$new_post = ($post_id == 0);
// Check for existing email account with same address for new posts
if ($new_post) {
$args = [
'post_type' => 'email-account',
'post_status' => 'any',
'title' => $post_title,
'fields' => 'ids',
'posts_per_page' => 1
];
$query = new WP_Query($args);
if ($query->have_posts()) {
wp_send_json_error(['message' => __('Email account already exists.', 'rl-mailwarmer')]);
return;
}
}
// Prepare post data
$post_data = array(
'post_title' => $post_title,
'post_type' => 'email-account',
'post_status' => 'publish'
);
if ($post_id) {
$post_data['ID'] = $post_id;
$post_id = wp_update_post($post_data);
} else {
$post_id = wp_insert_post($post_data);
}
if (is_wp_error($post_id)) {
wp_send_json_error(['message' => $post_id->get_error_message()]);
return;
}
// Update meta fields
$meta_fields = [
'domain_id', 'mail_password', 'full_name', 'email_signature',
'email_provider', 'smtp_password', 'smtp_server', 'smtp_port',
'imap_password', 'imap_server', 'imap_port'
];
foreach ($meta_fields as $field) {
if (isset($_POST[$field])) {
update_post_meta($post_id, $field, sanitize_text_field($_POST[$field]));
}
}
// For new accounts, set ownership and include in warmup pool
if ($new_post) {
update_post_meta($post_id, 'owner_id', $current_user_id);
update_post_meta($post_id, 'include_in_warmup_pool', $current_user_id);
}
// Return success response
wp_send_json_success([
'message' => $new_post ? __('Email account added successfully.', 'rl-mailwarmer') : __('Email account updated successfully.', 'rl-mailwarmer'),
'post_id' => $post_id,
'permalink' => get_permalink($post_id)
]);
});
/**
* Delete an email account via AJAX
*/
add_action('wp_ajax_rl_mailwarmer_delete_email_account', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'email_delete_nonce')) {
wp_send_json_error(__('Security check failed', 'rl-mailwarmer'));
}
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
if (!$post_id) {
wp_send_json_error(__('Invalid email account ID', 'rl-mailwarmer'));
return;
}
// Verify post type
$post = get_post($post_id);
if (!$post || $post->post_type !== 'email-account') {
wp_send_json_error(__('Invalid email account', 'rl-mailwarmer'));
return;
}
// Verify ownership
$owner_id = get_post_meta($post_id, 'owner_id', true);
if ($owner_id != get_current_user_id() && !current_user_can('manage_options')) {
wp_send_json_error(__('Permission denied', 'rl-mailwarmer'));
return;
}
// Delete the email account
$result = wp_delete_post($post_id, true);
if (!$result) {
wp_send_json_error(__('Failed to delete email account', 'rl-mailwarmer'));
return;
}
wp_send_json_success(['message' => __('Email account deleted successfully', 'rl-mailwarmer')]);
});
add_action('wp_ajax_rl_mailwarmer_modify_email_account', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'modify_email_account_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Prepare arguments for modify_email_account
$args = [
'action' => sanitize_text_field($_POST['action_type']),
'email' => sanitize_email($_POST['email_address']),
'metadata' => [
'mail_password' => sanitize_text_field($_POST['mail_password']),
'email_provider' => intval($_POST['email_provider']),
'imap_server' => sanitize_text_field($_POST['imap_server']),
],
];
// Call modify_email_account
try {
$result = RL_MailWarmer_Email_Helper::modify_email_account($args);
wp_send_json_success('Email account successfully modified. Post ID: ' . $result);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
add_action('wp_ajax_rl_mailwarmer_check_mail_login', function () {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'check_mail_login_nonce')) {
wp_send_json_error(__('Invalid nonce', 'rl-mailwarmer'));
}
// Validate and sanitize input
$post_id = intval($_POST['post_id']);
$protocol = !empty($_POST['protocol']) ? sanitize_text_field($_POST['protocol']) : null;
if (!$post_id || get_post_type($post_id) !== 'email-account') {
wp_send_json_error(__('Invalid email account ID.', 'rl-mailwarmer'));
}
// Call check_mail_login
try {
$results = RL_MailWarmer_Email_Helper::check_mail_login($post_id, $protocol);
wp_send_json_success($results);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
});
/**
* Dashboard Modal AJAX handlers
*/
/**
* Validate domain for adding to Mailferno
*/
add_action('wp_ajax_validate_domain', function() {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'dashboard_modal_nonce')) {
wp_send_json_error(['message' => __('Security check failed', 'rl-mailwarmer')]);
}
// Get and validate domain
$domain = isset($_POST['domain']) ? sanitize_text_field($_POST['domain']) : '';
if (empty($domain)) {
wp_send_json_error(['message' => __('Domain name is required', 'rl-mailwarmer')]);
}
// Check if domain already exists
$existing_domain = get_page_by_title($domain, OBJECT, 'domain');
if ($existing_domain) {
wp_send_json_error(['message' => __('Domain already exists in your account', 'rl-mailwarmer')]);
return;
}
// Check if domain is valid (DNS resolves)
if (!checkdnsrr($domain, 'A') && !checkdnsrr($domain, 'AAAA')) {
wp_send_json_error(['message' => __('Domain does not resolve to a valid IP address', 'rl-mailwarmer')]);
return;
}
// Check if domain uses CloudFlare
$uses_cloudflare = false;
// Get the NS records for the domain
$ns_records = dns_get_record($domain, DNS_NS);
// If no NS records found directly, try with www
if (empty($ns_records)) {
$ns_records = dns_get_record('www.' . $domain, DNS_NS);
}
// Check if any NS record contains cloudflare
if (!empty($ns_records)) {
foreach ($ns_records as $record) {
if (isset($record['target']) && stripos($record['target'], 'cloudflare') !== false) {
$uses_cloudflare = true;
break;
}
}
}
wp_send_json_success([
'isValid' => true,
'usesCloudFlare' => $uses_cloudflare
]);
});
/**
* Verify CloudFlare credentials and check MX records
*/
add_action('wp_ajax_verify_cloudflare', function() {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'dashboard_modal_nonce')) {
wp_send_json_error(['message' => __('Security check failed', 'rl-mailwarmer')]);
}
$domain = isset($_POST['domain']) ? sanitize_text_field($_POST['domain']) : '';
$email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
$key = isset($_POST['key']) ? sanitize_text_field($_POST['key']) : '';
if (empty($domain) || empty($email) || empty($key)) {
wp_send_json_error(['message' => __('Missing required fields', 'rl-mailwarmer')]);
return;
}
// Use existing cloudflare helper to verify credentials and get zone ID
try {
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://api.cloudflare.com/client/v4/',
'headers' => [
'Content-Type' => 'application/json',
],
]);
$response = $client->get('zones', [
'headers' => [
'Authorization' => "Bearer {$key}",
'Content-Type' => 'application/json',
],
'query' => ['name' => $domain],
]);
$data = json_decode($response->getBody()->getContents(), true);
if (!isset($data['result'][0]['id'])) {
wp_send_json_error(['message' => __('Domain not found in your CloudFlare account', 'rl-mailwarmer')]);
return;
}
$zone_id = $data['result'][0]['id'];
// Check if MX records exist
$has_mx = false;
// Query CloudFlare for MX records
$mx_response = $client->get("zones/{$zone_id}/dns_records", [
'headers' => [
'Authorization' => "Bearer {$key}",
'Content-Type' => 'application/json',
],
'query' => ['type' => 'MX'],
]);
$mx_data = json_decode($mx_response->getBody()->getContents(), true);
if (isset($mx_data['result']) && !empty($mx_data['result'])) {
$has_mx = true;
}
wp_send_json_success([
'zoneId' => $zone_id,
'hasMX' => $has_mx
]);
} catch (Exception $e) {
wp_send_json_error(['message' => __('Failed to verify CloudFlare credentials: ', 'rl-mailwarmer') . $e->getMessage()]);
}
});
/**
* Create domain with all configurations
*/
add_action('wp_ajax_create_domain', function() {
// Verify nonce
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'dashboard_modal_nonce')) {
wp_send_json_error(['message' => __('Security check failed', 'rl-mailwarmer')]);
}
// Get domain data
$domain_data_json = isset($_POST['domainData']) ? $_POST['domainData'] : '';
if (empty($domain_data_json)) {
wp_send_json_error(['message' => __('No domain data provided', 'rl-mailwarmer')]);
return;
}
$domain_data = json_decode(stripslashes($domain_data_json), true);
// Create the domain post
$current_user_id = get_current_user_id();
$domain_name = $domain_data['domain'];
$post_data = array(
'post_title' => $domain_name,
'post_type' => 'domain',
'post_status' => 'publish'
);
$post_id = wp_insert_post($post_data);
if (is_wp_error($post_id)) {
wp_send_json_error(['message' => $post_id->get_error_message()]);
return;
}
// Save domain meta data
update_post_meta($post_id, 'cloudflare_api_email', $domain_data['cloudflareEmail']);
update_post_meta($post_id, 'cloudflare_api_key', $domain_data['cloudflareKey']);
update_post_meta($post_id, 'cloudflare_zone_id', $domain_data['cloudflareZoneId']);
update_post_meta($post_id, 'domain_in_use', !$domain_data['configureMailferno']);
update_post_meta($post_id, 'owner_id', $current_user_id);
// Run a domain health check
$domain_report_id = RL_MailWarmer_Domain_Helper::save_domain_health_report($post_id);
// Handle DNS configuration if requested
if ($domain_data['configureMailferno']) {
$server = get_field('defaut_mailferno_mx', 'option');
RL_MailWarmer_Domain_Helper::update_mx_record($post_id, $server->post_title, 0, 3600);
}
// Fix DNS records
$results = RL_MailWarmer_Domain_Helper::fix_deliverability_dns_issues($post_id);
// Create email accounts if provided
$email_accounts = [];
if (!empty($domain_data['emailAccounts'])) {
foreach ($domain_data['emailAccounts'] as $email) {
// Extract username from email
$username = explode('@', $email)[0];
// Create email account
$email_post_data = array(
'post_title' => $email,
'post_type' => 'email-account',
'post_status' => 'publish'
);
$email_post_id = wp_insert_post($email_post_data);
if (!is_wp_error($email_post_id)) {
// Set default password and metadata
update_post_meta($email_post_id, 'domain_id', $post_id);
update_post_meta($email_post_id, 'mail_password', wp_generate_password(12, false));
update_post_meta($email_post_id, 'full_name', ucwords(str_replace(['.', '-', '_'], ' ', $username)));
update_post_meta($email_post_id, 'owner_id', $current_user_id);
update_post_meta($email_post_id, 'include_in_warmup_pool', true);
$email_accounts[] = $email_post_id;
}
}
}
wp_send_json_success([
'message' => __('Domain added successfully. ' . (!empty($email_accounts) ? count($email_accounts) . ' email accounts created.' : ''), 'rl-mailwarmer'),
'domain_id' => $post_id,
'email_accounts' => $email_accounts
]);
});