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.
297 lines
9.9 KiB
PHP
297 lines
9.9 KiB
PHP
<?php
|
|
// Copyright 2026 Umbra Tools (umbratools.com)
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
/**
|
|
* Amazon Scraper class
|
|
*
|
|
* Fetches author and book data from Amazon
|
|
*
|
|
* @package Umbra_Bookshelf
|
|
*/
|
|
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
class Umbra_Amazon_Scraper {
|
|
|
|
private $user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
|
|
|
/**
|
|
* Search Amazon for a book by title and author
|
|
*
|
|
* @param string $title Book title.
|
|
* @param string $author Author name.
|
|
* @return array List of books found.
|
|
*/
|
|
public function search_books($title, $author = '') {
|
|
$query = $title;
|
|
if ($author) {
|
|
$query .= ' ' . $author;
|
|
}
|
|
|
|
$url = 'https://www.amazon.com/s?k=' . urlencode($query) . '&i=stripbooks';
|
|
|
|
$response = wp_remote_get($url, [
|
|
'timeout' => 30,
|
|
'headers' => [
|
|
'User-Agent' => $this->user_agent,
|
|
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
'Accept-Language' => 'en-US,en;q=0.5',
|
|
],
|
|
]);
|
|
|
|
if (is_wp_error($response)) {
|
|
return ['error' => $response->get_error_message()];
|
|
}
|
|
|
|
$body = wp_remote_retrieve_body($response);
|
|
|
|
return $this->parse_search_results($body);
|
|
}
|
|
|
|
/**
|
|
* Parse Amazon search results
|
|
*/
|
|
private function parse_search_results($html) {
|
|
$books = [];
|
|
|
|
// Match search result items with data-asin
|
|
if (preg_match_all('/<div[^>]*data-asin="([A-Z0-9]{10})"[^>]*class="[^"]*s-result-item[^"]*"[^>]*>(.*?)<\/div>\s*<\/div>\s*<\/div>/si', $html, $matches)) {
|
|
foreach ($matches as $index => $match) {
|
|
$asin = $match[1];
|
|
$item_html = $match[2];
|
|
|
|
$book = $this->parse_search_item($item_html, $asin);
|
|
if ($book) {
|
|
$books[] = $book;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Alternative pattern
|
|
if (empty($books)) {
|
|
if (preg_match_all('/data-asin="([A-Z0-9]{10})"/si', $html, $asin_matches)) {
|
|
foreach ($asin_matches[1] as $asin) {
|
|
// Try to find context around this ASIN
|
|
$pattern = '/data-asin="' . preg_quote($asin) . '"[^>]*>(.*?)(?=data-asin="|$)/si';
|
|
if (preg_match($pattern, $html, $context_match)) {
|
|
$book = $this->parse_search_item($context_match[1], $asin);
|
|
if ($book) {
|
|
$books[] = $book;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return $books;
|
|
}
|
|
|
|
/**
|
|
* Parse a single search result item
|
|
*/
|
|
private function parse_search_item($html, $asin) {
|
|
$book = [
|
|
'asin' => $asin,
|
|
'title' => '',
|
|
'author' => '',
|
|
'format' => '',
|
|
'rating' => 0,
|
|
'ratings_count' => 0,
|
|
'cover_image' => '',
|
|
'url' => 'https://www.amazon.com/dp/' . $asin,
|
|
];
|
|
|
|
// Extract title
|
|
if (preg_match('/<h2[^>]*>.*?<span[^>]*>(.*?)<\/span>/si', $html, $matches)) {
|
|
$book['title'] = trim(strip_tags($matches[1]));
|
|
} elseif (preg_match('/<a[^>]*>.*?<span[^>]*class="[^"]*a-size[^"]*"[^>]*>(.*?)<\/span>/si', $html, $matches)) {
|
|
$book['title'] = trim(strip_tags($matches[1]));
|
|
}
|
|
|
|
// Extract author
|
|
if (preg_match('/<span[^>]*class="[^"]*a-size[^"]*"[^>]*>\s*by\s+<a[^>]*>(.*?)<\/a>/si', $html, $matches)) {
|
|
$book['author'] = trim(strip_tags($matches[1]));
|
|
}
|
|
|
|
// Extract format (Kindle, Paperback, Hardcover, Audio)
|
|
if (preg_match('/(Kindle\s*Edition|Paperback|Hardcover|Audio\s*CD|Audible|MP3\s*CD)/si', $html, $matches)) {
|
|
$book['format'] = trim($matches[1]);
|
|
}
|
|
|
|
// Extract rating
|
|
if (preg_match('/(\d+\.?\d*)\s*out\s*of\s*5\s*stars?/si', $html, $matches)) {
|
|
$book['rating'] = (float) $matches[1];
|
|
}
|
|
|
|
// Extract ratings count
|
|
if (preg_match('/([\d,]+)\s*ratings?/si', $html, $matches)) {
|
|
$book['ratings_count'] = absint(str_replace(',', '', $matches[1]));
|
|
}
|
|
|
|
// Extract cover image
|
|
if (preg_match('/<img[^>]*src="(https:\/\/[^"]*\.jpg)"/si', $html, $matches)) {
|
|
$book['cover_image'] = $matches[1];
|
|
}
|
|
|
|
if (empty($book['title'])) {
|
|
return null;
|
|
}
|
|
|
|
return $book;
|
|
}
|
|
|
|
/**
|
|
* Look up book by ASIN and get full details including ISBN
|
|
*
|
|
* @param string $asin Amazon ASIN.
|
|
* @return array Book details.
|
|
*/
|
|
public function lookup_by_asin($asin) {
|
|
$url = 'https://www.amazon.com/dp/' . $asin;
|
|
|
|
$response = wp_remote_get($url, [
|
|
'timeout' => 30,
|
|
'headers' => [
|
|
'User-Agent' => $this->user_agent,
|
|
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
'Accept-Language' => 'en-US,en;q=0.5',
|
|
],
|
|
]);
|
|
|
|
if (is_wp_error($response)) {
|
|
return ['error' => $response->get_error_message()];
|
|
}
|
|
|
|
$body = wp_remote_retrieve_body($response);
|
|
|
|
return $this->parse_product_page($body, $asin);
|
|
}
|
|
|
|
/**
|
|
* Parse Amazon product page for full book details
|
|
*/
|
|
private function parse_product_page($html, $asin) {
|
|
$book = [
|
|
'asin' => $asin,
|
|
'title' => '',
|
|
'author' => '',
|
|
'isbn' => '',
|
|
'isbn13' => '',
|
|
'rating' => 0,
|
|
'ratings_count' => 0,
|
|
'cover_image' => '',
|
|
'description' => '',
|
|
'formats' => [],
|
|
];
|
|
|
|
// Extract title
|
|
if (preg_match('/<h1[^>]*id="title"[^>]*>(.*?)<\/h1>/si', $html, $matches)) {
|
|
$book['title'] = trim(strip_tags($matches[1]));
|
|
}
|
|
|
|
// Extract author
|
|
if (preg_match('/by\s+<a[^>]*>(.*?)<\/a>/si', $html, $matches)) {
|
|
$book['author'] = trim(strip_tags($matches[1]));
|
|
}
|
|
|
|
// Extract rating
|
|
if (preg_match('/(\d+\.?\d*)\s*out\s*of\s*5\s*stars?/si', $html, $matches)) {
|
|
$book['rating'] = (float) $matches[1];
|
|
}
|
|
|
|
// Extract ratings count
|
|
if (preg_match('/([\d,]+)\s*ratings?/si', $html, $matches)) {
|
|
$book['ratings_count'] = absint(str_replace(',', '', $matches[1]));
|
|
}
|
|
|
|
// Extract cover image
|
|
if (preg_match('/<img[^>]*id="landingImage"[^>]*src="([^"]+)"/si', $html, $matches)) {
|
|
$book['cover_image'] = $matches[1];
|
|
}
|
|
|
|
// Extract ISBN from product details
|
|
if (preg_match('/ISBN-10:\s*(\d{10})/si', $html, $matches)) {
|
|
$book['isbn'] = $matches[1];
|
|
}
|
|
if (preg_match('/ISBN-13:\s*(\d{13})/si', $html, $matches)) {
|
|
$book['isbn13'] = $matches[1];
|
|
}
|
|
|
|
// Extract ASIN
|
|
if (preg_match('/ASIN:\s*([A-Z0-9]{10})/si', $html, $matches)) {
|
|
$book['asin'] = $matches[1];
|
|
}
|
|
|
|
// Extract description
|
|
if (preg_match('/<div[^>]*id="bookDescription_feature_div"[^>]*>.*?<span[^>]*>(.*?)<\/span>/si', $html, $matches)) {
|
|
$book['description'] = trim(strip_tags($matches[1]));
|
|
}
|
|
|
|
// Look for other format links (Kindle, Paperback, Hardcover)
|
|
if (preg_match_all('/<li[^>]*>.*?<a[^>]*href="\/dp\/([A-Z0-9]{10})"[^>]*>.*?<span[^>]*>(.*?)<\/span>/si', $html, $matches)) {
|
|
foreach ($matches[1] as $index => $format_asin) {
|
|
$format_name = trim(strip_tags($matches[2][$index]));
|
|
if ($format_asin !== $asin && !empty($format_name)) {
|
|
$book['formats'][] = [
|
|
'asin' => $format_asin,
|
|
'format' => $format_name,
|
|
'url' => 'https://www.amazon.com/dp/' . $format_asin,
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
return $book;
|
|
}
|
|
|
|
/**
|
|
* Get all format ASINs for a book by searching
|
|
*
|
|
* @param string $title Book title.
|
|
* @param string $author Author name.
|
|
* @return array Format => ASIN mapping.
|
|
*/
|
|
public function get_format_asins($title, $author = '') {
|
|
$formats = [
|
|
'kindle' => '',
|
|
'paperback' => '',
|
|
'hardcover' => '',
|
|
'audio' => '',
|
|
];
|
|
|
|
// Search for the book
|
|
$results = $this->search_books($title, $author);
|
|
|
|
if (isset($results['error']) || empty($results)) {
|
|
return $formats;
|
|
}
|
|
|
|
// Match results to formats
|
|
foreach ($results as $book) {
|
|
$book_title = strtolower($book['title'] ?? '');
|
|
$book_format = strtolower($book['format'] ?? '');
|
|
|
|
// Check if this is the same book (title match)
|
|
similar_text(strtolower($title), $book_title, $percent);
|
|
if ($percent < 60) {
|
|
continue;
|
|
}
|
|
|
|
if (strpos($book_format, 'kindle') !== false || strpos($book_format, 'ebook') !== false) {
|
|
$formats['kindle'] = $book['asin'];
|
|
} elseif (strpos($book_format, 'paperback') !== false) {
|
|
$formats['paperback'] = $book['asin'];
|
|
} elseif (strpos($book_format, 'hardcover') !== false) {
|
|
$formats['hardcover'] = $book['asin'];
|
|
} elseif (strpos($book_format, 'audio') !== false || strpos($book_format, 'audible') !== false) {
|
|
$formats['audio'] = $book['asin'];
|
|
}
|
|
}
|
|
|
|
return $formats;
|
|
}
|
|
}
|