Files
Bookshelf/umbra-bookshelf/includes/books/class-umbra-book-manager.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

481 lines
14 KiB
PHP

<?php
// Copyright 2026 Umbra Tools (umbratools.com)
// SPDX-License-Identifier: Apache-2.0
/**
* Book Manager class
*
* @package Umbra_Bookshelf
*/
if (!defined('ABSPATH')) {
exit;
}
class Umbra_Book_Manager {
/**
* Get all books
*/
public static function get_books($args = []) {
global $wpdb;
$table = Umbra_Database::table('books');
$defaults = [
'number' => 20,
'offset' => 0,
'orderby' => 'title',
'order' => 'ASC',
'search' => '',
];
$args = wp_parse_args($args, $defaults);
$where = '1=1';
$params = [];
if (!empty($args['search'])) {
$where .= ' AND title LIKE %s';
$params[] = '%' . $wpdb->esc_like($args['search']) . '%';
}
$order = strtoupper($args['order']) === 'DESC' ? 'DESC' : 'ASC';
$allowed_orders = ['title', 'created_at', 'updated_at', 'rating_amazon', 'rating_goodreads'];
$orderby = in_array($args['orderby'], $allowed_orders) ? $args['orderby'] : 'title';
$query = "SELECT * FROM {$table} WHERE {$where} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d";
$params[] = $args['number'];
$params[] = $args['offset'];
if (!empty($params)) {
$query = $wpdb->prepare($query, ...$params);
}
$books = $wpdb->get_results($query);
return $books;
}
/**
* Get book by ID
*/
public static function get_book($book_id) {
global $wpdb;
$table = Umbra_Database::table('books');
$book = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE id = %d",
$book_id
)
);
if ($book) {
$book->authors = self::get_book_authors($book_id);
$book->retail_links = self::get_book_retail_links($book_id);
$book->seo = Umbra_SEO::get_book_seo($book_id);
}
return $book;
}
/**
* Get book by title
*/
public static function get_book_by_title($title) {
global $wpdb;
$table = Umbra_Database::table('books');
$book = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE title = %s",
$title
)
);
return $book;
}
/**
* Get book by slug
*/
public static function get_book_by_slug($slug) {
global $wpdb;
$table = Umbra_Database::table('books');
$book = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE slug = %s",
$slug
)
);
if ($book) {
$book->authors = self::get_book_authors($book->id);
$book->retail_links = self::get_book_retail_links($book->id);
$book->seo = Umbra_SEO::get_book_seo($book->id);
}
return $book;
}
/**
* Create new book
*/
public static function create_book($data) {
global $wpdb;
$table = Umbra_Database::table('books');
$slug = sanitize_title($data['slug'] ?? $data['title'] ?? '');
$insert_data = [
'title' => sanitize_text_field($data['title']),
'slug' => $slug,
'description' => wp_kses_post($data['description'] ?? ''),
'cover_image' => esc_url_raw($data['cover_image'] ?? ''),
'isbn_ebook' => self::sanitize_isbn($data['isbn_ebook'] ?? ''),
'isbn_paperback' => self::sanitize_isbn($data['isbn_paperback'] ?? ''),
'isbn_hardcover' => self::sanitize_isbn($data['isbn_hardcover'] ?? ''),
'isbn_audio' => self::sanitize_isbn($data['isbn_audio'] ?? ''),
'asin_ebook' => sanitize_text_field($data['asin_ebook'] ?? ''),
'asin_paperback' => sanitize_text_field($data['asin_paperback'] ?? ''),
'asin_hardcover' => sanitize_text_field($data['asin_hardcover'] ?? ''),
'asin_audio' => sanitize_text_field($data['asin_audio'] ?? ''),
'amazon_asin' => sanitize_text_field($data['amazon_asin'] ?? ''),
'goodreads_id' => sanitize_text_field($data['goodreads_id'] ?? ''),
'series_id' => absint($data['series_id'] ?? 0),
];
// Handle ratings
if (isset($data['rating_amazon'])) {
$insert_data['rating_amazon'] = (float) $data['rating_amazon'];
}
if (isset($data['rating_goodreads'])) {
$insert_data['rating_goodreads'] = (float) $data['rating_goodreads'];
}
$result = $wpdb->insert($table, $insert_data);
if ($result) {
$book_id = $wpdb->insert_id;
// Handle authors - new system uses author_ids
if (!empty($data['author_ids']) && is_array($data['author_ids'])) {
self::update_book_authors_by_id($book_id, $data['author_ids']);
} elseif (!empty($data['authors']) && is_array($data['authors'])) {
// Legacy support
self::update_book_authors($book_id, $data['authors']);
}
return $book_id;
}
return false;
}
/**
* Update book
*/
public static function update_book($book_id, $data) {
global $wpdb;
$table = Umbra_Database::table('books');
$update_data = [];
if (isset($data['title'])) {
$update_data['title'] = sanitize_text_field($data['title']);
}
if (isset($data['description'])) {
$update_data['description'] = wp_kses_post($data['description']);
}
if (isset($data['cover_image'])) {
$update_data['cover_image'] = esc_url_raw($data['cover_image']);
}
if (isset($data['isbn_ebook'])) {
$update_data['isbn_ebook'] = self::sanitize_isbn($data['isbn_ebook']);
}
if (isset($data['isbn_paperback'])) {
$update_data['isbn_paperback'] = self::sanitize_isbn($data['isbn_paperback']);
}
if (isset($data['isbn_hardcover'])) {
$update_data['isbn_hardcover'] = self::sanitize_isbn($data['isbn_hardcover']);
}
if (isset($data['isbn_audio'])) {
$update_data['isbn_audio'] = self::sanitize_isbn($data['isbn_audio']);
}
if (isset($data['asin_ebook'])) {
$update_data['asin_ebook'] = sanitize_text_field($data['asin_ebook']);
}
if (isset($data['asin_paperback'])) {
$update_data['asin_paperback'] = sanitize_text_field($data['asin_paperback']);
}
if (isset($data['asin_hardcover'])) {
$update_data['asin_hardcover'] = sanitize_text_field($data['asin_hardcover']);
}
if (isset($data['asin_audio'])) {
$update_data['asin_audio'] = sanitize_text_field($data['asin_audio']);
}
if (isset($data['amazon_asin'])) {
$update_data['amazon_asin'] = sanitize_text_field($data['amazon_asin']);
}
if (isset($data['goodreads_id'])) {
$update_data['goodreads_id'] = sanitize_text_field($data['goodreads_id']);
}
if (isset($data['series_id'])) {
$update_data['series_id'] = absint($data['series_id']);
}
if (empty($update_data)) {
return false;
}
$result = $wpdb->update(
$table,
$update_data,
['id' => $book_id],
null,
['%d']
);
// Handle authors - new system uses author_ids
if (isset($data['author_ids']) && is_array($data['author_ids'])) {
self::update_book_authors_by_id($book_id, $data['author_ids']);
} elseif (isset($data['authors']) && is_array($data['authors'])) {
// Legacy support
self::update_book_authors($book_id, $data['authors']);
}
return $result !== false;
}
/**
* Delete book
*/
public static function delete_book($book_id) {
global $wpdb;
// Delete related data
$wpdb->delete(Umbra_Database::table('book_authors'), ['book_id' => $book_id], ['%d']);
$wpdb->delete(Umbra_Database::table('retail_links'), ['book_id' => $book_id], ['%d']);
$wpdb->delete(Umbra_Database::table('book_seo'), ['book_id' => $book_id], ['%d']);
// Delete book
$table = Umbra_Database::table('books');
$result = $wpdb->delete($table, ['id' => $book_id], ['%d']);
return $result !== false;
}
/**
* Get book authors
*/
public static function get_book_authors($book_id) {
global $wpdb;
$table = Umbra_Database::table('book_authors');
$authors = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE book_id = %d ORDER BY sort_order ASC",
$book_id
)
);
return $authors;
}
/**
* Update book authors by author IDs
*/
public static function update_book_authors_by_id($book_id, $author_ids) {
global $wpdb;
$table = Umbra_Database::table('book_authors');
$authors_table = Umbra_Database::table('authors');
// Delete existing authors
$wpdb->delete($table, ['book_id' => $book_id], ['%d']);
// Filter out zero values
$author_ids = array_filter(array_map('absint', $author_ids));
// Insert new authors
foreach ($author_ids as $index => $author_id) {
if ($author_id <= 0) continue;
// Get author details
$author = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$authors_table} WHERE id = %d",
$author_id
)
);
if ($author) {
$wpdb->insert($table, [
'book_id' => $book_id,
'author_name' => $author->display_name,
'author_id' => $author_id,
'goodreads_author_id' => $author->goodreads_author_id,
'is_primary' => ($index === 0) ? 1 : 0,
'sort_order' => $index + 1,
]);
}
}
}
/**
* Update book authors (legacy)
*/
public static function update_book_authors($book_id, $authors) {
global $wpdb;
$table = Umbra_Database::table('book_authors');
// Delete existing authors
$wpdb->delete($table, ['book_id' => $book_id], ['%d']);
// Insert new authors
foreach ($authors as $index => $author) {
$wpdb->insert($table, [
'book_id' => $book_id,
'author_name' => sanitize_text_field($author['name']),
'author_id' => absint($author['user_id'] ?? 0),
'goodreads_author_id' => sanitize_text_field($author['goodreads_id'] ?? ''),
'is_primary' => ($index === 0) ? 1 : 0,
'sort_order' => $index + 1,
]);
}
}
/**
* Get book retail links
*/
public static function get_book_retail_links($book_id, $format = '') {
global $wpdb;
$table = Umbra_Database::table('retail_links');
$sites_table = Umbra_Database::table('retail_sites');
$where = 'rl.book_id = %d AND rs.is_active = 1';
$params = [$book_id];
if (!empty($format)) {
$where .= ' AND rl.format = %s';
$params[] = $format;
}
$query = $wpdb->prepare(
"SELECT rl.*, rs.name as site_name, rs.icon as site_icon, rs.affiliate_param, rs.affiliate_code
FROM {$table} rl
LEFT JOIN {$sites_table} rs ON rl.site_id = rs.id
WHERE {$where}
ORDER BY rs.name ASC",
...$params
);
$links = $wpdb->get_results($query);
return $links;
}
/**
* Get books by series
*/
public static function get_books_by_series($series_id) {
global $wpdb;
$table = Umbra_Database::table('books');
$books = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE series_id = %d ORDER BY created_at ASC",
$series_id
)
);
return $books;
}
/**
* Sanitize ISBN
*/
private static function sanitize_isbn($isbn) {
return preg_replace('/[^0-9X]/i', '', $isbn);
}
/**
* Get series list
*/
public static function get_series_list() {
global $wpdb;
$table = Umbra_Database::table('series');
return $wpdb->get_results("SELECT * FROM {$table} ORDER BY name ASC");
}
/**
* Count books
*/
public static function count_books($search = '') {
global $wpdb;
$table = Umbra_Database::table('books');
$where = '1=1';
$params = [];
if (!empty($search)) {
$where .= ' AND title LIKE %s';
$params[] = '%' . $wpdb->esc_like($search) . '%';
}
$query = "SELECT COUNT(*) FROM {$table} WHERE {$where}";
if (!empty($params)) {
$query = $wpdb->prepare($query, ...$params);
}
return $wpdb->get_var($query);
}
/**
* Get rating for book
*/
public static function get_rating($book_id) {
$book = self::get_book($book_id);
if (!$book) {
return [
'amazon' => 0,
'goodreads' => 0,
];
}
return [
'amazon' => (float) $book->rating_amazon,
'goodreads' => (float) $book->rating_goodreads,
];
}
}