Files
Bookshelf/umbra-bookshelf/includes/email/class-umbra-email-admin.php
bdm dec732931c Consolidate three plugins into Umbra Bookshelf
Merge BD Bookshelf (0.1.0), BD BookShelfHelper (2.0.0) and BD SimpleEmail
(2.0.0) into a single plugin released as Umbra Bookshelf 1.0.0, with the
BD Bookshelf theme left as a separate, unrenamed artifact.

Modules
  includes/books/    catalogue, ISBN/ASIN, series, retail, ratings, shortcodes,
                     SEO, GDPR, scrapers, admin, CSV/post import
  includes/library/  book post type + series taxonomy, pen names, data entry,
                     shortlinks, reviews, migrate
  includes/email/    subscribers, newsletters, composition, sending

Renamed: plugin headers, text domains (all three -> umbra-bookshelf), classes
(BD_*/BDM_* -> Umbra_*), constants (-> UMBRA_BOOKSHELF_*), asset handles, JS
globals and admin slugs.

Deliberately not renamed -- persisted contract with live installs and with
published post content: table names, option keys, post meta keys, transients,
nonce actions, cron hooks, AJAX actions, shortcodes ([bd-book], [bd-books],
[bdm_signup]), post type `book`, taxonomy `series`, cookies and CSS classes.
BD_BookShelfHelper survives only as a class_alias for the unmodified theme.

Collisions resolved
  * class-umbra-theme-compatibility.php declared BD_BookShelfHelper, the same
    name as the library module's helper. Latent while the plugins were
    separate (only fired when both were active), but an unconditional fatal
    once merged. Renamed to Umbra_Theme_Compatibility with a class_alias.
  * All three modules called add_menu_page. One top-level menu is now
    registered by the bootstrap at admin_menu priority 9.
  * BD Bookshelf and BookShelfHelper both claimed bd-bookshelf-settings, leaving
    one Settings screen unreachable -> umbra-bookshelf-settings and
    umbra-bookshelf-library-settings.
  * Catalogue and library both enqueued bd-bookshelf-admin; the second enqueue
    was silently discarded -> unique handles per module.
  * Umbra_Admin and Umbra_Migration both registered bd_bookshelf_import_csv, so
    one handler silently replaced the other. The import page now lives only in
    Umbra_Admin (the variant wired to the admin JS); Umbra_Migration keeps only
    the preview/run endpoints it uniquely provides.
  * Modules were constructed from an init callback, so their own init
    registrations raced the hook being dispatched. Now constructed on
    plugins_loaded behind a re-entrancy guard.

