Files
Umbra-Bookshelf/umbra-bookshelf/includes/email/class-umbra-simple-email.php
bdm 0bd78e587a Resolve the known issues; switch licence to GPL
Closes the three problems that blocked the consolidation and records the rest
as tasks.

Licence: GPLv2 or later (WordPress.org compatible)

  LICENSE is now the full GPLv2 text and NOTICE is gone (it was Apache
  specific). All 101 SPDX headers read GPL-2.0-or-later and every shipped
  header says "GPLv2 or later".

  This also fixes an inconsistency that predated the consolidation: the theme's
  style.css declared GPLv2 while its PHP files carried Apache headers.

  Old/ and archive/pre-umbra-releases/ keep their original Apache headers on
  purpose -- they are frozen snapshots, not shipped code.

Schema: the catalogue schema is canonical for bd_books and bd_series

  Adds Umbra_Schema_Migration. The catalogue and library modules previously
  both created those two tables with different columns, so whichever plugin
  activated first won and the other read and wrote against the wrong shape.

  The migration detects a library-shaped table, RENAMES it aside (never drops
  it), creates the canonical table and copies rows across:

    - book IDs preserved, keeping bd_book_meta, bd_reviews, bd_ratings and
      bd_review_shortlinks valid
    - title/slug/description resolved from the linked post
    - the library's single isbn/asin land on the ebook columns; amazon_asin is
      also set so existing product links keep working
    - series migrated first so books.series_id still resolves
    - post linkage rewritten as _bd_bookshelf_book_id (preserved meta key)
    - publish_date kept as _bd_bookshelf_publish_date (no catalogue column)
    - bd_ratings goodreads/amazon folded into rating_goodreads/rating_amazon
    - rows whose post is gone are skipped with a log line, not turned into
      unusable books
    - duplicate slugs de-duplicated, since catalogue slug is UNIQUE

  It runs before dbDelta, and on admin_init as well as activation, because
  plugin updates do not re-run activation hooks. Ordering matters: dbDelta adds
  columns but never drops them, so pointed at a library-shaped table it would
  graft on catalogue columns and leave a table satisfying neither schema.

  Umbra_Bookshelf_Helper_Install no longer creates bd_books or bd_series.

Scraping: Goodreads only, one implementation

  There were three Goodreads implementations and two Amazon ones; both library
  "scrapers" were empty stubs attached to cron events that fired on schedule to
  do nothing, and both real scraper classes were never called at all.

  Umbra_Amazon_Scraper is deleted and the duplicate HTML parsing is gone from
  Umbra_Rating_Sync, which now delegates to Umbra_Goodreads_Scraper. The two
  library stubs and their cron registrations are removed. One schedule
  survives: bd_bookshelf_sync_ratings, every 12 hours.

  The rating_amazon column is retained (it holds data and is populated during
  migration) and Amazon retail links are unaffected.

  A new rating fetch failure keeps the last known value instead of writing zero.
  The admin ratings notice no longer warns about Amazon scraping.

Umbra_SEO is now instantiated

  It registers its hooks from a constructor and the bootstrap never constructed
  it, so the class was dead code and no SEO output was produced. Its meta, Open
  Graph, Twitter card and sitemap hooks now attach. Completing SEO for generated
  book detail pages is docs/TASKS.md #2.

Assets that 404'd

  - assets/images/default-cover.png now holds a real 512x815 cover
    (WorkingTitleCover_512x815.png). The helper returned this path but the
    repository contained no images at all.
  - email/assets/js/admin.js is committed as an empty placeholder. It was
    enqueued on every email admin page but had never been committed.

Tests

  - tests/schema_migration_test.php: 42 checks against a real database, driven
    through the sqlite3 CLI on a throwaway file. Covers shape detection, row
    mapping, ID preservation, orphan handling, rating folding, idempotency and
    slug collisions.
  - tests/run_all.sh runs every suite.
  - The declared version is now checked against the plugin header rather than a
    literal, so a version bump cannot silently break the suite.

Docs

  - KNOWN-ISSUES.md rewritten: three resolved, three remaining.
  - TASKS.md added: email admin behaviour, book detail page SEO, batching the
    rating sync, reclaiming legacy tables, reconciling the two book models,
    retiring the Old/ archive.
  - SPEC and ARCHITECTURE updated for schema ownership, the migration ordering
    constraint, and the single scraper.

Version 1.1.0.
2026-10-22 09:47:00 -07:00

366 lines
12 KiB
PHP

