Files
Umbra-Bookshelf/Old/bd-simpleemail/inc/class-email-admin.php
bdm 38cdebd0c6 Track Bookshelf WordPress theme, plugins and specs
Initial import of the bdmurphy Bookshelf work: the bd-bookshelf theme,
bd-bookshelf-plugin, bd-bookshelfhelper and bd-simpleemail plugins, plus
the specification documents, mockups and release archives.
2026-09-28 06:24:25 -07:00

311 lines
14 KiB
PHP

<?php
/**
* Email Admin Class
*/
if (!defined('ABSPATH')) {
exit;
}
class BD_SimpleEmail_Admin {
private static $instance = null;
public static function instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
}
public function enqueue_assets($hook) {
$screen = get_current_screen();
if (strpos($hook, 'bd-simpleemail') !== false || strpos($hook, 'bd-email') !== false) {
wp_enqueue_style('bd-email-admin', BD_EMAIL_URI . 'assets/admin.css', array(), BD_EMAIL_VERSION);
wp_enqueue_script('bd-email-admin', BD_EMAIL_URI . 'assets/admin.js', array('jquery'), BD_EMAIL_VERSION, true);
}
}
public static function subscribers_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
if (isset($_POST['bd_export_subscribers'])) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=subscribers.csv');
$subscribers = $wpdb->get_results("SELECT email, first_name, status, subscribed_at FROM {$table_name} WHERE status = 'subscribed'");
echo 'Email,First Name,Status,Subscribed Date' . "\n";
foreach ($subscribers as $sub) {
echo esc_csv($sub->email) . ',' . esc_csv($sub->first_name) . ',' . esc_csv($sub->status) . ',' . esc_csv($sub->subscribed_at) . "\n";
}
exit;
}
$subscribers = $wpdb->get_results("SELECT * FROM {$table_name} ORDER BY subscribed_at DESC");
$total = count($subscribers);
$subscribed = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'subscribed'");
$unsubscribed = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'unsubscribed'");
echo '<div class="wrap">';
echo '<h1>' . esc_html__('Subscribers', 'bd-simpleemail') . '</h1>';
echo '<div class="bd-email-stats">';
echo '<div class="stat-box"><h2>' . esc_html($total) . '</h2><p>Total</p></div>';
echo '<div class="stat-box"><h2>' . esc_html($subscribed) . '</h2><p>Active</p></div>';
echo '<div class="stat-box"><h2>' . esc_html($unsubscribed) . '</h2><p>Unsubscribed</p></div>';
echo '</div>';
echo '<form method="post">';
echo '<p><input type="submit" name="bd_export_subscribers" class="button" value="' . esc_attr__('Export CSV', 'bd-simpleemail') . '"></p>';
echo '</form>';
echo '<table class="widefat">';
echo '<thead><tr><th>ID</th><th>Email</th><th>First Name</th><th>Status</th><th>Subscribed</th><th>Unsubscribed</th></tr></thead>';
echo '<tbody>';
foreach ($subscribers as $sub) {
echo '<tr>';
echo '<td>' . esc_html($sub->id) . '</td>';
echo '<td>' . esc_html($sub->email) . '</td>';
echo '<td>' . esc_html($sub->first_name) . '</td>';
echo '<td>' . esc_html($sub->status) . '</td>';
echo '<td>' . esc_html($sub->subscribed_at) . '</td>';
echo '<td>' . ($sub->unsubscribed_at ? esc_html($sub->unsubscribed_at) : '-') . '</td>';
echo '</tr>';
}
echo '</tbody></table></div>';
}
public static function new_newsletter_page() {
$error = '';
$success = '';
if (isset($_POST['bd_send_newsletter']) && check_admin_referer('bd_send_newsletter')) {
$subject = sanitize_text_field($_POST['subject']);
$content = wp_kses_post($_POST['content']);
$ai_generate = isset($_POST['ai_generate']);
$publish_blog = isset($_POST['publish_blog']);
if ($ai_generate && $subject) {
$prompt = sanitize_textarea_field($_POST['ai_prompt']);
$content = self::generate_newsletter($subject, $prompt);
}
if ($content) {
$result = BD_Email_Sender::send_newsletter($subject, $content);
if ($result['success']) {
self::log_newsletter($subject, $content, $result['count']);
$success = sprintf(__('Newsletter sent to %d subscribers!', 'bd-simpleemail'), $result['count']);
if ($publish_blog) {
self::publish_as_blog_post($subject, $content);
}
} else {
$error = $result['message'];
}
} else {
$error = __('Content is required', 'bd-simpleemail');
}
}
if ($ai_settings = BD_SimpleEmail::get_settings()) {
$has_ai = !empty($ai_settings['gemini_api_key']);
} else {
$has_ai = false;
}
echo '<div class="wrap">';
echo '<h1>' . esc_html__('New Newsletter', 'bd-simpleemail') . '</h1>';
if ($error) {
echo '<div class="error"><p>' . esc_html($error) . '</p></div>';
}
if ($success) {
echo '<div class="updated"><p>' . esc_html($success) . '</p></div>';
}
if (!$has_ai) {
echo '<div class="notice notice-warning"><p>' . esc_html__('Gemini API key not configured. AI generation disabled.', 'bd-simpleemail') . '</p></div>';
}
echo '<form method="post" id="newsletter-form">';
wp_nonce_field('bd_send_newsletter');
echo '<table class="form-table">';
echo '<tr><th>' . esc_html__('Subject', 'bd-simpleemail') . '</th>';
echo '<td><input type="text" name="subject" class="large-text" required></td></tr>';
if ($has_ai) {
echo '<tr><th>' . esc_html__('AI Generate', 'bd-simpleemail') . '</th>';
echo '<td><input type="checkbox" name="ai_generate" id="ai_generate" value="1"> <label for="ai_generate">' . esc_html__('Use Gemini AI to generate content', 'bd-simpleemail') . '</label></td></tr>';
echo '<tr class="ai-prompt-row" style="display:none;"><th>' . esc_html__('Prompt', 'bd-simpleemail') . '</th>';
echo '<td><textarea name="ai_prompt" rows="4" class="large-text" placeholder="Describe what the newsletter should contain..."></textarea></td></tr>';
}
echo '<tr><th>' . esc_html__('Content', 'bd-simpleemail') . '</th>';
echo '<td><textarea name="content" rows="20" class="large-text" id="newsletter-content"></textarea></td></tr>';
echo '<tr><th>' . esc_html__('Options', 'bd-simpleemail') . '</th>';
echo '<td><input type="checkbox" name="publish_blog" id="publish_blog" value="1"> <label for="publish_blog">' . esc_html__('Also publish as blog post', 'bd-simpleemail') . '</label></td></tr>';
echo '</table>';
echo '<p><input type="submit" name="bd_send_newsletter" class="button button-primary" value="' . esc_attr__('Send Newsletter', 'bd-simpleemail') . '"></p>';
echo '</form>';
echo '<script>';
echo "jQuery(document).ready(function($) {";
echo "$('#ai_generate').on('change', function() {";
echo "$('.ai-prompt-row').toggle(this.checked);";
echo "});";
echo "});";
echo '</script>';
echo '</div>';
}
public static function settings_page() {
if (isset($_POST['bd_save_email_settings'])) {
update_option('bdm_gmail_address', sanitize_email($_POST['gmail_address']));
update_option('bdm_sender_name', sanitize_text_field($_POST['sender_name']));
update_option('bdm_reply_to', sanitize_email($_POST['reply_to']));
if (!empty($_POST['gmail_password'])) {
update_option('bdm_gmail_password', BD_Email_Sender::encrypt_password($_POST['gmail_password']));
}
if (!empty($_POST['gemini_api_key'])) {
update_option('bdm_gemini_api_key', sanitize_text_field($_POST['gemini_api_key']));
}
echo '<div class="updated"><p>' . esc_html__('Settings saved.', 'bd-simpleemail') . '</p></div>';
}
$settings = BD_SimpleEmail::get_settings();
$business = BD_SimpleEmail::get_business_info();
echo '<div class="wrap">';
echo '<h1>' . esc_html__('BD SimpleEmail Settings', 'bd-simpleemail') . '</h1>';
echo '<form method="post">';
wp_nonce_field('bd_email_settings');
echo '<h2>' . esc_html__('Gmail Configuration', 'bd-simpleemail') . '</h2>';
echo '<p>' . esc_html__('Configure your Gmail account for sending newsletters via SMTP.', 'bd-simpleemail') . '</p>';
echo '<table class="form-table">';
echo '<tr><th>' . esc_html__('Gmail Address', 'bd-simpleemail') . '</th>';
echo '<td><input type="email" name="gmail_address" value="' . esc_attr($settings['gmail_address']) . '" class="regular-text"></td></tr>';
echo '<tr><th>' . esc_html__('App Password', 'bd-simpleemail') . '</th>';
echo '<td><input type="password" name="gmail_password" class="regular-text" placeholder="Leave blank to keep current">';
echo '<p class="description"><a href="https://support.google.com/accounts/answer/185833" target="_blank">' . esc_html__('Learn how to generate an app password', 'bd-simpleemail') . '</a></p></td></tr>';
echo '<tr><th>' . esc_html__('Sender Name', 'bd-simpleemail') . '</th>';
echo '<td><input type="text" name="sender_name" value="' . esc_attr($settings['sender_name']) . '" class="regular-text"></td></tr>';
echo '<tr><th>' . esc_html__('Reply-To', 'bd-simpleemail') . '</th>';
echo '<td><input type="email" name="reply_to" value="' . esc_attr($settings['reply_to']) . '" class="regular-text"></td></tr>';
echo '</table>';
echo '<h2>' . esc_html__('Gemini AI', 'bd-simpleemail') . '</h2>';
echo '<table class="form-table">';
echo '<tr><th>' . esc_html__('API Key', 'bd-simpleemail') . '</th>';
echo '<td><input type="text" name="gemini_api_key" value="' . esc_attr($settings['gemini_api_key']) . '" class="regular-text">';
echo '<p class="description"><a href="https://makersuite.google.com/app/apikey" target="_blank">' . esc_html__('Get your API key', 'bd-simpleemail') . '</a></p></td></tr>';
echo '</table>';
echo '<h2>' . esc_html__('Business Information (CAN-SPAM)', 'bd-simpleemail') . '</h2>';
echo '<p>' . esc_html__('These fields are required for CAN-SPAM compliance and appear in email footers.', 'bd-simpleemail') . '</p>';
echo '<table class="form-table">';
echo '<tr><th>' . esc_html__('Business Name', 'bd-simpleemail') . '</th>';
echo '<td>' . esc_html($business['name'] ?: '-') . '</td></tr>';
echo '<tr><th>' . esc_html__('Address', 'bd-simpleemail') . '</th>';
echo '<td>' . esc_html($business['address_1']) . '<br>' . esc_html($business['address_2']) . '<br>' . esc_html($business['city']) . '<br>' . esc_html($business['country']) . '</td></tr>';
echo '<tr><th>' . esc_html__('Phone', 'bd-simpleemail') . '</th>';
echo '<td>' . esc_html($business['phone'] ?: '-') . '</td></tr>';
echo '</table>';
echo '<p><input type="submit" name="bd_save_email_settings" class="button button-primary" value="' . esc_attr__('Save Settings', 'bd-simpleemail') . '"></p>';
echo '</form></div>';
}
private static function generate_newsletter($subject, $prompt) {
$settings = BD_SimpleEmail::get_settings();
if (empty($settings['gemini_api_key'])) {
return '';
}
$system_instruction = "You are a professional newsletter writer for an author. Write engaging, concise newsletter content in HTML format. Use <p> for paragraphs, <h2> for headings, and <ul> for lists. Keep it friendly but professional.";
$full_prompt = $system_instruction . "\n\nSubject: " . $subject . "\n\nAdditional instructions: " . $prompt;
$api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $settings['gemini_api_key'];
$body = array(
'contents' => array(
array(
'parts' => array(
array('text' => $full_prompt)
)
)
),
'generationConfig' => array(
'temperature' => 0.9,
'maxOutputTokens' => 2048,
),
);
$response = wp_remote_post($api_url, array(
'body' => json_encode($body),
'headers' => array(
'Content-Type' => 'application/json',
),
));
if (is_wp_error($response)) {
return '';
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
return $data['candidates'][0]['content']['parts'][0]['text'];
}
return '';
}
private static function log_newsletter($subject, $content, $recipient_count) {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_newsletters';
$wpdb->insert($table_name, array(
'subject' => $subject,
'body_html' => $content,
'sent_at' => current_time('mysql'),
'recipient_count' => $recipient_count,
));
}
private static function publish_as_blog_post($subject, $content) {
$post_id = wp_insert_post(array(
'post_title' => $subject,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'post',
));
return $post_id;
}
}