Also
  * Missing assets created: assets/images/default-cover.png (referenced but
    never committed, so every cover-less book 404'd) and email/assets/js/
    admin.js (enqueued on every email admin page but never committed).
  * Library module's strpos($hook, 'bd-bookshelf') asset check matched every
    catalogue and email screen once slugs shared the umbra-bookshelf- prefix;
    now matched against its own slug list.
  * Consolidated uninstall deduplicates the double drop of bd_books/bd_series.
  * Specs aligned to the new name; pre-merge specs retained under
    spec/archive/ with provenance notes.
  * Tests added: tests/verify_structure.py (static) and tests/smoke_runtime.php
    (WordPress-stub runtime boot, front-end and admin contexts).

Deferred and recorded in docs/KNOWN-ISSUES.md: the catalogue and library
modules still create bd_books and bd_series with two incompatible schemas
(pre-existing, now unconditional), and Goodreads/Amazon scraping is still
implemented twice on shared cron hooks.
2026-10-18 19:55:36 -07:00

391 lines
15 KiB
PHP

<?php
// Copyright 2026 Umbra Tools (umbratools.com)
// SPDX-License-Identifier: Apache-2.0
/**
* Email Admin Class
*
* @package Umbra_Simple_Email
*/
if (!defined('ABSPATH')) {
exit;
}
class Umbra_Simple_Email_Admin {
private static $instance = null;
/**
* Get instance
*
* @return Umbra_Simple_Email_Admin
*/
public static function instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
}
/**
* Enqueue admin assets
*
* @param string $hook Current admin page.
*/
public function enqueue_assets($hook) {
// Matches the submenu slugs registered by Umbra_Simple_Email::add_menu_pages().
if (strpos($hook, 'umbra-bookshelf-subscribers') !== false
|| strpos($hook, 'umbra-bookshelf-newsletter') !== false
|| strpos($hook, 'umbra-bookshelf-email-settings') !== false) {
wp_enqueue_style(
'umbra-bookshelf-email-admin',
UMBRA_BOOKSHELF_URL . 'email/assets/css/admin.css',
array(),
UMBRA_BOOKSHELF_EMAIL_VERSION
);
wp_enqueue_script(
'umbra-bookshelf-email-admin',
UMBRA_BOOKSHELF_URL . 'email/assets/js/admin.js',
array('jquery'),
UMBRA_BOOKSHELF_EMAIL_VERSION,
true
);
}
}
/**
* Subscribers page
*/
public static function subscribers_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
if (isset($_POST['bd_export_subscribers'])) {
check_admin_referer('bd_export_subscribers');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=subscribers-' . date('Y-m-d') . '.csv');
$subscribers = $wpdb->get_results(
"SELECT email, first_name, status, subscribed_at FROM {$table_name} WHERE status = 'subscribed'"
);
printf("Email,First Name,Status,Subscribed Date\n");
foreach ($subscribers as $sub) {
printf("%s,%s,%s,%s\n",
esc_html($sub->email),
esc_html($sub->first_name),
esc_html($sub->status),
esc_html($sub->subscribed_at)
);
}
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">';
printf('<div class="stat-box"><h2>%d</h2><p>%s</p></div>', esc_html($total), esc_html__('Total', 'bd-simpleemail'));
printf('<div class="stat-box"><h2>%d</h2><p>%s</p></div>', esc_html($subscribed), esc_html__('Active', 'bd-simpleemail'));
printf('<div class="stat-box"><h2>%d</h2><p>%s</p></div>', esc_html($unsubscribed), esc_html__('Unsubscribed', 'bd-simpleemail'));
echo '</div>';
echo '<form method="post">';
wp_nonce_field('bd_export_subscribers');
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) {
printf('<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',
esc_html($sub->id),
esc_html($sub->email),
esc_html($sub->first_name),
esc_html($sub->status),
esc_html($sub->subscribed_at),
$sub->unsubscribed_at ? esc_html($sub->unsubscribed_at) : '-'
);
}
echo '</tbody></table></div>';
}
/**
* New newsletter page
*/
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 = Umbra_Email_Sender::send_newsletter($subject, $content);
if ($result['success']) {
self::log_newsletter($subject, $content, $result['count']);
$success = sprintf(
esc_html__('Newsletter sent to %d subscribers!', 'bd-simpleemail'),
$result['count']
);
if ($publish_blog && $subject) {
self::publish_as_blog_post($subject, $content);
}
} else {
$error = $result['message'];
}
} else {
$error = esc_html__('Content is required', 'bd-simpleemail');
}
}
$settings = Umbra_Simple_Email::get_settings();
$has_ai = !empty($settings['gemini_api_key']);
echo '<div class="wrap">';
echo '<h1>' . esc_html__('New Newsletter', 'bd-simpleemail') . '</h1>';
if ($error) {
printf('<div class="error"><p>%s</p></div>', esc_html($error));
}
if ($success) {
printf('<div class="updated"><p>%s</p></div>', esc_html($success));
}
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"> ';
echo '<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="' . esc_attr__('Describe what the newsletter should contain...', 'bd-simpleemail') . '"></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"> ';
echo '<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>
jQuery(document).ready(function($) {
$("#ai_generate").on("change", function() {
$(".ai-prompt-row").toggle(this.checked);
});
});
</script>';
echo '</div>';
}
/**
* Settings page
*/
public static function settings_page() {
if (isset($_POST['bd_save_email_settings'])) {
check_admin_referer('bd_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', Umbra_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 = Umbra_Simple_Email::get_settings();
$business = Umbra_Simple_Email::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>';
printf('<td><input type="email" name="gmail_address" value="%s" class="regular-text"></td></tr>',
esc_attr($settings['gmail_address'])
);
echo '<tr><th>' . esc_html__('App Password', 'bd-simpleemail') . '</th>';
echo '<td><input type="password" name="gmail_password" class="regular-text" placeholder="' . esc_attr__('Leave blank to keep current', 'bd-simpleemail') . '">';
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>';
printf('<td><input type="text" name="sender_name" value="%s" class="regular-text"></td></tr>',
esc_attr($settings['sender_name'])
);
echo '<tr><th>' . esc_html__('Reply-To', 'bd-simpleemail') . '</th>';
printf('<td><input type="email" name="reply_to" value="%s" class="regular-text"></td></tr>',
esc_attr($settings['reply_to'])
);
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>';
printf('<td><input type="text" name="gemini_api_key" value="%s" class="regular-text">',
esc_attr($settings['gemini_api_key'])
);
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.', 'bd-simpleemail') . '</p>';
echo '<table class="form-table">';
printf('<tr><th>' . esc_html__('Business Name', 'bd-simpleemail') . '</th><td>%s</td></tr>', esc_html($business['name']) ?: '-');
printf('<tr><th>' . esc_html__('Address', 'bd-simpleemail') . '</th><td>%s</td></tr>',
esc_html($business['address_1']) . '<br>' . esc_html($business['address_2']) . '<br>' . esc_html($business['city']) . '<br>' . esc_html($business['country'])
);
printf('<tr><th>' . esc_html__('Phone', 'bd-simpleemail') . '</th><td>%s</td></tr>', esc_html($business['phone']) ?: '-');
echo '</table>';
submit_button(esc_html__('Save Settings', 'bd-simpleemail'), 'primary', 'bd_save_email_settings');
echo '</form></div>';
}
/**
* Generate newsletter with Gemini AI
*
* @param string $subject Newsletter subject.
* @param string $prompt User prompt.
* @return string
*/
private static function generate_newsletter($subject, $prompt) {
$settings = Umbra_Simple_Email::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 '';
}
/**
* Log newsletter send
*
* @param string $subject Subject.
* @param string $content Content.
* @param int $recipient_count Recipient count.
*/
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,
));
}
/**
* Publish newsletter as blog post
*
* @param string $subject Subject.
* @param string $content Content.
* @return int Post ID.
*/
private static function publish_as_blog_post($subject, $content) {
return wp_insert_post(array(
'post_title' => $subject,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'post',
));
}
}