<?php
// Copyright 2026 Umbra Tools (umbratools.com)
// SPDX-License-Identifier: GPL-2.0-or-later
/**
* Main SimpleEmail Plugin Class
*
* @package Umbra_Simple_Email
*/
if (!defined('ABSPATH')) {
exit;
}
class Umbra_Simple_Email {
private static $instance = null;
/**
* Get instance
*
* @return Umbra_Simple_Email
*/
public static function instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
$this->init_hooks();
}
/**
* Initialize hooks
*/
private function init_hooks() {
add_action('admin_menu', array($this, 'add_menu_pages'));
add_action('admin_post_bdm_signup_submit', array($this, 'handle_signup'));
add_action('admin_post_bdm_unsubscribe_submit', array($this, 'handle_unsubscribe'));
add_action('wp_ajax_bdm_ajax_signup', array($this, 'ajax_signup'));
add_action('wp_ajax_nopriv_bdm_ajax_signup', array($this, 'ajax_signup'));
add_shortcode('bdm_signup', array($this, 'signup_shortcode'));
}
/**
* Add admin menu pages
*/
public function add_menu_pages() {
// The top-level "Umbra Bookshelf" menu is registered once by the plugin
// bootstrap (Umbra_Bookshelf::register_admin_menu); this module only
// contributes submenus beneath it.
add_submenu_page(
'umbra-bookshelf',
esc_html__('Subscribers', 'umbra-bookshelf'),
esc_html__('Subscribers', 'umbra-bookshelf'),
'manage_options',
'umbra-bookshelf-subscribers',
array('Umbra_Simple_Email_Admin', 'subscribers_page')
);
add_submenu_page(
'umbra-bookshelf',
esc_html__('New Newsletter', 'umbra-bookshelf'),
esc_html__('New Newsletter', 'umbra-bookshelf'),
'manage_options',
'umbra-bookshelf-newsletter',
array('Umbra_Simple_Email_Admin', 'new_newsletter_page')
);
add_submenu_page(
'umbra-bookshelf',
esc_html__('Email Settings', 'umbra-bookshelf'),
esc_html__('Email Settings', 'umbra-bookshelf'),
'manage_options',
'umbra-bookshelf-email-settings',
array('Umbra_Simple_Email_Admin', 'settings_page')
);
}
/**
* Handle signup form submission
*/
public function handle_signup() {
if (!isset($_POST['bdm_signup_nonce']) || !wp_verify_nonce($_POST['bdm_signup_nonce'], 'bdm_signup')) {
wp_safe_redirect(add_query_arg('error', 'invalid', home_url('/signup/')));
exit;
}
$email = sanitize_email($_POST['email']);
if (!$email) {
wp_safe_redirect(add_query_arg('error', 'invalid', home_url('/signup/')));
exit;
}
$first_name = sanitize_text_field($_POST['first_name'] ?? '');
$result = self::subscribe($email, $first_name);
if ($result) {
wp_safe_redirect(add_query_arg('success', '1', home_url('/signup/')));
} else {
wp_safe_redirect(add_query_arg('error', 'exists', home_url('/signup/')));
}
exit;
}
/**
* Handle unsubscribe form submission
*/
public function handle_unsubscribe() {
if (!isset($_POST['bdm_unsubscribe_nonce']) || !wp_verify_nonce($_POST['bdm_unsubscribe_nonce'], 'bdm_unsubscribe')) {
wp_safe_redirect(add_query_arg('error', 'invalid', home_url('/unsubscribe/')));
exit;
}
$email = sanitize_email($_POST['email']);
if ($email) {
self::unsubscribe($email);
}
wp_safe_redirect(add_query_arg('success', '1', home_url('/unsubscribe/')));
exit;
}
/**
* Handle AJAX signup
*/
public function ajax_signup() {
check_ajax_referer('bdm_ajax_signup');
$email = sanitize_email($_POST['email'] ?? '');
if (!$email || !is_email($email)) {
wp_send_json_error(array('message' => esc_html__('Invalid email address', 'umbra-bookshelf')));
}
$first_name = sanitize_text_field($_POST['first_name'] ?? '');
$opt_in = isset($_POST['opt_in']) && $_POST['opt_in'];
if (!$opt_in) {
wp_send_json_error(array('message' => esc_html__('Please confirm your subscription', 'umbra-bookshelf')));
}
$result = self::subscribe($email, $first_name);
if ($result) {
wp_send_json_success(array('message' => esc_html__('Thank you for subscribing!', 'umbra-bookshelf')));
} else {
wp_send_json_error(array('message' => esc_html__('You are already subscribed or cannot be added', 'umbra-bookshelf')));
}
}
/**
* Subscribe a new email
*
* @param string $email Email address.
* @param string $first_name First name.
* @return bool
*/
public static function subscribe($email, $first_name = '') {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
$exists = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM {$table_name} WHERE email = %s",
$email
));
if ($exists) {
return false;
}
$result = $wpdb->insert($table_name, array(
'email' => $email,
'first_name' => $first_name,
'status' => 'subscribed',
'subscribed_at' => current_time('mysql'),
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
));
return $result !== false;
}
/**
* Unsubscribe an email
*
* @param string $email Email address.
* @return bool
*/
public static function unsubscribe($email) {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
return $wpdb->update(
$table_name,
array(
'status' => 'unsubscribed',
'unsubscribed_at' => current_time('mysql'),
),
array('email' => $email)
) !== false;
}
/**
* Get subscribers
*
* @param string $status Status filter.
* @return array
*/
public static function get_subscribers($status = 'subscribed') {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
return $wpdb->get_results($wpdb->prepare(
"SELECT * FROM {$table_name} WHERE status = %s ORDER BY subscribed_at DESC",
$status
));
}
/**
* Get subscriber count
*
* @param string $status Status filter.
* @return int
*/
public static function get_subscriber_count($status = 'subscribed') {
global $wpdb;
$table_name = $wpdb->prefix . 'bd_subscribers';
return (int) $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM {$table_name} WHERE status = %s",
$status
));
}
/**
* Get plugin settings
*
* @return array
*/
public static function get_settings() {
return array(
'gmail_address' => get_option('bdm_gmail_address', ''),
'gmail_password' => get_option('bdm_gmail_password', ''),
'sender_name' => get_option('bdm_sender_name', get_bloginfo('name')),
'reply_to' => get_option('bdm_reply_to', ''),
'gemini_api_key'=> get_option('bdm_gemini_api_key', ''),
);
}
/**
* Get business info from theme options
*
* @return array
*/
public static function get_business_info() {
$options = get_option('bdm_theme_options', array());
return array(
'name' => $options['business_name'] ?? '',
'address_1' => $options['business_address_1'] ?? '',
'address_2' => $options['business_address_2'] ?? '',
'city' => $options['business_city'] ?? '',
'country' => $options['business_country'] ?? '',
'phone' => $options['business_phone'] ?? '',
);
}
/**
* Generate unsubscribe token
*
* @param string $email Email address.
* @return string
*/
public static function generate_unsubscribe_token($email) {
$secret_key = defined('AUTH_KEY') ? AUTH_KEY : 'bdm_unsubscribe_secret';
return hash_hmac('sha256', $email, $secret_key);
}
/**
* Verify unsubscribe token
*
* @param string $email Email address.
* @param string $token Token to verify.
* @return bool
*/
public static function verify_unsubscribe_token($email, $token) {
return hash_equals(self::generate_unsubscribe_token($email), $token);
}
/**
* Signup shortcode
*
* @param array $atts Shortcode attributes.
* @return string
*/
public function signup_shortcode($atts = array()) {
$atts = shortcode_atts(array(), $atts);
ob_start();
?>
<form id="bdm-signup-form" class="bdm-signup-form">
<?php wp_nonce_field('bdm_ajax_signup', 'bdm_signup_nonce'); ?>
<p class="form-field">
<label for="bdm-email"><?php esc_html_e('Email Address', 'umbra-bookshelf'); ?> *</label>
<input type="email" id="bdm-email" name="email" required>
</p>
<p class="form-field">
<label for="bdm-first-name"><?php esc_html_e('First Name', 'umbra-bookshelf'); ?></label>
<input type="text" id="bdm-first-name" name="first_name">
</p>
<p class="form-field checkbox-field">
<input type="checkbox" id="bdm-opt-in" name="opt_in" value="1" required>
<label for="bdm-opt-in"><?php esc_html_e('I agree to receive email updates.', 'umbra-bookshelf'); ?></label>
</p>
<p class="form-submit">
<button type="submit" class="submit-btn"><?php esc_html_e('Subscribe', 'umbra-bookshelf'); ?></button>
</p>
<div class="form-response" style="display:none;"></div>
</form>
<script>
(function() {
'use strict';
var form = document.getElementById('bdm-signup-form');
if (!form) return;
form.addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(form);
formData.append('action', 'bdm_ajax_signup');
var response = form.querySelector('.form-response');
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: formData,
credentials: 'same-origin'
})
.then(function(res) { return res.json(); })
.then(function(data) {
if (data.success) {
response.innerHTML = '<p class="success">' + data.data.message + '</p>';
form.reset();
} else {
response.innerHTML = '<p class="error">' + data.data.message + '</p>';
}
response.style.display = 'block';
})
.catch(function() {
response.innerHTML = '<p class="error"><?php esc_html_e('An error occurred. Please try again.', 'umbra-bookshelf'); ?></p>';
response.style.display = 'block';
});
});
})();
</script>
<?php
return ob_get_clean();
}
}