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

339 lines
9.8 KiB
PHP

<?php
// Copyright 2026 Umbra Tools (umbratools.com)
// SPDX-License-Identifier: Apache-2.0
/**
* Shortcodes Manager class
*
* @package Umbra_Bookshelf
*/
if (!defined('ABSPATH')) {
exit;
}
class Umbra_Shortcodes {
/**
* Constructor
*/
public function __construct() {
// Register shortcodes
add_shortcode('sell_ebook', [$this, 'shortcode_sell_ebook']);
add_shortcode('sell_pb', [$this, 'shortcode_sell_pb']);
add_shortcode('sell_hc', [$this, 'shortcode_sell_hc']);
add_shortcode('sell_audio', [$this, 'shortcode_sell_audio']);
add_shortcode('rating', [$this, 'shortcode_rating']);
// Register redirect handler
add_action('template_redirect', [$this, 'handle_redirect']);
}
/**
* Shortcode: [sell_ebook id="123"]
*/
public function shortcode_sell_ebook($atts) {
return $this->render_sell_grid($atts, 'ebook');
}
/**
* Shortcode: [sell_pb id="123"]
*/
public function shortcode_sell_pb($atts) {
return $this->render_sell_grid($atts, 'paperback');
}
/**
* Shortcode: [sell_hc id="123"]
*/
public function shortcode_sell_hc($atts) {
return $this->render_sell_grid($atts, 'hardcover');
}
/**
* Shortcode: [sell_audio id="123"]
*/
public function shortcode_sell_audio($atts) {
return $this->render_sell_grid($atts, 'audio');
}
/**
* Render sell grid for a format
*/
private function render_sell_grid($atts, $format) {
$atts = shortcode_atts([
'id' => 0,
'class' => '',
'columns' => 'auto',
'show_icons' => 'true',
'show_names' => 'true',
'icon_style' => 'simple',
], $atts);
$book_id = absint($atts['id']);
if (!$book_id) {
return '';
}
$links = Umbra_Book_Manager::get_book_retail_links($book_id, $format);
if (empty($links)) {
return '';
}
$class = sanitize_html_class('bd-bookshelf-sell-grid bd-bookshelf-format-' . $format . ' ' . $atts['class']);
$columns = in_array($atts['columns'], ['2', '3', '4']) ? absint($atts['columns']) : '';
$show_icons = $atts['show_icons'] === 'true';
$show_names = $atts['show_names'] === 'true';
$output = '<div class="' . esc_attr($class) . '"';
if ($columns) {
$output .= ' style="grid-template-columns: repeat(' . $columns . ', 1fr);"';
}
$output .= '>';
foreach ($links as $link) {
$output .= '<a href="' . esc_url($link->url) . '" class="bd-bookshelf-sell-item" target="_blank" rel="nofollow noopener">';
if ($show_icons) {
$output .= $this->render_site_icon($link->site_icon, $link->site_name, $atts['icon_style']);
}
if ($show_names) {
$output .= '<span class="bd-bookshelf-site-name">' . esc_html($link->site_name) . '</span>';
}
$output .= '</a>';
}
$output .= '</div>';
return $output;
}
/**
* Render site icon
*/
private function render_site_icon($icon, $name, $style = 'simple') {
if ($style === 'uploaded' && preg_match('/^https?:\/\//', $icon)) {
return '<img src="' . esc_url($icon) . '" alt="' . esc_attr($name) . '" class="bd-bookshelf-site-icon">';
}
// Simple letter icon
$letter = strtoupper(substr($name, 0, 1));
return '<span class="bd-bookshelf-site-icon bd-bookshelf-icon-simple">' . esc_html($letter) . '</span>';
}
/**
* Shortcode: [rating title="Book Title" format="both"]
*/
public function shortcode_rating($atts) {
$atts = shortcode_atts([
'title' => '',
'format' => 'both',
], $atts);
if (empty($atts['title'])) {
return '';
}
$book = Umbra_Book_Manager::get_book_by_title(sanitize_text_field($atts['title']));
if (!$book) {
return '';
}
$rating = Umbra_Book_Manager::get_rating($book->id);
$format = in_array($atts['format'], ['stars', 'numeric', 'both']) ? $atts['format'] : 'both';
$output = '<span class="bd-bookshelf-rating">';
if ($format === 'stars' || $format === 'both') {
$output .= $this->render_stars($rating['goodreads']);
}
if ($format === 'numeric' || $format === 'both') {
$output .= '<span class="bd-bookshelf-rating-number">' . number_format($rating['goodreads'], 1) . '/5</span>';
}
$output .= '</span>';
return $output;
}
/**
* Render star rating with Unicode stars
*/
private function render_stars($rating) {
$full_stars = floor($rating);
$half_star = ($rating - $full_stars) >= 0.5;
$empty_stars = 5 - $full_stars - ($half_star ? 1 : 0);
$output = '<span class="bd-bookshelf-stars">';
for ($i = 0; $i < $full_stars; $i++) {
$output .= '<span class="bd-bookshelf-star full">★</span>';
}
if ($half_star) {
$output .= '<span class="bd-bookshelf-star half">★</span>';
}
for ($i = 0; $i < $empty_stars; $i++) {
$output .= '<span class="bd-bookshelf-star empty">☆</span>';
}
$output .= '</span>';
return $output;
}
/**
* Handle shortcode redirects
*/
public function handle_redirect() {
global $wpdb;
if (is_admin()) {
return;
}
$slug = get_query_var('bd_bookshelf_redirect');
if (empty($slug)) {
return;
}
$table = Umbra_Database::table('shortcodes');
$shortcode = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$table} WHERE slug = %s AND is_active = 1",
$slug
)
);
if (!$shortcode) {
return;
}
// Track click
$this->track_click($shortcode->id);
// Redirect
$type = in_array($shortcode->redirect_type, ['301', '302', '307']) ? $shortcode->redirect_type : '301';
wp_redirect($shortcode->target_url, absint($type));
exit;
}
/**
* Track click for shortcode
*/
private function track_click($shortcode_id) {
global $wpdb;
$table = Umbra_Database::table('shortcode_clicks');
$wpdb->insert($table, [
'shortcode_id' => $shortcode_id,
'ip_address' => $this->get_client_ip(),
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '',
'referer' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw($_SERVER['HTTP_REFERER']) : '',
]);
// Increment click count
$wpdb->query(
$wpdb->prepare(
"UPDATE " . Umbra_Database::table('shortcodes') . " SET click_count = click_count + 1 WHERE id = %d",
$shortcode_id
)
);
}
/**
* Get client IP address
*/
private function get_client_ip() {
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return sanitize_text_field($ip);
}
/**
* Create custom shortcode
*/
public static function create_shortcode($slug, $target_url, $redirect_type = '301', $description = '') {
global $wpdb;
$table = Umbra_Database::table('shortcodes');
$result = $wpdb->insert($table, [
'slug' => sanitize_title($slug),
'target_url' => esc_url_raw($target_url),
'redirect_type' => in_array($redirect_type, ['301', '302', '307']) ? $redirect_type : '301',
'description' => sanitize_text_field($description),
'is_active' => 1,
]);
return $result ? $wpdb->insert_id : false;
}
/**
* Update custom shortcode
*/
public static function update_shortcode($shortcode_id, $data) {
global $wpdb;
$table = Umbra_Database::table('shortcodes');
$update_data = [];
if (isset($data['slug'])) {
$update_data['slug'] = sanitize_title($data['slug']);
}
if (isset($data['target_url'])) {
$update_data['target_url'] = esc_url_raw($data['target_url']);
}
if (isset($data['redirect_type'])) {
$update_data['redirect_type'] = in_array($data['redirect_type'], ['301', '302', '307']) ? $data['redirect_type'] : '301';
}
if (isset($data['description'])) {
$update_data['description'] = sanitize_text_field($data['description']);
}
if (isset($data['is_active'])) {
$update_data['is_active'] = absint($data['is_active']);
}
if (empty($update_data)) {
return false;
}
$result = $wpdb->update(
$table,
$update_data,
['id' => $shortcode_id],
null,
['%d']
);
return $result !== false;
}
/**
* Delete custom shortcode
*/
public static function delete_shortcode($shortcode_id) {
global $wpdb;
$wpdb->delete(Umbra_Database::table('shortcode_clicks'), ['shortcode_id' => $shortcode_id], ['%d']);
return $wpdb->delete(Umbra_Database::table('shortcodes'), ['id' => $shortcode_id], ['%d']) !== false;
}
}