Initial commit: AutoBlogger v0.1.0
WordPress plugin that auto-researches topics from Reddit, generates SEO-optimized articles via OpenRouter LLMs, runs them through a chief editor agent, and publishes on a daily schedule. Includes: - Full generation pipeline (collect → analyze → score → generate → review → publish) - Cost tracking and budget enforcement - Admin UI: settings, review queue, metrics, activity log - CI/CD pipeline (GitHub Actions → WordPress REST deploy) - Unit test suite (PHPUnit + Brain Monkey) - Structured logging with configurable verbosity Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
96
includes/admin/class-admin-notices.php
Executable file
96
includes/admin/class-admin-notices.php
Executable file
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Displays admin notices for onboarding, errors, and budget warnings.
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() on `admin_notices`.
|
||||
* Dependencies: Autoblogger_Cost_Tracker (for budget warnings).
|
||||
*
|
||||
* @see class-autoblogger.php — Registers the hook.
|
||||
*/
|
||||
class Autoblogger_Admin_Notices {
|
||||
|
||||
/**
|
||||
* Display relevant admin notices.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_display_notices(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->check_api_key_notice();
|
||||
$this->check_budget_notice();
|
||||
$this->check_subreddit_notice();
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a notice if the OpenRouter API key is not configured.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function check_api_key_notice(): void {
|
||||
$api_key = get_option( 'autoblogger_openrouter_api_key', '' );
|
||||
if ( '' !== $api_key ) {
|
||||
return;
|
||||
}
|
||||
|
||||
printf(
|
||||
'<div class="notice notice-warning is-dismissible"><p>%s <a href="%s">%s</a></p></div>',
|
||||
esc_html__( 'AutoBlogger: OpenRouter API key is not configured. Content generation is disabled.', 'autoblogger' ),
|
||||
esc_url( admin_url( 'admin.php?page=autoblogger-settings' ) ),
|
||||
esc_html__( 'Configure now', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a warning if monthly budget is approaching or exceeded.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function check_budget_notice(): void {
|
||||
$cost_tracker = new Autoblogger_Cost_Tracker();
|
||||
$utilization = $cost_tracker->get_budget_utilization();
|
||||
|
||||
if ( $utilization >= 100.0 ) {
|
||||
printf(
|
||||
'<div class="notice notice-error"><p>%s</p></div>',
|
||||
esc_html__( 'AutoBlogger: Monthly API budget EXCEEDED. Content generation is paused until next month or budget increase.', 'autoblogger' )
|
||||
);
|
||||
} elseif ( $utilization >= 80.0 ) {
|
||||
printf(
|
||||
'<div class="notice notice-warning"><p>%s</p></div>',
|
||||
esc_html( sprintf(
|
||||
/* translators: %s: budget utilization percentage */
|
||||
__( 'AutoBlogger: Monthly API budget is at %.0f%%. Consider increasing the budget or reducing daily article count.', 'autoblogger' ),
|
||||
$utilization
|
||||
) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a notice if no subreddits are configured.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function check_subreddit_notice(): void {
|
||||
$subreddits = json_decode( get_option( 'autoblogger_target_subreddits', '[]' ), true );
|
||||
if ( ! empty( $subreddits ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only show on our settings page.
|
||||
$screen = get_current_screen();
|
||||
if ( ! $screen || 'toplevel_page_autoblogger-settings' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
printf(
|
||||
'<div class="notice notice-info is-dismissible"><p>%s</p></div>',
|
||||
esc_html__( 'AutoBlogger: No subreddits configured. Add target subreddits in Source Configuration to start collecting data.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
}
|
||||
207
includes/admin/class-admin-page.php
Executable file
207
includes/admin/class-admin-page.php
Executable file
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Registers and renders the main AutoBlogger settings page in wp-admin.
|
||||
*
|
||||
* Uses the WordPress Settings API for option registration, sanitization, and rendering.
|
||||
* Settings are defined as a declarative array — adding a new setting is one array entry.
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() registers menu and settings hooks.
|
||||
* Dependencies: Autoblogger_Encryption (for API key storage), Autoblogger_Settings_Fields.
|
||||
*
|
||||
* @see class-autoblogger.php — Registers hooks that call this class.
|
||||
* @see class-settings-fields.php — Defines all settings fields and sections.
|
||||
* @see CONVENTIONS.md — "How To: Add a New Admin Setting".
|
||||
*/
|
||||
class Autoblogger_Admin_Page {
|
||||
|
||||
private const PAGE_SLUG = 'autoblogger-settings';
|
||||
private const OPTION_GROUP = 'autoblogger_settings_group';
|
||||
|
||||
/** Register the top-level AutoBlogger menu item. */
|
||||
public function on_register_menu(): void {
|
||||
add_menu_page(
|
||||
__( 'AutoBlogger', 'autoblogger' ),
|
||||
__( 'AutoBlogger', 'autoblogger' ),
|
||||
'manage_options',
|
||||
self::PAGE_SLUG,
|
||||
[ $this, 'render_page' ],
|
||||
'dashicons-edit-page',
|
||||
30
|
||||
);
|
||||
}
|
||||
|
||||
/** Register all settings with the WordPress Settings API. */
|
||||
public function on_register_settings(): void {
|
||||
$sections = Autoblogger_Settings_Fields::get_sections();
|
||||
$fields = Autoblogger_Settings_Fields::get_fields();
|
||||
|
||||
foreach ( $sections as $section_id => $section ) {
|
||||
add_settings_section( $section_id, $section['title'], '__return_empty_string', self::PAGE_SLUG );
|
||||
}
|
||||
|
||||
foreach ( $fields as $field ) {
|
||||
$section = $field['section'] ?? 'autoblogger_api';
|
||||
register_setting( self::OPTION_GROUP, $field['id'], [
|
||||
'type' => $field['wp_type'] ?? 'string',
|
||||
'sanitize_callback' => [ $this, 'sanitize_field' ],
|
||||
'default' => $field['default'] ?? '',
|
||||
] );
|
||||
add_settings_field( $field['id'], $field['label'], [ $this, 'render_field' ], self::PAGE_SLUG, $section, $field );
|
||||
}
|
||||
}
|
||||
|
||||
/** Enqueue admin CSS and JS on all AutoBlogger admin pages. */
|
||||
public function on_enqueue_assets( string $hook_suffix ): void {
|
||||
$pages = [
|
||||
'toplevel_page_' . self::PAGE_SLUG,
|
||||
'autoblogger_page_autoblogger-metrics',
|
||||
'autoblogger_page_autoblogger-review-queue',
|
||||
'autoblogger_page_autoblogger-logs',
|
||||
];
|
||||
if ( ! in_array( $hook_suffix, $pages, true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_enqueue_style( 'autoblogger-admin', AUTOBLOGGER_PLUGIN_URL . 'assets/css/admin.css', [], AUTOBLOGGER_VERSION );
|
||||
wp_enqueue_script( 'autoblogger-admin', AUTOBLOGGER_PLUGIN_URL . 'assets/js/admin.js', [ 'jquery' ], AUTOBLOGGER_VERSION, true );
|
||||
|
||||
wp_localize_script( 'autoblogger-admin', 'autobloggerAdmin', [
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'generateNonce' => wp_create_nonce( 'autoblogger_generate_now' ),
|
||||
'testNonce' => wp_create_nonce( 'autoblogger_test_connection' ),
|
||||
'reviewNonce' => wp_create_nonce( 'autoblogger_review_queue' ),
|
||||
'generatingText' => __( 'Generating...', 'autoblogger' ),
|
||||
'generateText' => __( 'Generate Now', 'autoblogger' ),
|
||||
'testingText' => __( 'Testing...', 'autoblogger' ),
|
||||
'testText' => __( 'Test Connections', 'autoblogger' ),
|
||||
] );
|
||||
}
|
||||
|
||||
/** Render the settings page (delegates to template). */
|
||||
public function render_page(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
$sections = Autoblogger_Settings_Fields::get_sections();
|
||||
$fields = Autoblogger_Settings_Fields::get_fields();
|
||||
include AUTOBLOGGER_PLUGIN_DIR . 'templates/admin/settings-page.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a single settings field based on its type.
|
||||
*
|
||||
* @param array<string, mixed> $args Field definition.
|
||||
*/
|
||||
public function render_field( array $args ): void {
|
||||
$id = esc_attr( $args['id'] );
|
||||
$type = $args['type'] ?? 'text';
|
||||
$default = $args['default'] ?? '';
|
||||
$desc = $args['description'] ?? '';
|
||||
$value = get_option( $args['id'], $default );
|
||||
|
||||
if ( 'password' === $type && '' !== $value ) {
|
||||
$decrypted = Autoblogger_Encryption::decrypt( $value );
|
||||
$value = '' !== $decrypted ? '••••••••' : '';
|
||||
}
|
||||
|
||||
switch ( $type ) {
|
||||
case 'text':
|
||||
case 'number':
|
||||
case 'url':
|
||||
case 'time':
|
||||
$attrs = '';
|
||||
if ( isset( $args['min'] ) ) { $attrs .= ' min="' . esc_attr( (string) $args['min'] ) . '"'; }
|
||||
if ( isset( $args['max'] ) ) { $attrs .= ' max="' . esc_attr( (string) $args['max'] ) . '"'; }
|
||||
if ( isset( $args['step'] ) ) { $attrs .= ' step="' . esc_attr( (string) $args['step'] ) . '"'; }
|
||||
printf( '<input type="%s" id="%s" name="%s" value="%s" class="ab-input" %s />', esc_attr( $type ), $id, $id, esc_attr( (string) $value ), $attrs );
|
||||
break;
|
||||
|
||||
case 'password':
|
||||
printf( '<input type="password" id="%s" name="%s" value="" class="ab-input" placeholder="%s" autocomplete="off" />',
|
||||
$id, $id, '' !== $value ? esc_attr__( 'Saved (enter new value to change)', 'autoblogger' ) : '' );
|
||||
break;
|
||||
|
||||
case 'textarea':
|
||||
printf( '<textarea id="%s" name="%s" rows="3" class="ab-textarea">%s</textarea>', $id, $id, esc_textarea( (string) $value ) );
|
||||
break;
|
||||
|
||||
case 'select':
|
||||
printf( '<select id="%s" name="%s" class="ab-select">', $id, $id );
|
||||
foreach ( ( $args['options'] ?? [] ) as $v => $label ) {
|
||||
printf( '<option value="%s"%s>%s</option>', esc_attr( (string) $v ), selected( $value, (string) $v, false ), esc_html( $label ) );
|
||||
}
|
||||
echo '</select>';
|
||||
break;
|
||||
|
||||
case 'toggle':
|
||||
$checked = in_array( $value, [ '1', 'yes', true ], true );
|
||||
printf( '<label class="ab-toggle"><input type="hidden" name="%s" value="0" /><input type="checkbox" name="%s" value="1" %s /><span class="ab-toggle-slider"></span></label>',
|
||||
$id, $id, checked( $checked, true, false ) );
|
||||
break;
|
||||
|
||||
case 'checkboxes':
|
||||
$current = json_decode( (string) $value, true ) ?: [];
|
||||
foreach ( ( $args['options'] ?? [] ) as $v => $label ) {
|
||||
$is_checked = in_array( $v, $current, true );
|
||||
$disabled = strpos( $label, 'coming soon' ) !== false ? ' disabled' : '';
|
||||
printf( '<label class="ab-checkbox-label"><input type="checkbox" name="%s[]" value="%s" %s%s /> %s</label>',
|
||||
$id, esc_attr( $v ), checked( $is_checked, true, false ), $disabled, esc_html( $label ) );
|
||||
}
|
||||
break;
|
||||
|
||||
case 'author_select':
|
||||
wp_dropdown_users( [ 'name' => $id, 'id' => $id, 'selected' => absint( $value ), 'show_option_none' => __( '— Auto (first admin) —', 'autoblogger' ), 'option_none_value' => '0', 'class' => 'ab-select' ] );
|
||||
break;
|
||||
|
||||
case 'category_select':
|
||||
wp_dropdown_categories( [ 'name' => $id, 'id' => $id, 'selected' => absint( $value ), 'show_option_none' => __( '— Auto-assign by type —', 'autoblogger' ), 'option_none_value' => '0', 'class' => 'ab-select', 'hide_empty' => false ] );
|
||||
break;
|
||||
}
|
||||
|
||||
if ( isset( $args['badge'] ) ) {
|
||||
printf( ' <span class="ab-badge">%s</span>', esc_html( $args['badge'] ) );
|
||||
}
|
||||
if ( '' !== $desc ) {
|
||||
printf( '<p class="ab-field-desc">%s</p>', esc_html( $desc ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a settings field value.
|
||||
*
|
||||
* @param mixed $value The submitted value.
|
||||
* @return mixed Sanitized value.
|
||||
*/
|
||||
public function sanitize_field( $value ) {
|
||||
$option_name = '';
|
||||
$filter = current_filter();
|
||||
if ( 0 === strpos( $filter, 'sanitize_option_' ) ) {
|
||||
$option_name = substr( $filter, strlen( 'sanitize_option_' ) );
|
||||
}
|
||||
|
||||
$encrypted = [ 'autoblogger_openrouter_api_key', 'autoblogger_reddit_client_secret', 'autoblogger_ga4_credentials_json' ];
|
||||
if ( in_array( $option_name, $encrypted, true ) ) {
|
||||
if ( '' === $value ) { return get_option( $option_name, '' ); }
|
||||
return Autoblogger_Encryption::encrypt( sanitize_text_field( $value ) );
|
||||
}
|
||||
|
||||
$json_fields = [ 'autoblogger_target_subreddits', 'autoblogger_topic_exclusions', 'autoblogger_enabled_sources' ];
|
||||
if ( in_array( $option_name, $json_fields, true ) ) {
|
||||
if ( is_array( $value ) ) { return wp_json_encode( array_values( array_map( 'sanitize_text_field', $value ) ) ); }
|
||||
if ( is_string( $value ) && '[' !== substr( trim( $value ), 0, 1 ) ) {
|
||||
$items = array_filter( array_map( 'trim', explode( ',', $value ) ) );
|
||||
return wp_json_encode( array_values( $items ) );
|
||||
}
|
||||
return sanitize_text_field( $value );
|
||||
}
|
||||
|
||||
$numeric = [ 'autoblogger_daily_article_target', 'autoblogger_monthly_budget_usd', 'autoblogger_min_word_count', 'autoblogger_max_word_count', 'autoblogger_default_author', 'autoblogger_default_category' ];
|
||||
if ( in_array( $option_name, $numeric, true ) ) {
|
||||
return is_numeric( $value ) ? $value : 0;
|
||||
}
|
||||
|
||||
return sanitize_text_field( (string) $value );
|
||||
}
|
||||
}
|
||||
67
includes/admin/class-dashboard-widget.php
Executable file
67
includes/admin/class-dashboard-widget.php
Executable file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* WordPress Dashboard widget showing AutoBlogger generation status at a glance.
|
||||
*
|
||||
* Displays: last generation time, articles generated today, monthly cost,
|
||||
* and budget utilization.
|
||||
*
|
||||
* Triggered by: Could be registered via wp_dashboard_setup hook.
|
||||
* Dependencies: Autoblogger_Cost_Tracker.
|
||||
*
|
||||
* @see class-autoblogger.php — Can register this on wp_dashboard_setup.
|
||||
*/
|
||||
class Autoblogger_Dashboard_Widget {
|
||||
|
||||
/**
|
||||
* Register the dashboard widget.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_register_widget(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_add_dashboard_widget(
|
||||
'autoblogger_status',
|
||||
__( 'AutoBlogger Status', 'autoblogger' ),
|
||||
[ $this, 'render_widget' ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the widget content.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_widget(): void {
|
||||
$cost_tracker = new Autoblogger_Cost_Tracker();
|
||||
$monthly_spend = $cost_tracker->get_monthly_spend();
|
||||
$budget = (float) get_option( 'autoblogger_monthly_budget_usd', 50.00 );
|
||||
$utilization = $cost_tracker->get_budget_utilization();
|
||||
|
||||
$next_run = wp_next_scheduled( 'autoblogger_daily_generation' );
|
||||
|
||||
printf( '<p><strong>%s</strong> $%.2f / $%.2f (%.0f%%)</p>',
|
||||
esc_html__( 'Monthly Spend:', 'autoblogger' ),
|
||||
$monthly_spend,
|
||||
$budget,
|
||||
$utilization
|
||||
);
|
||||
|
||||
if ( false !== $next_run ) {
|
||||
printf( '<p><strong>%s</strong> %s</p>',
|
||||
esc_html__( 'Next Generation:', 'autoblogger' ),
|
||||
esc_html( wp_date( 'M j, Y g:i A', $next_run ) )
|
||||
);
|
||||
}
|
||||
|
||||
printf(
|
||||
'<p><a href="%s" class="button button-secondary">%s</a></p>',
|
||||
esc_url( admin_url( 'admin.php?page=autoblogger-metrics' ) ),
|
||||
esc_html__( 'View Full Metrics', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
}
|
||||
84
includes/admin/class-log-viewer.php
Executable file
84
includes/admin/class-log-viewer.php
Executable file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Admin page displaying structured application log entries.
|
||||
*
|
||||
* Provides level filtering (error/warning/info/debug), text search,
|
||||
* pagination, and a one-click "Clear Old Logs" action. Reads from the
|
||||
* ab_event_log table via Autoblogger_Logger::query().
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() on `admin_menu`.
|
||||
* Dependencies: Autoblogger_Logger.
|
||||
*
|
||||
* @see core/class-logger.php — Writes log entries and provides query().
|
||||
* @see templates/admin/log-viewer.php — Renders the HTML.
|
||||
* @see class-autoblogger.php — Registers the AJAX clear action.
|
||||
*/
|
||||
class Autoblogger_Log_Viewer {
|
||||
|
||||
/**
|
||||
* Register the log viewer submenu page under AutoBlogger.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_register_menu(): void {
|
||||
add_submenu_page(
|
||||
'autoblogger-settings',
|
||||
__( 'Activity Log', 'autoblogger' ),
|
||||
__( 'Activity Log', 'autoblogger' ),
|
||||
'manage_options',
|
||||
'autoblogger-logs',
|
||||
[ $this, 'render_page' ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the log viewer page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_page(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$level = isset( $_GET['level'] ) ? sanitize_key( $_GET['level'] ) : 'all';
|
||||
$search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
|
||||
$paged = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
|
||||
|
||||
$result = Autoblogger_Logger::query( $level, $search, $paged, 50 );
|
||||
$rows = $result['rows'];
|
||||
$total = $result['total'];
|
||||
$total_pages = (int) ceil( $total / 50 );
|
||||
|
||||
include AUTOBLOGGER_PLUGIN_DIR . 'templates/admin/log-viewer.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: clear logs older than 30 days.
|
||||
*
|
||||
* Side effects: deletes rows from ab_event_log.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_ajax_clear_logs(): void {
|
||||
check_ajax_referer( 'autoblogger_clear_logs', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'autoblogger' ) ], 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$days = isset( $_POST['days'] ) ? absint( $_POST['days'] ) : 30;
|
||||
$deleted = Autoblogger_Logger::prune( $days );
|
||||
|
||||
wp_send_json_success( [
|
||||
'message' => sprintf(
|
||||
/* translators: %d: number of entries deleted */
|
||||
__( '%d log entries cleared.', 'autoblogger' ),
|
||||
$deleted
|
||||
),
|
||||
] );
|
||||
}
|
||||
}
|
||||
46
includes/admin/class-metrics-page.php
Executable file
46
includes/admin/class-metrics-page.php
Executable file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Admin page displaying cost dashboard, content scores, and generation history.
|
||||
*
|
||||
* Shows: monthly spend, daily cost chart, spend by pipeline stage, budget
|
||||
* utilization, top/bottom performing posts, and recent generation logs.
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() on `admin_menu`.
|
||||
* Dependencies: Autoblogger_Cost_Tracker.
|
||||
*
|
||||
* @see class-autoblogger.php — Registers the hook.
|
||||
* @see core/class-cost-tracker.php — Provides cost data.
|
||||
*/
|
||||
class Autoblogger_Metrics_Page {
|
||||
|
||||
/**
|
||||
* Register the metrics submenu page under AutoBlogger.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_register_menu(): void {
|
||||
add_submenu_page(
|
||||
'autoblogger-settings',
|
||||
__( 'Metrics & Costs', 'autoblogger' ),
|
||||
__( 'Metrics & Costs', 'autoblogger' ),
|
||||
'manage_options',
|
||||
'autoblogger-metrics',
|
||||
[ $this, 'render_page' ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the metrics page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_page(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
include AUTOBLOGGER_PLUGIN_DIR . 'templates/admin/metrics-page.php';
|
||||
}
|
||||
}
|
||||
54
includes/admin/class-post-metabox.php
Executable file
54
includes/admin/class-post-metabox.php
Executable file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Adds a metabox to posts showing AutoBlogger generation metadata.
|
||||
*
|
||||
* Only appears on posts that were generated by AutoBlogger (checked via
|
||||
* _autoblogger_generated post meta).
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() on `add_meta_boxes`.
|
||||
* Dependencies: WordPress post meta API.
|
||||
*
|
||||
* @see class-autoblogger.php — Registers the hook.
|
||||
* @see core/class-publisher.php — Writes the metadata this class displays.
|
||||
*/
|
||||
class Autoblogger_Post_Metabox {
|
||||
|
||||
/**
|
||||
* Register the metabox for the post editor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_register_metabox(): void {
|
||||
$screen = get_current_screen();
|
||||
if ( ! $screen || 'post' !== $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $post;
|
||||
if ( ! $post || '1' !== get_post_meta( $post->ID, '_autoblogger_generated', true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_meta_box(
|
||||
'autoblogger_generation_info',
|
||||
__( 'AutoBlogger Generation Info', 'autoblogger' ),
|
||||
[ $this, 'render_metabox' ],
|
||||
'post',
|
||||
'side',
|
||||
'default'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the generation metadata metabox.
|
||||
*
|
||||
* @param \WP_Post $post
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_metabox( \WP_Post $post ): void {
|
||||
include AUTOBLOGGER_PLUGIN_DIR . 'templates/admin/metabox-generation-info.php';
|
||||
}
|
||||
}
|
||||
203
includes/admin/class-review-queue.php
Executable file
203
includes/admin/class-review-queue.php
Executable file
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Admin page listing generated draft posts for editorial review.
|
||||
*
|
||||
* Provides approve (publish), edit (opens WP editor), and reject (trash)
|
||||
* actions on each draft. Supports bulk approve/reject via checkboxes.
|
||||
*
|
||||
* Triggered by: Autoblogger::register_admin_hooks() on `admin_menu`.
|
||||
* Dependencies: WordPress WP_Query, post meta API.
|
||||
*
|
||||
* @see class-autoblogger.php — Registers the hook and AJAX handlers.
|
||||
* @see core/class-publisher.php — Creates the drafts this page displays.
|
||||
* @see templates/admin/review-queue.php — Renders the HTML.
|
||||
*/
|
||||
class Autoblogger_Review_Queue {
|
||||
|
||||
/**
|
||||
* Register the review queue submenu page under AutoBlogger.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_register_menu(): void {
|
||||
$hook = add_submenu_page(
|
||||
'autoblogger-settings',
|
||||
__( 'Review Queue', 'autoblogger' ),
|
||||
__( 'Review Queue', 'autoblogger' ),
|
||||
'manage_options',
|
||||
'autoblogger-review-queue',
|
||||
[ $this, 'render_page' ]
|
||||
);
|
||||
|
||||
if ( false !== $hook ) {
|
||||
add_action( "load-{$hook}", [ $this, 'on_handle_bulk_actions' ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the review queue page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_page(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$paged = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
|
||||
$query = $this->get_pending_posts( $paged );
|
||||
|
||||
include AUTOBLOGGER_PLUGIN_DIR . 'templates/admin/review-queue.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Query generated draft posts awaiting review.
|
||||
*
|
||||
* @param int $paged Page number.
|
||||
*
|
||||
* @return \WP_Query
|
||||
*/
|
||||
public function get_pending_posts( int $paged = 1 ): \WP_Query {
|
||||
return new \WP_Query( [
|
||||
'post_type' => 'post',
|
||||
'post_status' => 'draft',
|
||||
'posts_per_page' => 20,
|
||||
'paged' => $paged,
|
||||
'meta_query' => [
|
||||
[
|
||||
'key' => '_autoblogger_generated',
|
||||
'value' => '1',
|
||||
],
|
||||
],
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle bulk approve/reject actions submitted via form POST.
|
||||
*
|
||||
* Verifies nonce and capability before processing. Redirects back with
|
||||
* a status message query arg.
|
||||
*
|
||||
* Side effects: changes post status, may trash posts.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_handle_bulk_actions(): void {
|
||||
if ( ! isset( $_POST['autoblogger_bulk_action'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
check_admin_referer( 'autoblogger_review_queue_bulk', 'autoblogger_review_nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$action = sanitize_text_field( wp_unslash( $_POST['autoblogger_bulk_action'] ) );
|
||||
$post_ids = isset( $_POST['autoblogger_post_ids'] ) && is_array( $_POST['autoblogger_post_ids'] )
|
||||
? array_map( 'absint', $_POST['autoblogger_post_ids'] )
|
||||
: [];
|
||||
|
||||
if ( empty( $post_ids ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
foreach ( $post_ids as $post_id ) {
|
||||
if ( $post_id <= 0 ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( 'approve' === $action ) {
|
||||
$result = wp_update_post( [ 'ID' => $post_id, 'post_status' => 'publish' ], true );
|
||||
if ( ! is_wp_error( $result ) ) {
|
||||
update_post_meta( $post_id, '_autoblogger_approved_at', gmdate( 'c' ) );
|
||||
$count++;
|
||||
}
|
||||
} elseif ( 'reject' === $action ) {
|
||||
$result = wp_trash_post( $post_id );
|
||||
if ( false !== $result ) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$redirect = add_query_arg(
|
||||
[
|
||||
'page' => 'autoblogger-review-queue',
|
||||
'autoblogger_bulk_done' => $count,
|
||||
'autoblogger_bulk_type' => $action,
|
||||
],
|
||||
admin_url( 'admin.php' )
|
||||
);
|
||||
|
||||
wp_safe_redirect( $redirect );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: approve a single post (publish it).
|
||||
*
|
||||
* Side effects: changes post status to 'publish'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_ajax_approve_post(): void {
|
||||
check_ajax_referer( 'autoblogger_review_queue', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'autoblogger' ) ], 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
|
||||
if ( $post_id <= 0 ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Invalid post ID.', 'autoblogger' ) ] );
|
||||
return;
|
||||
}
|
||||
|
||||
$result = wp_update_post( [ 'ID' => $post_id, 'post_status' => 'publish' ], true );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
wp_send_json_error( [ 'message' => $result->get_error_message() ] );
|
||||
return;
|
||||
}
|
||||
|
||||
update_post_meta( $post_id, '_autoblogger_approved_at', gmdate( 'c' ) );
|
||||
wp_send_json_success( [ 'message' => __( 'Post published.', 'autoblogger' ), 'post_id' => $post_id ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: reject a single post (trash it).
|
||||
*
|
||||
* Side effects: trashes the post.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_ajax_reject_post(): void {
|
||||
check_ajax_referer( 'autoblogger_review_queue', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'autoblogger' ) ], 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
|
||||
if ( $post_id <= 0 ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Invalid post ID.', 'autoblogger' ) ] );
|
||||
return;
|
||||
}
|
||||
|
||||
$result = wp_trash_post( $post_id );
|
||||
if ( false === $result || null === $result ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Failed to reject post.', 'autoblogger' ) ] );
|
||||
return;
|
||||
}
|
||||
|
||||
wp_send_json_success( [ 'message' => __( 'Post rejected.', 'autoblogger' ), 'post_id' => $post_id ] );
|
||||
}
|
||||
}
|
||||
291
includes/admin/class-settings-fields.php
Executable file
291
includes/admin/class-settings-fields.php
Executable file
@@ -0,0 +1,291 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Declarative settings fields and sections for the AutoBlogger admin page.
|
||||
*
|
||||
* Centralizes all field and section definitions in one place, making it trivial
|
||||
* to add new settings (just add one array entry). Decoupled from page rendering logic.
|
||||
*
|
||||
* Triggered by: Autoblogger_Admin_Page::on_register_settings() calls static methods here.
|
||||
* Dependencies: None — contains only data definitions and static methods.
|
||||
*
|
||||
* @see admin/class-admin-page.php — Calls get_sections() and get_fields() to register settings.
|
||||
* @see CONVENTIONS.md — "How To: Add a New Admin Setting".
|
||||
*/
|
||||
class Autoblogger_Settings_Fields {
|
||||
|
||||
/**
|
||||
* Get all settings sections. Each section maps to a tab in the admin UI.
|
||||
*
|
||||
* @return array<string, array{title: string, icon: string, description: string}>
|
||||
*/
|
||||
public static function get_sections(): array {
|
||||
return [
|
||||
'autoblogger_api' => [
|
||||
'title' => __( 'API Keys', 'autoblogger' ),
|
||||
'icon' => 'dashicons-admin-network',
|
||||
'description' => __( 'Connect your external services. Keys are encrypted at rest.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_models' => [
|
||||
'title' => __( 'AI Models', 'autoblogger' ),
|
||||
'icon' => 'dashicons-superhero-alt',
|
||||
'description' => __( 'Choose which models power each stage of the pipeline.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_content' => [
|
||||
'title' => __( 'Content', 'autoblogger' ),
|
||||
'icon' => 'dashicons-edit-large',
|
||||
'description' => __( 'Control tone, length, pipeline mode, and topic guardrails.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_sources' => [
|
||||
'title' => __( 'Sources', 'autoblogger' ),
|
||||
'icon' => 'dashicons-rss',
|
||||
'description' => __( 'Configure where AutoBlogger finds trending topics.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_schedule' => [
|
||||
'title' => __( 'Schedule & Budget', 'autoblogger' ),
|
||||
'icon' => 'dashicons-calendar-alt',
|
||||
'description' => __( 'Set daily generation schedule, volume, and spending limits.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_publishing' => [
|
||||
'title' => __( 'Publishing', 'autoblogger' ),
|
||||
'icon' => 'dashicons-megaphone',
|
||||
'description' => __( 'Control how generated content is published.', 'autoblogger' ),
|
||||
],
|
||||
'autoblogger_analytics' => [
|
||||
'title' => __( 'Analytics', 'autoblogger' ),
|
||||
'icon' => 'dashicons-chart-area',
|
||||
'description' => __( 'Connect Google Analytics 4 for post performance scoring.', 'autoblogger' ),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all settings fields. Adding a new setting = adding one entry to this array.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public static function get_fields(): array {
|
||||
return [
|
||||
// ── API Keys ────────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_openrouter_api_key',
|
||||
'label' => __( 'OpenRouter API Key', 'autoblogger' ),
|
||||
'type' => 'password',
|
||||
'section' => 'autoblogger_api',
|
||||
'description' => __( 'Get your key at openrouter.ai/keys', 'autoblogger' ),
|
||||
'icon' => '🔑',
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_reddit_client_id',
|
||||
'label' => __( 'Reddit Client ID', 'autoblogger' ),
|
||||
'type' => 'text',
|
||||
'section' => 'autoblogger_api',
|
||||
'description' => __( 'Create a script app at reddit.com/prefs/apps', 'autoblogger' ),
|
||||
'icon' => '🤖',
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_reddit_client_secret',
|
||||
'label' => __( 'Reddit Client Secret', 'autoblogger' ),
|
||||
'type' => 'password',
|
||||
'section' => 'autoblogger_api',
|
||||
],
|
||||
|
||||
// ── AI Models ───────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_analysis_model',
|
||||
'label' => __( 'Analysis Model', 'autoblogger' ),
|
||||
'type' => 'text',
|
||||
'section' => 'autoblogger_models',
|
||||
'default' => AUTOBLOGGER_DEFAULT_ANALYSIS_MODEL,
|
||||
'description' => __( 'Used for source analysis. Pick a cheap, fast model.', 'autoblogger' ),
|
||||
'badge' => __( 'Low cost', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_writing_model',
|
||||
'label' => __( 'Writing Model', 'autoblogger' ),
|
||||
'type' => 'text',
|
||||
'section' => 'autoblogger_models',
|
||||
'default' => AUTOBLOGGER_DEFAULT_WRITING_MODEL,
|
||||
'description' => __( 'Used for article generation. Quality matters here.', 'autoblogger' ),
|
||||
'badge' => __( 'Quality', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_editor_model',
|
||||
'label' => __( 'Editor Model', 'autoblogger' ),
|
||||
'type' => 'text',
|
||||
'section' => 'autoblogger_models',
|
||||
'default' => AUTOBLOGGER_DEFAULT_EDITOR_MODEL,
|
||||
'description' => __( 'Used for the chief editor review pass.', 'autoblogger' ),
|
||||
'badge' => __( 'Quality', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Content ─────────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_niche_description',
|
||||
'label' => __( 'Niche Description', 'autoblogger' ),
|
||||
'type' => 'textarea',
|
||||
'section' => 'autoblogger_content',
|
||||
'description' => __( 'Describe your site\'s niche. Guides content analysis and generation.', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_tone',
|
||||
'label' => __( 'Content Tone', 'autoblogger' ),
|
||||
'type' => 'select',
|
||||
'section' => 'autoblogger_content',
|
||||
'default' => 'informational',
|
||||
'options' => [
|
||||
'informational' => __( 'Informational', 'autoblogger' ),
|
||||
'conversational' => __( 'Conversational', 'autoblogger' ),
|
||||
'professional' => __( 'Professional', 'autoblogger' ),
|
||||
'casual' => __( 'Casual', 'autoblogger' ),
|
||||
'authoritative' => __( 'Authoritative', 'autoblogger' ),
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_writing_pipeline',
|
||||
'label' => __( 'Writing Pipeline', 'autoblogger' ),
|
||||
'type' => 'select',
|
||||
'section' => 'autoblogger_content',
|
||||
'default' => 'multi_step',
|
||||
'options' => [
|
||||
'multi_step' => __( 'Multi-step (outline → draft → polish)', 'autoblogger' ),
|
||||
'single_pass' => __( 'Single-pass (one LLM call)', 'autoblogger' ),
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_min_word_count',
|
||||
'label' => __( 'Min Word Count', 'autoblogger' ),
|
||||
'type' => 'number',
|
||||
'section' => 'autoblogger_content',
|
||||
'default' => 800,
|
||||
'min' => 200,
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_max_word_count',
|
||||
'label' => __( 'Max Word Count', 'autoblogger' ),
|
||||
'type' => 'number',
|
||||
'section' => 'autoblogger_content',
|
||||
'default' => 2000,
|
||||
'min' => 500,
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_topic_exclusions',
|
||||
'label' => __( 'Topic Exclusions', 'autoblogger' ),
|
||||
'type' => 'textarea',
|
||||
'section' => 'autoblogger_content',
|
||||
'description' => __( 'Comma-separated topics to never write about.', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Sources ─────────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_target_subreddits',
|
||||
'label' => __( 'Target Subreddits', 'autoblogger' ),
|
||||
'type' => 'textarea',
|
||||
'section' => 'autoblogger_sources',
|
||||
'description' => __( 'Comma-separated, without r/. E.g.: peptides, Nootropics, biohackers', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_enabled_sources',
|
||||
'label' => __( 'Enabled Sources', 'autoblogger' ),
|
||||
'type' => 'checkboxes',
|
||||
'section' => 'autoblogger_sources',
|
||||
'options' => [
|
||||
'reddit' => __( 'Reddit', 'autoblogger' ),
|
||||
'tiktok' => __( 'TikTok (coming soon)', 'autoblogger' ),
|
||||
'instagram' => __( 'Instagram (coming soon)', 'autoblogger' ),
|
||||
'youtube' => __( 'YouTube (coming soon)', 'autoblogger' ),
|
||||
],
|
||||
'default' => '["reddit"]',
|
||||
'description' => __( 'Select which platforms to monitor for topics.', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Schedule & Budget ───────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_daily_article_target',
|
||||
'label' => __( 'Articles per Day', 'autoblogger' ),
|
||||
'type' => 'number',
|
||||
'section' => 'autoblogger_schedule',
|
||||
'default' => 1,
|
||||
'min' => 1,
|
||||
'max' => 10,
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_schedule_time',
|
||||
'label' => __( 'Generation Time', 'autoblogger' ),
|
||||
'type' => 'time',
|
||||
'section' => 'autoblogger_schedule',
|
||||
'default' => '03:00',
|
||||
'description' => __( 'Daily generation runs at this time (server timezone).', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_monthly_budget_usd',
|
||||
'label' => __( 'Monthly Budget (USD)', 'autoblogger' ),
|
||||
'type' => 'number',
|
||||
'section' => 'autoblogger_schedule',
|
||||
'default' => 50,
|
||||
'min' => 0,
|
||||
'step' => '0.01',
|
||||
'description' => __( 'Hard stop when reached. 0 = unlimited.', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Publishing ──────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_auto_publish',
|
||||
'label' => __( 'Auto-Publish', 'autoblogger' ),
|
||||
'type' => 'toggle',
|
||||
'section' => 'autoblogger_publishing',
|
||||
'default' => '0',
|
||||
'description' => __( 'Automatically publish editor-approved posts. When off, all posts go to the Review Queue as drafts.', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_default_author',
|
||||
'label' => __( 'Default Author', 'autoblogger' ),
|
||||
'type' => 'author_select',
|
||||
'section' => 'autoblogger_publishing',
|
||||
'default' => 0,
|
||||
'description' => __( 'WordPress user assigned as author of generated posts.', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_default_category',
|
||||
'label' => __( 'Default Category', 'autoblogger' ),
|
||||
'type' => 'category_select',
|
||||
'section' => 'autoblogger_publishing',
|
||||
'default' => 0,
|
||||
'description' => __( 'Fallback category for generated posts.', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Logging ─────────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_log_level',
|
||||
'label' => __( 'Log Level', 'autoblogger' ),
|
||||
'type' => 'select',
|
||||
'section' => 'autoblogger_publishing',
|
||||
'default' => 'info',
|
||||
'options' => [
|
||||
'error' => __( 'Error — only failures', 'autoblogger' ),
|
||||
'warning' => __( 'Warning — errors + warnings', 'autoblogger' ),
|
||||
'info' => __( 'Info — key events (recommended)', 'autoblogger' ),
|
||||
'debug' => __( 'Debug — everything (verbose)', 'autoblogger' ),
|
||||
],
|
||||
'description' => __( 'Controls detail level in the Activity Log.', 'autoblogger' ),
|
||||
],
|
||||
|
||||
// ── Analytics ───────────────────────────────────────────────
|
||||
[
|
||||
'id' => 'autoblogger_ga4_property_id',
|
||||
'label' => __( 'GA4 Property ID', 'autoblogger' ),
|
||||
'type' => 'text',
|
||||
'section' => 'autoblogger_analytics',
|
||||
'description' => __( 'Format: properties/XXXXXXXXX. Leave blank to skip GA4.', 'autoblogger' ),
|
||||
],
|
||||
[
|
||||
'id' => 'autoblogger_ga4_credentials_json',
|
||||
'label' => __( 'Service Account JSON', 'autoblogger' ),
|
||||
'type' => 'password',
|
||||
'section' => 'autoblogger_analytics',
|
||||
'description' => __( 'Paste the full JSON key file for a service account with Analytics read access.', 'autoblogger' ),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
226
includes/class-activator.php
Executable file
226
includes/class-activator.php
Executable file
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Handles plugin activation: creates database tables, sets default options,
|
||||
* and schedules the initial cron job.
|
||||
*
|
||||
* Triggered by: WordPress `register_activation_hook` in autoblogger.php.
|
||||
* Dependencies: WordPress $wpdb, dbDelta().
|
||||
*
|
||||
* @see class-deactivator.php — Reverses transient/cron setup on deactivation.
|
||||
* @see ARCHITECTURE.md — Database schema definitions.
|
||||
*/
|
||||
class Autoblogger_Activator {
|
||||
|
||||
/**
|
||||
* Run activation tasks.
|
||||
*
|
||||
* Creates custom database tables if they don't exist, sets default option
|
||||
* values (without overwriting existing ones), and schedules the daily
|
||||
* generation cron event.
|
||||
*
|
||||
* Side effects: writes to wp_options, creates database tables, schedules WP-Cron event.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function activate(): void {
|
||||
self::create_tables();
|
||||
self::set_default_options();
|
||||
self::schedule_cron();
|
||||
|
||||
// Store the DB version so we can run migrations on future updates.
|
||||
update_option( 'autoblogger_db_version', AUTOBLOGGER_DB_VERSION, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create all custom database tables using dbDelta.
|
||||
*
|
||||
* Side effects: creates/updates four database tables.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function create_tables(): void {
|
||||
global $wpdb;
|
||||
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
$prefix = $wpdb->prefix . 'autoblogger_';
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
|
||||
// Source data — raw posts/comments from social platforms.
|
||||
$sql_source_data = "CREATE TABLE {$prefix}source_data (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
source_type VARCHAR(50) NOT NULL,
|
||||
source_id VARCHAR(255) NOT NULL,
|
||||
subreddit VARCHAR(255) DEFAULT NULL,
|
||||
title TEXT DEFAULT NULL,
|
||||
content LONGTEXT DEFAULT NULL,
|
||||
author VARCHAR(255) DEFAULT NULL,
|
||||
score INT DEFAULT 0,
|
||||
comment_count INT DEFAULT 0,
|
||||
permalink VARCHAR(500) DEFAULT NULL,
|
||||
collected_at DATETIME NOT NULL,
|
||||
metadata_json LONGTEXT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY source_unique (source_type, source_id),
|
||||
KEY source_collected (source_type, collected_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Analysis results — detected patterns from source data.
|
||||
$sql_analysis = "CREATE TABLE {$prefix}analysis_results (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
analysis_type VARCHAR(50) NOT NULL,
|
||||
topic VARCHAR(500) NOT NULL,
|
||||
summary TEXT DEFAULT NULL,
|
||||
frequency INT DEFAULT 1,
|
||||
relevance_score FLOAT DEFAULT 0,
|
||||
source_ids_json LONGTEXT DEFAULT NULL,
|
||||
analyzed_at DATETIME NOT NULL,
|
||||
metadata_json LONGTEXT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY type_relevance (analysis_type, relevance_score),
|
||||
KEY analyzed_at (analyzed_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Generation log — every API call with cost tracking.
|
||||
// run_id groups all log entries from a single pipeline execution so
|
||||
// link_generation_logs() can accurately attribute costs to a post.
|
||||
$sql_generation_log = "CREATE TABLE {$prefix}generation_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
post_id BIGINT UNSIGNED DEFAULT NULL,
|
||||
run_id VARCHAR(36) DEFAULT NULL,
|
||||
stage VARCHAR(50) NOT NULL,
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100) NOT NULL,
|
||||
prompt_tokens INT DEFAULT 0,
|
||||
completion_tokens INT DEFAULT 0,
|
||||
estimated_cost DECIMAL(10,6) DEFAULT 0,
|
||||
request_json LONGTEXT DEFAULT NULL,
|
||||
response_status VARCHAR(20) NOT NULL DEFAULT 'success',
|
||||
error_message TEXT DEFAULT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY post_id (post_id),
|
||||
KEY run_id (run_id),
|
||||
KEY created_at (created_at),
|
||||
KEY stage (stage)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Content scores — post performance metrics for self-improvement.
|
||||
$sql_content_scores = "CREATE TABLE {$prefix}content_scores (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
post_id BIGINT UNSIGNED NOT NULL,
|
||||
pageviews INT DEFAULT 0,
|
||||
avg_time_on_page FLOAT DEFAULT 0,
|
||||
bounce_rate FLOAT DEFAULT 0,
|
||||
comment_count INT DEFAULT 0,
|
||||
composite_score FLOAT DEFAULT 0,
|
||||
score_factors_json LONGTEXT DEFAULT NULL,
|
||||
measured_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY post_id (post_id),
|
||||
KEY measured_at (measured_at),
|
||||
KEY composite_score (composite_score)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Event log — structured application log entries for the admin log viewer.
|
||||
$sql_event_log = "CREATE TABLE {$prefix}event_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
level VARCHAR(10) NOT NULL DEFAULT 'info',
|
||||
context VARCHAR(100) DEFAULT NULL,
|
||||
message TEXT NOT NULL,
|
||||
meta_json LONGTEXT DEFAULT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY level (level),
|
||||
KEY created_at (created_at),
|
||||
KEY level_created (level, created_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
dbDelta( $sql_source_data );
|
||||
dbDelta( $sql_analysis );
|
||||
dbDelta( $sql_generation_log );
|
||||
dbDelta( $sql_content_scores );
|
||||
dbDelta( $sql_event_log );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default option values without overwriting existing ones.
|
||||
*
|
||||
* Uses add_option() which is a no-op if the option already exists.
|
||||
*
|
||||
* Side effects: writes to wp_options.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function set_default_options(): void {
|
||||
$defaults = [
|
||||
'autoblogger_analysis_model' => AUTOBLOGGER_DEFAULT_ANALYSIS_MODEL,
|
||||
'autoblogger_writing_model' => AUTOBLOGGER_DEFAULT_WRITING_MODEL,
|
||||
'autoblogger_editor_model' => AUTOBLOGGER_DEFAULT_EDITOR_MODEL,
|
||||
'autoblogger_daily_article_target' => 1,
|
||||
'autoblogger_writing_pipeline' => 'multi_step',
|
||||
'autoblogger_niche_description' => '',
|
||||
'autoblogger_target_subreddits' => '[]',
|
||||
'autoblogger_monthly_budget_usd' => 50.00,
|
||||
'autoblogger_tone' => 'informational',
|
||||
'autoblogger_min_word_count' => 800,
|
||||
'autoblogger_max_word_count' => 2000,
|
||||
'autoblogger_topic_exclusions' => '[]',
|
||||
'autoblogger_enabled_sources' => '["reddit"]',
|
||||
'autoblogger_schedule_time' => '03:00',
|
||||
'autoblogger_log_level' => 'info',
|
||||
];
|
||||
|
||||
foreach ( $defaults as $key => $value ) {
|
||||
add_option( $key, $value );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule the daily generation cron event if not already scheduled.
|
||||
*
|
||||
* The custom 'autoblogger_six_hours' schedule is normally registered via
|
||||
* the `cron_schedules` filter in class-autoblogger.php. However, activation
|
||||
* runs before `plugins_loaded`, so the filter may not be registered yet.
|
||||
* We register it inline here to ensure it exists at scheduling time.
|
||||
*
|
||||
* Side effects: registers a WP-Cron event, may register a cron schedule.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function schedule_cron(): void {
|
||||
if ( ! wp_next_scheduled( 'autoblogger_daily_generation' ) ) {
|
||||
// Schedule for the configured time tomorrow.
|
||||
$time_str = get_option( 'autoblogger_schedule_time', '03:00' );
|
||||
$parts = explode( ':', $time_str );
|
||||
$hour = isset( $parts[0] ) ? absint( $parts[0] ) : 3;
|
||||
$minute = isset( $parts[1] ) ? absint( $parts[1] ) : 0;
|
||||
$timestamp = strtotime( "tomorrow {$hour}:{$minute}" );
|
||||
|
||||
if ( false !== $timestamp ) {
|
||||
wp_schedule_event( $timestamp, 'daily', 'autoblogger_daily_generation' );
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure the six-hour schedule exists before referencing it.
|
||||
// Activation can fire before plugins_loaded, so the cron_schedules filter
|
||||
// in class-autoblogger.php may not be hooked yet.
|
||||
$schedules = wp_get_schedules();
|
||||
if ( ! isset( $schedules['autoblogger_six_hours'] ) ) {
|
||||
add_filter( 'cron_schedules', static function ( array $scheds ): array {
|
||||
$scheds['autoblogger_six_hours'] = [
|
||||
'interval' => 6 * HOUR_IN_SECONDS,
|
||||
'display' => __( 'Every Six Hours', 'autoblogger' ),
|
||||
];
|
||||
return $scheds;
|
||||
} );
|
||||
}
|
||||
|
||||
// Schedule a separate metrics collection job (runs every 6 hours).
|
||||
if ( ! wp_next_scheduled( 'autoblogger_collect_metrics' ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'autoblogger_six_hours', 'autoblogger_collect_metrics' );
|
||||
}
|
||||
}
|
||||
}
|
||||
298
includes/class-autoblogger.php
Executable file
298
includes/class-autoblogger.php
Executable file
@@ -0,0 +1,298 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Main orchestrator for the AutoBlogger plugin.
|
||||
*
|
||||
* Registers all WordPress hooks (actions and filters) and wires up dependencies.
|
||||
* This is the ONLY place hooks are registered — individual classes contain only
|
||||
* business logic, not hook registration.
|
||||
*
|
||||
* Triggered by: autoblogger() singleton in autoblogger.php, called on `plugins_loaded`.
|
||||
* Dependencies: All other plugin classes (loaded via autoloader), Autoblogger_Pipeline_Runner.
|
||||
*
|
||||
* @see autoblogger.php — Plugin bootstrap that instantiates this class.
|
||||
* @see core/class-pipeline-runner.php — Executes the generation pipeline.
|
||||
* @see ARCHITECTURE.md — Data flow diagram showing how classes interact.
|
||||
* @see CONVENTIONS.md — Hook naming conventions.
|
||||
*/
|
||||
class Autoblogger {
|
||||
|
||||
/**
|
||||
* Whether the plugin has been initialized.
|
||||
*/
|
||||
private bool $initialized = false;
|
||||
|
||||
/**
|
||||
* Register all hooks and initialize the plugin.
|
||||
*
|
||||
* Called once on `plugins_loaded`. Idempotent — calling it twice is a no-op.
|
||||
*
|
||||
* Side effects: registers WordPress actions and filters.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function run(): void {
|
||||
if ( $this->initialized ) {
|
||||
return;
|
||||
}
|
||||
$this->initialized = true;
|
||||
|
||||
// Check for database migrations on admin_init.
|
||||
add_action( 'admin_init', [ $this, 'on_check_db_version' ] );
|
||||
|
||||
// Register custom cron schedules.
|
||||
add_filter( 'cron_schedules', [ $this, 'filter_add_cron_schedules' ] );
|
||||
|
||||
// Admin hooks — only load on admin pages.
|
||||
if ( is_admin() ) {
|
||||
$this->register_admin_hooks();
|
||||
}
|
||||
|
||||
// Cron hooks — always registered so WP-Cron can fire them.
|
||||
$this->register_cron_hooks();
|
||||
|
||||
// AJAX hooks — always registered so admin AJAX works.
|
||||
$this->register_ajax_hooks();
|
||||
|
||||
/**
|
||||
* Fires after AutoBlogger has finished registering all hooks.
|
||||
*
|
||||
* Useful for add-ons that need to hook into AutoBlogger's lifecycle.
|
||||
*/
|
||||
do_action( 'autoblogger_loaded' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register admin-only hooks (settings page, notices, metabox, dashboard widget).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_admin_hooks(): void {
|
||||
$admin_page = new Autoblogger_Admin_Page();
|
||||
add_action( 'admin_menu', [ $admin_page, 'on_register_menu' ] );
|
||||
add_action( 'admin_init', [ $admin_page, 'on_register_settings' ] );
|
||||
add_action( 'admin_enqueue_scripts', [ $admin_page, 'on_enqueue_assets' ] );
|
||||
|
||||
$notices = new Autoblogger_Admin_Notices();
|
||||
add_action( 'admin_notices', [ $notices, 'on_display_notices' ] );
|
||||
|
||||
$metabox = new Autoblogger_Post_Metabox();
|
||||
add_action( 'add_meta_boxes', [ $metabox, 'on_register_metabox' ] );
|
||||
|
||||
$metrics_page = new Autoblogger_Metrics_Page();
|
||||
add_action( 'admin_menu', [ $metrics_page, 'on_register_menu' ] );
|
||||
|
||||
$dashboard_widget = new Autoblogger_Dashboard_Widget();
|
||||
add_action( 'wp_dashboard_setup', [ $dashboard_widget, 'on_register_widget' ] );
|
||||
|
||||
$review_queue = new Autoblogger_Review_Queue();
|
||||
add_action( 'admin_menu', [ $review_queue, 'on_register_menu' ] );
|
||||
|
||||
$log_viewer = new Autoblogger_Log_Viewer();
|
||||
add_action( 'admin_menu', [ $log_viewer, 'on_register_menu' ] );
|
||||
}
|
||||
|
||||
/** Register cron-triggered hooks for scheduled generation and metrics. */
|
||||
private function register_cron_hooks(): void {
|
||||
add_action( 'autoblogger_daily_generation', [ $this, 'on_daily_generation' ] );
|
||||
add_action( 'autoblogger_collect_metrics', [ $this, 'on_collect_metrics' ] );
|
||||
}
|
||||
|
||||
/** Register AJAX handlers for admin actions. */
|
||||
private function register_ajax_hooks(): void {
|
||||
add_action( 'wp_ajax_autoblogger_generate_now', [ $this, 'on_ajax_generate_now' ] );
|
||||
add_action( 'wp_ajax_autoblogger_test_connection', [ $this, 'on_ajax_test_connection' ] );
|
||||
|
||||
$review_queue = new Autoblogger_Review_Queue();
|
||||
add_action( 'wp_ajax_autoblogger_approve_post', [ $review_queue, 'on_ajax_approve_post' ] );
|
||||
add_action( 'wp_ajax_autoblogger_reject_post', [ $review_queue, 'on_ajax_reject_post' ] );
|
||||
|
||||
$log_viewer = new Autoblogger_Log_Viewer();
|
||||
add_action( 'wp_ajax_autoblogger_clear_logs', [ $log_viewer, 'on_ajax_clear_logs' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if database needs migration after plugin update.
|
||||
*
|
||||
* Compares stored DB version with current AUTOBLOGGER_DB_VERSION.
|
||||
* If different, re-runs activation to apply schema changes via dbDelta.
|
||||
*
|
||||
* Side effects: may update database schema and db_version option.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_check_db_version(): void {
|
||||
$stored_version = get_option( 'autoblogger_db_version', '0' );
|
||||
if ( version_compare( $stored_version, AUTOBLOGGER_DB_VERSION, '<' ) ) {
|
||||
Autoblogger_Activator::activate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add custom cron schedules (six-hourly for metrics collection).
|
||||
*
|
||||
* @param array<string, array{interval: int, display: string}> $schedules Existing schedules.
|
||||
*
|
||||
* @return array<string, array{interval: int, display: string}> Modified schedules.
|
||||
*/
|
||||
public function filter_add_cron_schedules( array $schedules ): array {
|
||||
$schedules['autoblogger_six_hours'] = [
|
||||
'interval' => 6 * HOUR_IN_SECONDS,
|
||||
'display' => __( 'Every Six Hours', 'autoblogger' ),
|
||||
];
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the daily generation cron event.
|
||||
*
|
||||
* Uses a database-level atomic mutex to prevent overlapping runs.
|
||||
*
|
||||
* Side effects: API calls, database writes, WordPress post creation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_daily_generation(): void {
|
||||
if ( ! $this->acquire_generation_lock() ) {
|
||||
Autoblogger_Logger::instance()->info( 'Daily generation skipped: already running (lock held).', 'scheduler' );
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
( new Autoblogger_Pipeline_Runner() )->run();
|
||||
} catch ( \Exception $e ) {
|
||||
Autoblogger_Logger::instance()->error( 'Daily generation FAILED: ' . $e->getMessage(), 'scheduler' );
|
||||
} finally {
|
||||
$this->release_generation_lock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the metrics collection cron event.
|
||||
*
|
||||
* Side effects: API calls to GA4, database writes to ab_content_scores.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_collect_metrics(): void {
|
||||
try {
|
||||
$metrics = new Autoblogger_Metrics_Collector();
|
||||
$metrics->collect_all();
|
||||
} catch ( \Exception $e ) {
|
||||
Autoblogger_Logger::instance()->error( 'Metrics collection FAILED: ' . $e->getMessage(), 'metrics' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: trigger manual generation.
|
||||
*
|
||||
* Verifies nonce and capability, then runs the generation pipeline.
|
||||
* Uses the same atomic DB lock as the cron handler.
|
||||
*
|
||||
* Side effects: API calls, database writes, WordPress post creation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_ajax_generate_now(): void {
|
||||
check_ajax_referer( 'autoblogger_generate_now', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'autoblogger' ) ], 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->acquire_generation_lock() ) {
|
||||
wp_send_json_error( [ 'message' => __( 'A generation run is already in progress.', 'autoblogger' ) ] );
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$results = ( new Autoblogger_Pipeline_Runner() )->run();
|
||||
wp_send_json_success( $results );
|
||||
} catch ( \Exception $e ) {
|
||||
Autoblogger_Logger::instance()->error( 'Manual generation FAILED: ' . $e->getMessage(), 'pipeline' );
|
||||
wp_send_json_error( [ 'message' => $e->getMessage() ] );
|
||||
} finally {
|
||||
$this->release_generation_lock();
|
||||
}
|
||||
}
|
||||
|
||||
/** AJAX handler: test API connections (OpenRouter, Reddit). */
|
||||
public function on_ajax_test_connection(): void {
|
||||
check_ajax_referer( 'autoblogger_test_connection', 'nonce' );
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( [ 'message' => __( 'Insufficient permissions.', 'autoblogger' ) ], 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$service = isset( $_POST['service'] ) ? sanitize_text_field( wp_unslash( $_POST['service'] ) ) : '';
|
||||
$results = [];
|
||||
|
||||
if ( 'openrouter' === $service || 'all' === $service ) {
|
||||
$llm = new Autoblogger_OpenRouter_Provider();
|
||||
$results['openrouter'] = $llm->validate_credentials()
|
||||
? [ 'status' => 'ok', 'message' => __( 'OpenRouter connected.', 'autoblogger' ) ]
|
||||
: [ 'status' => 'error', 'message' => __( 'OpenRouter connection failed. Check your API key.', 'autoblogger' ) ];
|
||||
}
|
||||
if ( 'reddit' === $service || 'all' === $service ) {
|
||||
$reddit = new Autoblogger_Reddit_Provider();
|
||||
$results['reddit'] = $reddit->validate_credentials()
|
||||
? [ 'status' => 'ok', 'message' => __( 'Reddit API connected.', 'autoblogger' ) ]
|
||||
: [ 'status' => 'error', 'message' => __( 'Reddit connection failed. Check client ID/secret.', 'autoblogger' ) ];
|
||||
}
|
||||
wp_send_json_success( $results );
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire a database-level atomic mutex for generation.
|
||||
*
|
||||
* Uses INSERT IGNORE into wp_options — option_name has a UNIQUE index so only
|
||||
* one process can insert the row. Expired locks (>1 hour) are cleaned up first.
|
||||
*
|
||||
* @return bool True if lock acquired, false if another process holds it.
|
||||
*/
|
||||
private function acquire_generation_lock(): bool {
|
||||
global $wpdb;
|
||||
|
||||
$lock_name = 'autoblogger_generation_lock';
|
||||
$now = (string) time();
|
||||
|
||||
// Clean up expired locks older than 1 hour — prevents permanent deadlock.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->options} WHERE option_name = %s AND CAST(option_value AS UNSIGNED) < %d",
|
||||
$lock_name,
|
||||
time() - HOUR_IN_SECONDS
|
||||
)
|
||||
);
|
||||
|
||||
// Atomic insert — UNIQUE constraint on option_name guarantees only one process succeeds.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$result = $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, %s)",
|
||||
$lock_name,
|
||||
$now,
|
||||
'no'
|
||||
)
|
||||
);
|
||||
|
||||
return $result > 0;
|
||||
}
|
||||
|
||||
/** Release the generation mutex. */
|
||||
private function release_generation_lock(): void {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->options} WHERE option_name = %s",
|
||||
'autoblogger_generation_lock'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
94
includes/class-autoloader.php
Executable file
94
includes/class-autoloader.php
Executable file
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* PSR-4-inspired autoloader for AutoBlogger classes.
|
||||
*
|
||||
* Maps class names like `Autoblogger_Content_Generator` to file paths like
|
||||
* `includes/core/class-content-generator.php` by scanning known subdirectories.
|
||||
*
|
||||
* Triggered by: PHP's spl_autoload when a class is first referenced.
|
||||
* Dependencies: None — this is loaded before anything else.
|
||||
*
|
||||
* @see autoblogger.php — Registers this autoloader at boot time.
|
||||
*/
|
||||
class Autoblogger_Autoloader {
|
||||
|
||||
/**
|
||||
* Directories to scan for class files, relative to the plugin's includes/ dir.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private static array $directories = [
|
||||
'', // includes/ root
|
||||
'admin/',
|
||||
'core/',
|
||||
'providers/',
|
||||
'models/',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the autoloader with SPL.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function register(): void {
|
||||
spl_autoload_register( [ __CLASS__, 'autoload' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to load a class file.
|
||||
*
|
||||
* Converts `Autoblogger_Content_Generator` → `class-content-generator.php`
|
||||
* and searches each registered subdirectory under includes/.
|
||||
*
|
||||
* @param string $class_name Fully qualified class name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function autoload( string $class_name ): void {
|
||||
// Only handle our own classes.
|
||||
if ( 0 !== strpos( $class_name, 'Autoblogger' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$file_name = self::class_to_filename( $class_name );
|
||||
$base_dir = AUTOBLOGGER_PLUGIN_DIR . 'includes/';
|
||||
|
||||
foreach ( self::$directories as $directory ) {
|
||||
$file_path = $base_dir . $directory . $file_name;
|
||||
if ( file_exists( $file_path ) ) {
|
||||
require_once $file_path;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a class name to its expected filename.
|
||||
*
|
||||
* Autoblogger_Content_Generator → class-content-generator.php
|
||||
* Autoblogger_LLM_Provider_Interface → interface-llm-provider.php
|
||||
*
|
||||
* @param string $class_name The class name to convert.
|
||||
*
|
||||
* @return string The expected filename.
|
||||
*/
|
||||
private static function class_to_filename( string $class_name ): string {
|
||||
// Remove the Autoblogger_ prefix.
|
||||
$name = (string) preg_replace( '/^Autoblogger_/', '', $class_name );
|
||||
|
||||
// Determine file prefix: interface- or class-.
|
||||
$prefix = 'class-';
|
||||
if ( preg_match( '/_Interface$/', $name ) ) {
|
||||
$prefix = 'interface-';
|
||||
$name = (string) preg_replace( '/_Interface$/', '', $name );
|
||||
}
|
||||
|
||||
// Convert PascalCase/UPPER_CASE to kebab-case.
|
||||
$name = strtolower( (string) preg_replace( '/([a-z])([A-Z])/', '$1-$2', $name ) );
|
||||
$name = str_replace( '_', '-', $name );
|
||||
|
||||
return $prefix . $name . '.php';
|
||||
}
|
||||
}
|
||||
67
includes/class-deactivator.php
Executable file
67
includes/class-deactivator.php
Executable file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Handles plugin deactivation: clears scheduled cron events and transients.
|
||||
*
|
||||
* Note: does NOT delete data or options — that happens in uninstall.php.
|
||||
* Deactivation should be reversible (user can reactivate and pick up where they left off).
|
||||
*
|
||||
* Triggered by: WordPress `register_deactivation_hook` in autoblogger.php.
|
||||
* Dependencies: None.
|
||||
*
|
||||
* @see class-activator.php — Sets up what this class tears down.
|
||||
* @see uninstall.php — Permanent data removal on plugin deletion.
|
||||
*/
|
||||
class Autoblogger_Deactivator {
|
||||
|
||||
/**
|
||||
* Run deactivation tasks.
|
||||
*
|
||||
* Side effects: removes WP-Cron events and deletes transients.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function deactivate(): void {
|
||||
self::clear_cron();
|
||||
self::clear_transients();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all scheduled cron events belonging to this plugin.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function clear_cron(): void {
|
||||
$hooks = [
|
||||
'autoblogger_daily_generation',
|
||||
'autoblogger_collect_metrics',
|
||||
];
|
||||
|
||||
foreach ( $hooks as $hook ) {
|
||||
$timestamp = wp_next_scheduled( $hook );
|
||||
if ( false !== $timestamp ) {
|
||||
wp_unschedule_event( $timestamp, $hook );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all plugin transients.
|
||||
*
|
||||
* Side effects: deletes transients from wp_options.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function clear_transients(): void {
|
||||
$transients = [
|
||||
'autoblogger_reddit_token',
|
||||
'autoblogger_generation_lock',
|
||||
'autoblogger_openrouter_models',
|
||||
];
|
||||
|
||||
foreach ( $transients as $transient ) {
|
||||
delete_transient( $transient );
|
||||
}
|
||||
}
|
||||
}
|
||||
89
includes/class-encryption.php
Executable file
89
includes/class-encryption.php
Executable file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Encrypts and decrypts sensitive option values (API keys, secrets).
|
||||
*
|
||||
* Uses OpenSSL AES-256-CBC with a key derived from wp_salt('auth').
|
||||
* This is not bulletproof — anyone who can read wp-config.php can decrypt — but it
|
||||
* prevents casual exposure of API keys in database dumps or phpMyAdmin.
|
||||
*
|
||||
* Triggered by: Any code that reads/writes encrypted options (settings page, providers).
|
||||
* Dependencies: OpenSSL PHP extension, WordPress wp_salt() function.
|
||||
*
|
||||
* @see admin/class-admin-page.php — Uses this to store/retrieve API keys.
|
||||
*/
|
||||
class Autoblogger_Encryption {
|
||||
|
||||
private const METHOD = 'aes-256-cbc';
|
||||
|
||||
/**
|
||||
* Encrypt a plaintext string.
|
||||
*
|
||||
* @param string $plaintext The value to encrypt.
|
||||
*
|
||||
* @return string Base64-encoded ciphertext with IV prepended.
|
||||
*/
|
||||
public static function encrypt( string $plaintext ): string {
|
||||
if ( '' === $plaintext ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$key = self::get_key();
|
||||
$iv_len = (int) openssl_cipher_iv_length( self::METHOD );
|
||||
$iv = openssl_random_pseudo_bytes( $iv_len );
|
||||
|
||||
$ciphertext = openssl_encrypt( $plaintext, self::METHOD, $key, OPENSSL_RAW_DATA, $iv );
|
||||
if ( false === $ciphertext ) {
|
||||
Autoblogger_Logger::instance()->error( 'Encryption failed: ' . openssl_error_string(), 'encryption' );
|
||||
return '';
|
||||
}
|
||||
|
||||
// Prepend IV to ciphertext so we can extract it on decrypt.
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
return base64_encode( $iv . $ciphertext );
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a previously encrypted string.
|
||||
*
|
||||
* @param string $encrypted Base64-encoded ciphertext with IV prepended.
|
||||
*
|
||||
* @return string The original plaintext, or empty string on failure.
|
||||
*/
|
||||
public static function decrypt( string $encrypted ): string {
|
||||
if ( '' === $encrypted ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$key = self::get_key();
|
||||
$iv_len = (int) openssl_cipher_iv_length( self::METHOD );
|
||||
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
|
||||
$raw = base64_decode( $encrypted, true );
|
||||
if ( false === $raw || strlen( $raw ) <= $iv_len ) {
|
||||
Autoblogger_Logger::instance()->error( 'Decryption failed: invalid ciphertext format.', 'encryption' );
|
||||
return '';
|
||||
}
|
||||
|
||||
$iv = substr( $raw, 0, $iv_len );
|
||||
$ciphertext = substr( $raw, $iv_len );
|
||||
|
||||
$plaintext = openssl_decrypt( $ciphertext, self::METHOD, $key, OPENSSL_RAW_DATA, $iv );
|
||||
if ( false === $plaintext ) {
|
||||
Autoblogger_Logger::instance()->error( 'Decryption failed: ' . openssl_error_string(), 'encryption' );
|
||||
return '';
|
||||
}
|
||||
|
||||
return $plaintext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the encryption key from WordPress salts.
|
||||
*
|
||||
* @return string 32-byte key suitable for AES-256.
|
||||
*/
|
||||
private static function get_key(): string {
|
||||
return hash( 'sha256', wp_salt( 'auth' ), true );
|
||||
}
|
||||
}
|
||||
175
includes/core/class-chief-editor.php
Executable file
175
includes/core/class-chief-editor.php
Executable file
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Chief Editor agent — LLM-powered editorial review of generated content.
|
||||
*
|
||||
* Reviews articles for quality, accuracy, SEO, and tone before publishing.
|
||||
* Can approve, request revisions (and produce them), or reject content.
|
||||
* Rejected content is saved as a draft for human review.
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 5).
|
||||
* Dependencies: LLM_Provider_Interface, Cost_Tracker.
|
||||
*
|
||||
* @see core/class-content-generator.php — Produces the content we review.
|
||||
* @see core/class-publisher.php — Publishes approved content.
|
||||
* @see ARCHITECTURE.md — Data flow step 5.
|
||||
*/
|
||||
class Autoblogger_Chief_Editor {
|
||||
|
||||
private Autoblogger_LLM_Provider_Interface $llm;
|
||||
private Autoblogger_Cost_Tracker $cost_tracker;
|
||||
|
||||
public function __construct(
|
||||
Autoblogger_LLM_Provider_Interface $llm,
|
||||
Autoblogger_Cost_Tracker $cost_tracker
|
||||
) {
|
||||
$this->llm = $llm;
|
||||
$this->cost_tracker = $cost_tracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Review generated content and return an editorial verdict.
|
||||
*
|
||||
* The editor evaluates: content quality, factual tone, SEO elements,
|
||||
* readability, and alignment with the article idea. It can approve,
|
||||
* revise (and return revised content), or reject.
|
||||
*
|
||||
* Side effects: LLM API call(s), cost logging.
|
||||
*
|
||||
* @param string $content The generated HTML content.
|
||||
* @param Autoblogger_Article_Idea $idea The original article idea.
|
||||
*
|
||||
* @return Autoblogger_Editorial_Review
|
||||
*/
|
||||
public function review( string $content, Autoblogger_Article_Idea $idea ): Autoblogger_Editorial_Review {
|
||||
$model = get_option( 'autoblogger_editor_model', AUTOBLOGGER_DEFAULT_EDITOR_MODEL );
|
||||
$niche = get_option( 'autoblogger_niche_description', '' );
|
||||
|
||||
$system_prompt = $this->build_system_prompt( $niche );
|
||||
$user_prompt = $this->build_review_prompt( $content, $idea );
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $system_prompt ],
|
||||
[ 'role' => 'user', 'content' => $user_prompt ],
|
||||
],
|
||||
$model,
|
||||
[
|
||||
'temperature' => 0.3,
|
||||
'max_tokens' => 5000,
|
||||
'response_format' => [ 'type' => 'json_object' ],
|
||||
]
|
||||
);
|
||||
|
||||
$this->cost_tracker->log_api_call(
|
||||
null,
|
||||
'review',
|
||||
$this->llm->get_provider_name(),
|
||||
$response['model'],
|
||||
$response['prompt_tokens'],
|
||||
$response['completion_tokens']
|
||||
);
|
||||
|
||||
return $this->parse_review_response( $response['content'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $niche
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_system_prompt( string $niche ): string {
|
||||
$prompt = "You are a senior blog editor";
|
||||
if ( '' !== $niche ) {
|
||||
$prompt .= " specializing in {$niche} content";
|
||||
}
|
||||
$prompt .= ". Your job is to review article drafts before publication.\n\n";
|
||||
|
||||
$prompt .= "Evaluate the article on:\n";
|
||||
$prompt .= "1. QUALITY: Is the writing clear, engaging, and well-structured?\n";
|
||||
$prompt .= "2. ACCURACY: Does the content avoid making unsupported health/medical claims? Is the tone appropriately cautious for the topic?\n";
|
||||
$prompt .= "3. SEO: Are headings properly structured? Are target keywords naturally used?\n";
|
||||
$prompt .= "4. COMPLETENESS: Does it cover the key points? Does it have a proper intro and conclusion?\n";
|
||||
$prompt .= "5. READABILITY: Is sentence variety good? Are paragraphs appropriate length?\n\n";
|
||||
|
||||
$prompt .= "You must respond with JSON in this format:\n";
|
||||
$prompt .= "{\n";
|
||||
$prompt .= ' "verdict": "approved" | "revised" | "rejected",' . "\n";
|
||||
$prompt .= ' "quality_score": 0.0-1.0,' . "\n";
|
||||
$prompt .= ' "seo_score": 0.0-1.0,' . "\n";
|
||||
$prompt .= ' "issues": ["issue 1", "issue 2"],' . "\n";
|
||||
$prompt .= ' "notes": "Brief editorial notes",' . "\n";
|
||||
$prompt .= ' "revised_content": "Full revised HTML if verdict is revised, null otherwise"' . "\n";
|
||||
$prompt .= "}\n\n";
|
||||
|
||||
$prompt .= "Rules:\n";
|
||||
$prompt .= "- APPROVE if quality_score >= 0.7 and seo_score >= 0.6 and no critical issues\n";
|
||||
$prompt .= "- REVISE if fixable issues exist — you MUST provide the full revised HTML\n";
|
||||
$prompt .= "- REJECT only if the content is fundamentally flawed or off-topic\n";
|
||||
$prompt .= "- When revising, fix the issues yourself. Don't just describe them.\n";
|
||||
|
||||
return $prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $content
|
||||
* @param Autoblogger_Article_Idea $idea
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_review_prompt( string $content, Autoblogger_Article_Idea $idea ): string {
|
||||
return sprintf(
|
||||
"Review this article draft:\n\n" .
|
||||
"ORIGINAL BRIEF:\n" .
|
||||
"- Title: %s\n" .
|
||||
"- Topic: %s\n" .
|
||||
"- Type: %s\n" .
|
||||
"- Key points: %s\n" .
|
||||
"- Target keywords: %s\n\n" .
|
||||
"ARTICLE CONTENT:\n%s",
|
||||
$idea->get_suggested_title(),
|
||||
$idea->get_topic(),
|
||||
$idea->get_article_type(),
|
||||
implode( ', ', $idea->get_key_points() ),
|
||||
implode( ', ', $idea->get_target_keywords() ),
|
||||
$content
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the LLM's editorial review response.
|
||||
*
|
||||
* @param string $content JSON response from LLM.
|
||||
*
|
||||
* @return Autoblogger_Editorial_Review
|
||||
*/
|
||||
private function parse_review_response( string $content ): Autoblogger_Editorial_Review {
|
||||
$data = json_decode( $content, true );
|
||||
|
||||
if ( ! is_array( $data ) || ! isset( $data['verdict'] ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Chief editor response was not valid JSON. Defaulting to rejected.', 'editor' );
|
||||
return new Autoblogger_Editorial_Review( [
|
||||
'verdict' => 'rejected',
|
||||
'notes' => 'Editor response could not be parsed.',
|
||||
'quality_score' => 0.0,
|
||||
'seo_score' => 0.0,
|
||||
'issues' => [ 'Unparseable editor response' ],
|
||||
] );
|
||||
}
|
||||
|
||||
$verdict = sanitize_text_field( $data['verdict'] ?? 'rejected' );
|
||||
if ( ! in_array( $verdict, [ 'approved', 'revised', 'rejected' ], true ) ) {
|
||||
$verdict = 'rejected';
|
||||
}
|
||||
|
||||
return new Autoblogger_Editorial_Review( [
|
||||
'verdict' => $verdict,
|
||||
'notes' => sanitize_textarea_field( $data['notes'] ?? '' ),
|
||||
'revised_content' => isset( $data['revised_content'] ) ? wp_kses_post( $data['revised_content'] ) : null,
|
||||
'quality_score' => (float) ( $data['quality_score'] ?? 0.0 ),
|
||||
'seo_score' => (float) ( $data['seo_score'] ?? 0.0 ),
|
||||
'issues' => array_map( 'sanitize_text_field', $data['issues'] ?? [] ),
|
||||
] );
|
||||
}
|
||||
}
|
||||
293
includes/core/class-content-analyzer.php
Executable file
293
includes/core/class-content-analyzer.php
Executable file
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Analyzes collected source data using an LLM to detect recurring patterns:
|
||||
* questions people ask, complaints/pain points, and product comparisons.
|
||||
*
|
||||
* Uses a cheap model (configurable) to keep analysis costs low.
|
||||
* Batches source data into manageable chunks for the LLM context window.
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 2).
|
||||
* Dependencies: LLM_Provider_Interface, Cost_Tracker, WordPress $wpdb.
|
||||
*
|
||||
* @see providers/interface-llm-provider.php — LLM used for analysis.
|
||||
* @see core/class-cost-tracker.php — Logs API costs.
|
||||
* @see core/class-idea-scorer.php — Consumes analysis results.
|
||||
* @see ARCHITECTURE.md — Data flow step 2.
|
||||
*/
|
||||
class Autoblogger_Content_Analyzer {
|
||||
|
||||
private Autoblogger_LLM_Provider_Interface $llm;
|
||||
private Autoblogger_Cost_Tracker $cost_tracker;
|
||||
|
||||
public function __construct(
|
||||
Autoblogger_LLM_Provider_Interface $llm,
|
||||
Autoblogger_Cost_Tracker $cost_tracker
|
||||
) {
|
||||
$this->llm = $llm;
|
||||
$this->cost_tracker = $cost_tracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze recently collected source data for content patterns.
|
||||
*
|
||||
* Fetches unanalyzed data from the last 24 hours, batches it, sends to LLM
|
||||
* for pattern detection, and stores results in ab_analysis_results.
|
||||
*
|
||||
* Side effects: LLM API call, database reads/writes.
|
||||
*
|
||||
* @return Autoblogger_Analysis_Result[] Detected patterns.
|
||||
*/
|
||||
public function analyze_recent_data(): array {
|
||||
$source_items = $this->fetch_recent_source_data();
|
||||
|
||||
if ( empty( $source_items ) ) {
|
||||
Autoblogger_Logger::instance()->info( 'No new source data to analyze.', 'analyzer' );
|
||||
return [];
|
||||
}
|
||||
|
||||
$niche = get_option( 'autoblogger_niche_description', '' );
|
||||
$model = get_option( 'autoblogger_analysis_model', AUTOBLOGGER_DEFAULT_ANALYSIS_MODEL );
|
||||
|
||||
// Build the source data summary for the LLM (trim to avoid huge contexts).
|
||||
$summary = $this->build_source_summary( $source_items );
|
||||
|
||||
// Include past performance data for self-improvement.
|
||||
$performance_context = $this->get_performance_context();
|
||||
|
||||
$system_prompt = $this->build_system_prompt( $niche, $performance_context );
|
||||
$user_prompt = $this->build_user_prompt( $summary );
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $system_prompt ],
|
||||
[ 'role' => 'user', 'content' => $user_prompt ],
|
||||
],
|
||||
$model,
|
||||
[
|
||||
'temperature' => 0.3,
|
||||
'max_tokens' => 4000,
|
||||
'response_format' => [ 'type' => 'json_object' ],
|
||||
]
|
||||
);
|
||||
|
||||
// Log the cost.
|
||||
$this->cost_tracker->log_api_call(
|
||||
null,
|
||||
'analysis',
|
||||
$this->llm->get_provider_name(),
|
||||
$response['model'],
|
||||
$response['prompt_tokens'],
|
||||
$response['completion_tokens']
|
||||
);
|
||||
|
||||
// Parse LLM response into Analysis_Result objects.
|
||||
$results = $this->parse_analysis_response( $response['content'], $source_items );
|
||||
|
||||
// Store in database.
|
||||
$this->store_results( $results );
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch source data collected in the last 24 hours.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Raw database rows.
|
||||
*/
|
||||
private function fetch_recent_source_data(): array {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_source_data';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
return $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table} WHERE collected_at >= %s ORDER BY score DESC LIMIT 200",
|
||||
gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS )
|
||||
),
|
||||
ARRAY_A
|
||||
) ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a text summary of source data for the LLM to analyze.
|
||||
*
|
||||
* Prioritizes high-engagement content and keeps total text under ~8000 tokens.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $items Source data rows.
|
||||
*
|
||||
* @return string Formatted text summary.
|
||||
*/
|
||||
private function build_source_summary( array $items ): string {
|
||||
$parts = [];
|
||||
$char_limit = 30000; // Roughly ~7500 tokens.
|
||||
$current_chars = 0;
|
||||
|
||||
foreach ( $items as $item ) {
|
||||
$entry = sprintf(
|
||||
"[%s] r/%s | Score: %d | Comments: %d\nTitle: %s\n%s\n---",
|
||||
$item['source_type'],
|
||||
$item['subreddit'] ?? 'unknown',
|
||||
(int) $item['score'],
|
||||
(int) $item['comment_count'],
|
||||
$item['title'] ?? '(comment)',
|
||||
mb_substr( $item['content'] ?? '', 0, 500 )
|
||||
);
|
||||
|
||||
if ( $current_chars + strlen( $entry ) > $char_limit ) {
|
||||
break;
|
||||
}
|
||||
|
||||
$parts[] = $entry;
|
||||
$current_chars += strlen( $entry );
|
||||
}
|
||||
|
||||
return implode( "\n", $parts );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get past content performance data to feed into analysis for self-improvement.
|
||||
*
|
||||
* @return string Summary of what topics performed well/poorly.
|
||||
*/
|
||||
private function get_performance_context(): string {
|
||||
global $wpdb;
|
||||
$scores_table = $wpdb->prefix . 'autoblogger_content_scores';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$top_posts = $wpdb->get_results(
|
||||
"SELECT cs.post_id, cs.composite_score, p.post_title
|
||||
FROM {$scores_table} cs
|
||||
JOIN {$wpdb->posts} p ON p.ID = cs.post_id
|
||||
WHERE cs.composite_score > 0
|
||||
ORDER BY cs.composite_score DESC
|
||||
LIMIT 5",
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
if ( empty( $top_posts ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$lines = [ 'Top performing past articles (learn from these):' ];
|
||||
foreach ( $top_posts as $post ) {
|
||||
$lines[] = sprintf(
|
||||
'- "%s" (score: %.1f)',
|
||||
$post['post_title'],
|
||||
(float) $post['composite_score']
|
||||
);
|
||||
}
|
||||
|
||||
return implode( "\n", $lines );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the system prompt for content analysis.
|
||||
*
|
||||
* @param string $niche Niche description from settings.
|
||||
* @param string $performance_context Past performance data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_system_prompt( string $niche, string $performance_context ): string {
|
||||
$prompt = "You are a content strategist analyzing social media discussions to find article ideas for a blog";
|
||||
if ( '' !== $niche ) {
|
||||
$prompt .= " in the {$niche} niche";
|
||||
}
|
||||
$prompt .= ".\n\n";
|
||||
|
||||
$prompt .= "Analyze the provided social media posts and comments to identify:\n";
|
||||
$prompt .= "1. QUESTIONS: Recurring questions people ask (\"How do I...\", \"What is...\", \"Is it safe to...\")\n";
|
||||
$prompt .= "2. COMPLAINTS: Pain points, frustrations, or problems people report\n";
|
||||
$prompt .= "3. COMPARISONS: Product/method comparisons people discuss (\"X vs Y\", \"Which is better\")\n\n";
|
||||
|
||||
$prompt .= "For each pattern found, provide:\n";
|
||||
$prompt .= "- type: 'question', 'complaint', or 'comparison'\n";
|
||||
$prompt .= "- topic: A clear, specific topic description\n";
|
||||
$prompt .= "- summary: 1-2 sentence summary of the pattern\n";
|
||||
$prompt .= "- frequency: How many of the provided posts relate to this pattern\n";
|
||||
$prompt .= "- relevance_score: 0.0 to 1.0 indicating how relevant and article-worthy this topic is\n";
|
||||
$prompt .= "- suggested_title: A compelling blog post title for this topic\n";
|
||||
$prompt .= "- key_points: Array of 3-5 key points the article should cover\n";
|
||||
$prompt .= "- target_keywords: Array of SEO keywords for this topic\n\n";
|
||||
|
||||
if ( '' !== $performance_context ) {
|
||||
$prompt .= $performance_context . "\n\n";
|
||||
}
|
||||
|
||||
$prompt .= "Respond with valid JSON in this format:\n";
|
||||
$prompt .= '{"patterns": [{"type": "...", "topic": "...", "summary": "...", "frequency": N, "relevance_score": 0.X, "suggested_title": "...", "key_points": [...], "target_keywords": [...]}]}';
|
||||
|
||||
return $prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the user prompt containing the actual source data.
|
||||
*
|
||||
* @param string $summary Formatted source data summary.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_user_prompt( string $summary ): string {
|
||||
return "Here are the recent social media posts and comments to analyze:\n\n" . $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the LLM's JSON response into Analysis_Result objects.
|
||||
*
|
||||
* @param string $content LLM response content (JSON).
|
||||
* @param array<int, array<string, mixed>> $source_items Original source data for ID mapping.
|
||||
*
|
||||
* @return Autoblogger_Analysis_Result[]
|
||||
*/
|
||||
private function parse_analysis_response( string $content, array $source_items ): array {
|
||||
$data = json_decode( $content, true );
|
||||
if ( ! isset( $data['patterns'] ) || ! is_array( $data['patterns'] ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Analysis response was not valid JSON or missing patterns key.', 'analyzer' );
|
||||
return [];
|
||||
}
|
||||
|
||||
$source_ids = array_column( $source_items, 'id' );
|
||||
$results = [];
|
||||
|
||||
foreach ( $data['patterns'] as $pattern ) {
|
||||
$results[] = new Autoblogger_Analysis_Result( [
|
||||
'analysis_type' => sanitize_text_field( $pattern['type'] ?? 'question' ),
|
||||
'topic' => sanitize_text_field( $pattern['topic'] ?? '' ),
|
||||
'summary' => sanitize_textarea_field( $pattern['summary'] ?? '' ),
|
||||
'frequency' => absint( $pattern['frequency'] ?? 1 ),
|
||||
'relevance_score' => (float) ( $pattern['relevance_score'] ?? 0.0 ),
|
||||
'source_ids' => $source_ids,
|
||||
'analyzed_at' => current_time( 'mysql' ),
|
||||
'metadata' => [
|
||||
'suggested_title' => $pattern['suggested_title'] ?? '',
|
||||
'key_points' => $pattern['key_points'] ?? [],
|
||||
'target_keywords' => $pattern['target_keywords'] ?? [],
|
||||
],
|
||||
] );
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store analysis results in the database.
|
||||
*
|
||||
* Side effects: database inserts.
|
||||
*
|
||||
* @param Autoblogger_Analysis_Result[] $results
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function store_results( array $results ): void {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_analysis_results';
|
||||
|
||||
foreach ( $results as $result ) {
|
||||
$row = $result->to_db_row();
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->insert( $table, $row );
|
||||
}
|
||||
}
|
||||
}
|
||||
297
includes/core/class-content-generator.php
Executable file
297
includes/core/class-content-generator.php
Executable file
@@ -0,0 +1,297 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Writer agent — generates blog post content from article ideas.
|
||||
*
|
||||
* Supports two configurable pipeline modes:
|
||||
* - single_pass: One LLM call produces the complete article (cheaper, faster).
|
||||
* - multi_step: Outline → Draft → Polish pipeline (higher quality, more cost).
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 4).
|
||||
* Dependencies: LLM_Provider_Interface, Cost_Tracker.
|
||||
*
|
||||
* @see core/class-chief-editor.php — Reviews output of this class.
|
||||
* @see providers/interface-llm-provider.php — LLM used for generation.
|
||||
* @see ARCHITECTURE.md — Data flow step 4.
|
||||
*/
|
||||
class Autoblogger_Content_Generator {
|
||||
|
||||
private Autoblogger_LLM_Provider_Interface $llm;
|
||||
private Autoblogger_Cost_Tracker $cost_tracker;
|
||||
|
||||
public function __construct(
|
||||
Autoblogger_LLM_Provider_Interface $llm,
|
||||
Autoblogger_Cost_Tracker $cost_tracker
|
||||
) {
|
||||
$this->llm = $llm;
|
||||
$this->cost_tracker = $cost_tracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a blog post from an article idea.
|
||||
*
|
||||
* Reads pipeline mode from settings and dispatches to the appropriate method.
|
||||
*
|
||||
* Side effects: LLM API calls (1-3 depending on mode), cost logging.
|
||||
*
|
||||
* @param Autoblogger_Article_Idea $idea The scored idea to generate content for.
|
||||
*
|
||||
* @return string Generated HTML content.
|
||||
*
|
||||
* @throws \RuntimeException On generation failure.
|
||||
*/
|
||||
public function generate( Autoblogger_Article_Idea $idea ): string {
|
||||
$mode = get_option( 'autoblogger_writing_pipeline', 'multi_step' );
|
||||
|
||||
$request = new Autoblogger_Content_Request(
|
||||
$idea,
|
||||
$mode,
|
||||
get_option( 'autoblogger_tone', 'informational' ),
|
||||
absint( get_option( 'autoblogger_min_word_count', 800 ) ),
|
||||
absint( get_option( 'autoblogger_max_word_count', 2000 ) ),
|
||||
get_option( 'autoblogger_niche_description', '' ),
|
||||
json_decode( get_option( 'autoblogger_topic_exclusions', '[]' ), true ) ?: []
|
||||
);
|
||||
|
||||
if ( 'single_pass' === $mode ) {
|
||||
return $this->generate_single_pass( $request );
|
||||
}
|
||||
|
||||
return $this->generate_multi_step( $request );
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-pass generation: one LLM call produces the complete article.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
*
|
||||
* @return string Generated HTML content.
|
||||
*/
|
||||
private function generate_single_pass( Autoblogger_Content_Request $request ): string {
|
||||
$model = get_option( 'autoblogger_writing_model', AUTOBLOGGER_DEFAULT_WRITING_MODEL );
|
||||
$idea = $request->get_idea();
|
||||
|
||||
$system = $this->build_writer_system_prompt( $request );
|
||||
$user = $this->build_single_pass_prompt( $request );
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $system ],
|
||||
[ 'role' => 'user', 'content' => $user ],
|
||||
],
|
||||
$model,
|
||||
[
|
||||
'temperature' => 0.7,
|
||||
'max_tokens' => 4000,
|
||||
]
|
||||
);
|
||||
|
||||
$this->cost_tracker->log_api_call(
|
||||
null,
|
||||
'draft',
|
||||
$this->llm->get_provider_name(),
|
||||
$response['model'],
|
||||
$response['prompt_tokens'],
|
||||
$response['completion_tokens']
|
||||
);
|
||||
|
||||
return $response['content'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-step generation: Outline → Draft → Polish.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
*
|
||||
* @return string Generated HTML content.
|
||||
*/
|
||||
private function generate_multi_step( Autoblogger_Content_Request $request ): string {
|
||||
$model = get_option( 'autoblogger_writing_model', AUTOBLOGGER_DEFAULT_WRITING_MODEL );
|
||||
|
||||
// Step 1: Generate outline.
|
||||
$outline = $this->stage_outline( $request, $model );
|
||||
|
||||
// Step 2: Generate draft from outline.
|
||||
$draft = $this->stage_draft( $request, $outline, $model );
|
||||
|
||||
// Step 3: Polish the draft.
|
||||
$polished = $this->stage_polish( $request, $draft, $model );
|
||||
|
||||
return $polished;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-step stage 1: Generate an article outline.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
* @param string $model
|
||||
*
|
||||
* @return string The outline text.
|
||||
*/
|
||||
private function stage_outline( Autoblogger_Content_Request $request, string $model ): string {
|
||||
$idea = $request->get_idea();
|
||||
|
||||
$prompt = sprintf(
|
||||
"Create a detailed outline for a blog post titled: \"%s\"\n\n" .
|
||||
"Topic: %s\nArticle type: %s\n\nKey points to cover:\n%s\n\n" .
|
||||
"Target keywords: %s\n\n" .
|
||||
"The outline should have 4-6 main sections with bullet points under each. " .
|
||||
"Include an introduction hook and a conclusion with a call to action. " .
|
||||
"Word count target: %d-%d words.",
|
||||
$idea->get_suggested_title(),
|
||||
$idea->get_topic(),
|
||||
$idea->get_article_type(),
|
||||
implode( "\n- ", $idea->get_key_points() ),
|
||||
implode( ', ', $idea->get_target_keywords() ),
|
||||
$request->get_min_word_count(),
|
||||
$request->get_max_word_count()
|
||||
);
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $this->build_writer_system_prompt( $request ) ],
|
||||
[ 'role' => 'user', 'content' => $prompt ],
|
||||
],
|
||||
$model,
|
||||
[ 'temperature' => 0.5, 'max_tokens' => 1500 ]
|
||||
);
|
||||
|
||||
$this->cost_tracker->log_api_call(
|
||||
null, 'outline', $this->llm->get_provider_name(),
|
||||
$response['model'], $response['prompt_tokens'], $response['completion_tokens']
|
||||
);
|
||||
|
||||
return $response['content'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-step stage 2: Write the full draft from the outline.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
* @param string $outline
|
||||
* @param string $model
|
||||
*
|
||||
* @return string Draft HTML content.
|
||||
*/
|
||||
private function stage_draft( Autoblogger_Content_Request $request, string $outline, string $model ): string {
|
||||
$prompt = sprintf(
|
||||
"Using this outline, write the full blog post in HTML format.\n\n" .
|
||||
"OUTLINE:\n%s\n\n" .
|
||||
"Requirements:\n" .
|
||||
"- Write in a %s tone\n" .
|
||||
"- Target %d-%d words\n" .
|
||||
"- Use proper HTML headings (h2, h3), paragraphs, and lists\n" .
|
||||
"- Include an engaging introduction and strong conclusion\n" .
|
||||
"- Naturally incorporate these keywords: %s\n" .
|
||||
"- Do NOT include the title in the HTML (it will be set separately)\n" .
|
||||
"- Do NOT wrap in <html>, <head>, or <body> tags — just the article content",
|
||||
$outline,
|
||||
$request->get_tone(),
|
||||
$request->get_min_word_count(),
|
||||
$request->get_max_word_count(),
|
||||
implode( ', ', $request->get_idea()->get_target_keywords() )
|
||||
);
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $this->build_writer_system_prompt( $request ) ],
|
||||
[ 'role' => 'user', 'content' => $prompt ],
|
||||
],
|
||||
$model,
|
||||
[ 'temperature' => 0.7, 'max_tokens' => 4000 ]
|
||||
);
|
||||
|
||||
$this->cost_tracker->log_api_call(
|
||||
null, 'draft', $this->llm->get_provider_name(),
|
||||
$response['model'], $response['prompt_tokens'], $response['completion_tokens']
|
||||
);
|
||||
|
||||
return $response['content'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-step stage 3: Polish and refine the draft.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
* @param string $draft
|
||||
* @param string $model
|
||||
*
|
||||
* @return string Polished HTML content.
|
||||
*/
|
||||
private function stage_polish( Autoblogger_Content_Request $request, string $draft, string $model ): string {
|
||||
$prompt = "Review and polish this blog post draft. Improve:\n" .
|
||||
"1. Flow and readability\n" .
|
||||
"2. SEO optimization (headings, keyword placement)\n" .
|
||||
"3. Engagement (hooks, transitions, call-to-action)\n" .
|
||||
"4. Accuracy and clarity\n" .
|
||||
"5. Remove any filler or redundant sentences\n\n" .
|
||||
"Return the polished HTML content only. Do not add commentary.\n\n" .
|
||||
"DRAFT:\n" . $draft;
|
||||
|
||||
$response = $this->llm->send_chat_completion(
|
||||
[
|
||||
[ 'role' => 'system', 'content' => $this->build_writer_system_prompt( $request ) ],
|
||||
[ 'role' => 'user', 'content' => $prompt ],
|
||||
],
|
||||
$model,
|
||||
[ 'temperature' => 0.4, 'max_tokens' => 4000 ]
|
||||
);
|
||||
|
||||
$this->cost_tracker->log_api_call(
|
||||
null, 'polish', $this->llm->get_provider_name(),
|
||||
$response['model'], $response['prompt_tokens'], $response['completion_tokens']
|
||||
);
|
||||
|
||||
return $response['content'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the system prompt shared across all writing stages.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_writer_system_prompt( Autoblogger_Content_Request $request ): string {
|
||||
$niche = $request->get_niche_description();
|
||||
$prompt = "You are an expert blog writer";
|
||||
if ( '' !== $niche ) {
|
||||
$prompt .= " specializing in {$niche}";
|
||||
}
|
||||
$prompt .= ". Write well-researched, engaging, SEO-friendly content. ";
|
||||
$prompt .= "Use a {$request->get_tone()} tone. ";
|
||||
$prompt .= "Output HTML content only — no markdown, no code fences, no commentary.";
|
||||
return $prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the user prompt for single-pass generation.
|
||||
*
|
||||
* @param Autoblogger_Content_Request $request
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function build_single_pass_prompt( Autoblogger_Content_Request $request ): string {
|
||||
$idea = $request->get_idea();
|
||||
|
||||
return sprintf(
|
||||
"Write a complete blog post in HTML format.\n\n" .
|
||||
"Title: %s\nTopic: %s\nType: %s\n\nKey points:\n- %s\n\n" .
|
||||
"Keywords: %s\n\n" .
|
||||
"Requirements:\n" .
|
||||
"- %d-%d words\n" .
|
||||
"- Proper HTML (h2, h3, p, ul/li)\n" .
|
||||
"- Engaging intro, strong conclusion with CTA\n" .
|
||||
"- Do NOT include the title or <html>/<body> tags\n" .
|
||||
"- Output HTML only, no markdown or commentary",
|
||||
$idea->get_suggested_title(),
|
||||
$idea->get_topic(),
|
||||
$idea->get_article_type(),
|
||||
implode( "\n- ", $idea->get_key_points() ),
|
||||
implode( ', ', $idea->get_target_keywords() ),
|
||||
$request->get_min_word_count(),
|
||||
$request->get_max_word_count()
|
||||
);
|
||||
}
|
||||
}
|
||||
254
includes/core/class-cost-tracker.php
Executable file
254
includes/core/class-cost-tracker.php
Executable file
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Tracks all API costs, enforces monthly budget limits, and provides
|
||||
* cost reporting data for the admin dashboard.
|
||||
*
|
||||
* Every LLM API call in the plugin is logged through this class. The budget
|
||||
* enforcement is a hard stop — if the monthly budget is exceeded, no further
|
||||
* API calls are made until the next month or the budget is increased.
|
||||
*
|
||||
* Triggered by: Every class that makes an LLM API call (Content_Analyzer,
|
||||
* Content_Generator, Chief_Editor, Metrics_Collector).
|
||||
* Dependencies: WordPress $wpdb, Autoblogger_OpenRouter_Provider (for cost estimation).
|
||||
*
|
||||
* @see core/class-content-analyzer.php — Calls log_api_call() after analysis.
|
||||
* @see core/class-content-generator.php — Calls log_api_call() after each stage.
|
||||
* @see core/class-chief-editor.php — Calls log_api_call() after review.
|
||||
* @see admin/class-metrics-page.php — Displays cost data from this class.
|
||||
* @see ARCHITECTURE.md — ab_generation_log table schema.
|
||||
*/
|
||||
class Autoblogger_Cost_Tracker {
|
||||
|
||||
/**
|
||||
* Running cost for the current pipeline execution.
|
||||
* Reset each time the pipeline starts.
|
||||
*/
|
||||
private float $current_run_cost = 0.0;
|
||||
|
||||
/**
|
||||
* Unique identifier for the current pipeline run.
|
||||
* Used to link generation log entries to specific posts without timestamp-based guessing.
|
||||
*/
|
||||
private ?string $run_id = null;
|
||||
|
||||
/**
|
||||
* Set the run_id for the current pipeline execution.
|
||||
*
|
||||
* All subsequent log_api_call() entries will be tagged with this ID so
|
||||
* link_generation_logs() can attribute them to the correct post.
|
||||
*
|
||||
* @param string $run_id UUID or unique string for this run.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set_run_id( string $run_id ): void {
|
||||
$this->run_id = $run_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current run_id.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function get_run_id(): ?string {
|
||||
return $this->run_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an API call with its token usage and estimated cost.
|
||||
*
|
||||
* Side effects: database insert into ab_generation_log.
|
||||
*
|
||||
* @param int|null $post_id WordPress post ID (null during generation, set later).
|
||||
* @param string $stage Pipeline stage: 'analysis', 'outline', 'draft', 'polish', 'review'.
|
||||
* @param string $provider Provider name: 'OpenRouter'.
|
||||
* @param string $model Model identifier used.
|
||||
* @param int $prompt_tokens Input tokens consumed.
|
||||
* @param int $completion_tokens Output tokens generated.
|
||||
* @param string $response_status 'success', 'error', or 'timeout'.
|
||||
* @param string $error_message Error details if status is not 'success'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function log_api_call(
|
||||
?int $post_id,
|
||||
string $stage,
|
||||
string $provider,
|
||||
string $model,
|
||||
int $prompt_tokens,
|
||||
int $completion_tokens,
|
||||
string $response_status = 'success',
|
||||
string $error_message = ''
|
||||
): void {
|
||||
$llm = new Autoblogger_OpenRouter_Provider();
|
||||
$cost = $llm->estimate_cost( $model, $prompt_tokens, $completion_tokens );
|
||||
|
||||
$this->current_run_cost += $cost;
|
||||
|
||||
$log_entry = new Autoblogger_Generation_Log( [
|
||||
'post_id' => $post_id,
|
||||
'run_id' => $this->run_id,
|
||||
'stage' => $stage,
|
||||
'provider' => $provider,
|
||||
'model' => $model,
|
||||
'prompt_tokens' => $prompt_tokens,
|
||||
'completion_tokens' => $completion_tokens,
|
||||
'estimated_cost' => $cost,
|
||||
'response_status' => $response_status,
|
||||
'error_message' => $error_message,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
] );
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_generation_log';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->insert( $table, $log_entry->to_db_row() );
|
||||
|
||||
if ( false === $wpdb->insert_id ) {
|
||||
Autoblogger_Logger::instance()->error( 'Failed to log API call: ' . $wpdb->last_error, 'cost-tracker' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the monthly budget has been exceeded.
|
||||
*
|
||||
* Uses round() to 4 decimal places to avoid floating-point comparison edge
|
||||
* cases where e.g. $49.999999997 could be treated as >= $50.00.
|
||||
*
|
||||
* @return bool True if monthly spend >= configured budget.
|
||||
*/
|
||||
public function is_budget_exceeded(): bool {
|
||||
$budget = (float) get_option( 'autoblogger_monthly_budget_usd', 50.00 );
|
||||
if ( $budget <= 0 ) {
|
||||
// Budget of 0 means no limit.
|
||||
return false;
|
||||
}
|
||||
|
||||
$monthly_spend = $this->get_monthly_spend();
|
||||
|
||||
// Round to 4 decimal places (0.01 cent precision) to avoid
|
||||
// floating-point representation artifacts triggering false positives.
|
||||
return round( $monthly_spend, 4 ) >= round( $budget, 4 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total estimated spend for the current calendar month.
|
||||
*
|
||||
* @return float Total USD spend this month.
|
||||
*/
|
||||
public function get_monthly_spend(): float {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_generation_log';
|
||||
|
||||
$first_of_month = gmdate( 'Y-m-01 00:00:00' );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$result = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT COALESCE(SUM(estimated_cost), 0) FROM {$table} WHERE created_at >= %s AND response_status = 'success'",
|
||||
$first_of_month
|
||||
)
|
||||
);
|
||||
|
||||
return (float) $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cost accumulated during the current pipeline run.
|
||||
*
|
||||
* @return float USD cost for this run.
|
||||
*/
|
||||
public function get_current_run_cost(): float {
|
||||
return $this->current_run_cost;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get daily spend for the last N days (for the metrics dashboard chart).
|
||||
*
|
||||
* @param int $days Number of days to look back.
|
||||
*
|
||||
* @return array<string, float> Associative array of date => total_cost.
|
||||
*/
|
||||
public function get_daily_spend( int $days = 30 ): array {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_generation_log';
|
||||
|
||||
$start_date = gmdate( 'Y-m-d', time() - ( $days * DAY_IN_SECONDS ) );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT DATE(created_at) as day, SUM(estimated_cost) as total_cost
|
||||
FROM {$table}
|
||||
WHERE created_at >= %s AND response_status = 'success'
|
||||
GROUP BY DATE(created_at)
|
||||
ORDER BY day ASC",
|
||||
$start_date . ' 00:00:00'
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
$daily = [];
|
||||
foreach ( ( $results ?: [] ) as $row ) {
|
||||
$daily[ $row['day'] ] = (float) $row['total_cost'];
|
||||
}
|
||||
|
||||
return $daily;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get spend breakdown by pipeline stage for a given period.
|
||||
*
|
||||
* @param string $start_date Start date (Y-m-d).
|
||||
* @param string $end_date End date (Y-m-d).
|
||||
*
|
||||
* @return array<string, array{cost: float, tokens: int, calls: int}> Breakdown by stage.
|
||||
*/
|
||||
public function get_spend_by_stage( string $start_date, string $end_date ): array {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_generation_log';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$results = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT stage,
|
||||
SUM(estimated_cost) as total_cost,
|
||||
SUM(prompt_tokens + completion_tokens) as total_tokens,
|
||||
COUNT(*) as call_count
|
||||
FROM {$table}
|
||||
WHERE created_at BETWEEN %s AND %s AND response_status = 'success'
|
||||
GROUP BY stage",
|
||||
$start_date . ' 00:00:00',
|
||||
$end_date . ' 23:59:59'
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
$breakdown = [];
|
||||
foreach ( ( $results ?: [] ) as $row ) {
|
||||
$breakdown[ $row['stage'] ] = [
|
||||
'cost' => (float) $row['total_cost'],
|
||||
'tokens' => (int) $row['total_tokens'],
|
||||
'calls' => (int) $row['call_count'],
|
||||
];
|
||||
}
|
||||
|
||||
return $breakdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get budget utilization percentage for the current month.
|
||||
*
|
||||
* @return float Percentage (0-100+). Can exceed 100 if overspent.
|
||||
*/
|
||||
public function get_budget_utilization(): float {
|
||||
$budget = (float) get_option( 'autoblogger_monthly_budget_usd', 50.00 );
|
||||
if ( $budget <= 0 ) {
|
||||
return 0.0;
|
||||
}
|
||||
return ( $this->get_monthly_spend() / $budget ) * 100.0;
|
||||
}
|
||||
}
|
||||
202
includes/core/class-ga4-client.php
Executable file
202
includes/core/class-ga4-client.php
Executable file
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Google Analytics 4 API client for fetching post performance metrics.
|
||||
*
|
||||
* Handles OAuth2 service account authentication and the GA4 Data API.
|
||||
* Decoupled from metrics collection logic for testability and reusability.
|
||||
*
|
||||
* Triggered by: Autoblogger_Metrics_Collector::fetch_ga4_data() calls methods here.
|
||||
* Dependencies: Autoblogger_Encryption (for credentials decryption), wp_remote_post/get().
|
||||
*
|
||||
* @see core/class-metrics-collector.php — Instantiates this class.
|
||||
* @see ARCHITECTURE.md — External API integrations table.
|
||||
*/
|
||||
class Autoblogger_GA4_Client {
|
||||
|
||||
/**
|
||||
* Fetch Google Analytics 4 data for given posts.
|
||||
*
|
||||
* Returns empty data if GA4 is not configured or API call fails.
|
||||
*
|
||||
* Side effects: HTTP request to GA4 API (if configured).
|
||||
*
|
||||
* @param \WP_Post[] $posts
|
||||
*
|
||||
* @return array<int, array{pageviews: int, avg_time_on_page: float, bounce_rate: float}>
|
||||
*/
|
||||
public function fetch_data( array $posts ): array {
|
||||
$property_id = get_option( 'autoblogger_ga4_property_id', '' );
|
||||
if ( '' === $property_id ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$credentials_encrypted = get_option( 'autoblogger_ga4_credentials_json', '' );
|
||||
if ( '' === $credentials_encrypted ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$credentials = Autoblogger_Encryption::decrypt( $credentials_encrypted );
|
||||
if ( '' === $credentials ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Build page paths for the GA4 query.
|
||||
$page_paths = [];
|
||||
$path_to_id = [];
|
||||
foreach ( $posts as $post ) {
|
||||
$path = wp_parse_url( get_permalink( $post->ID ), PHP_URL_PATH );
|
||||
if ( $path ) {
|
||||
$page_paths[] = $path;
|
||||
$path_to_id[ $path ] = (int) $post->ID;
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $page_paths ) ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// GA4 Data API request.
|
||||
// Using the REST API directly since we don't want a full Google SDK dependency.
|
||||
$access_token = $this->get_access_token( $credentials );
|
||||
if ( '' === $access_token ) {
|
||||
Autoblogger_Logger::instance()->error( 'GA4: Failed to get access token. Possible causes: invalid service account JSON, expired or revoked private key, or network error reaching oauth2.googleapis.com. Verify credentials in AutoBlogger → Settings.', 'ga4' );
|
||||
return [];
|
||||
}
|
||||
|
||||
$request_body = [
|
||||
'dateRanges' => [ [ 'startDate' => '30daysAgo', 'endDate' => 'today' ] ],
|
||||
'dimensions' => [ [ 'name' => 'pagePath' ] ],
|
||||
'metrics' => [
|
||||
[ 'name' => 'screenPageViews' ],
|
||||
[ 'name' => 'averageSessionDuration' ],
|
||||
[ 'name' => 'bounceRate' ],
|
||||
],
|
||||
'dimensionFilter' => [
|
||||
'filter' => [
|
||||
'fieldName' => 'pagePath',
|
||||
'inListFilter' => [ 'values' => $page_paths ],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = wp_remote_post(
|
||||
"https://analyticsdata.googleapis.com/v1beta/properties/{$property_id}:runReport",
|
||||
[
|
||||
'timeout' => 30,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $access_token,
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'body' => wp_json_encode( $request_body ),
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'GA4 API request failed (WP HTTP error): ' . $response->get_error_message(), 'ga4' );
|
||||
return [];
|
||||
}
|
||||
|
||||
$ga4_status = wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $ga4_status ) {
|
||||
$ga4_body = wp_remote_retrieve_body( $response );
|
||||
Autoblogger_Logger::instance()->error(
|
||||
sprintf( 'GA4 API request failed (HTTP %d): %s', $ga4_status, substr( $ga4_body, 0, 500 ) ),
|
||||
'ga4'
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
$results = [];
|
||||
|
||||
foreach ( ( $data['rows'] ?? [] ) as $row ) {
|
||||
$path = $row['dimensionValues'][0]['value'] ?? '';
|
||||
if ( isset( $path_to_id[ $path ] ) ) {
|
||||
$results[ $path_to_id[ $path ] ] = [
|
||||
'pageviews' => (int) ( $row['metricValues'][0]['value'] ?? 0 ),
|
||||
'avg_time_on_page' => (float) ( $row['metricValues'][1]['value'] ?? 0 ),
|
||||
'bounce_rate' => (float) ( $row['metricValues'][2]['value'] ?? 0 ),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a GA4 access token from service account credentials.
|
||||
*
|
||||
* @param string $credentials_json JSON service account key.
|
||||
*
|
||||
* @return string Access token, or empty string on failure.
|
||||
*/
|
||||
private function get_access_token( string $credentials_json ): string {
|
||||
$creds = json_decode( $credentials_json, true );
|
||||
if ( ! isset( $creds['client_email'], $creds['private_key'] ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Build JWT for service account auth.
|
||||
$now = time();
|
||||
$header = wp_json_encode( [ 'alg' => 'RS256', 'typ' => 'JWT' ] );
|
||||
$claim = wp_json_encode( [
|
||||
'iss' => $creds['client_email'],
|
||||
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
|
||||
'aud' => 'https://oauth2.googleapis.com/token',
|
||||
'exp' => $now + 3600,
|
||||
'iat' => $now,
|
||||
] );
|
||||
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
$base64_header = rtrim( strtr( base64_encode( $header ), '+/', '-_' ), '=' );
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
$base64_claim = rtrim( strtr( base64_encode( $claim ), '+/', '-_' ), '=' );
|
||||
|
||||
$signing_input = $base64_header . '.' . $base64_claim;
|
||||
$signature = '';
|
||||
|
||||
$key = openssl_pkey_get_private( $creds['private_key'] );
|
||||
if ( false === $key ) {
|
||||
Autoblogger_Logger::instance()->error( 'GA4: Failed to parse private key from service account credentials. The key may be malformed or the OpenSSL extension may be misconfigured.', 'ga4' );
|
||||
return '';
|
||||
}
|
||||
|
||||
openssl_sign( $signing_input, $signature, $key, OPENSSL_ALGO_SHA256 );
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
$base64_signature = rtrim( strtr( base64_encode( $signature ), '+/', '-_' ), '=' );
|
||||
|
||||
$jwt = $signing_input . '.' . $base64_signature;
|
||||
|
||||
$response = wp_remote_post(
|
||||
'https://oauth2.googleapis.com/token',
|
||||
[
|
||||
'timeout' => 15,
|
||||
'body' => [
|
||||
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
||||
'assertion' => $jwt,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'GA4: OAuth token exchange failed (WP HTTP error): ' . $response->get_error_message(), 'ga4' );
|
||||
return '';
|
||||
}
|
||||
|
||||
$token_status = wp_remote_retrieve_response_code( $response );
|
||||
$data = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
|
||||
if ( 200 !== $token_status || ! isset( $data['access_token'] ) ) {
|
||||
$error_desc = $data['error_description'] ?? $data['error'] ?? 'unknown';
|
||||
Autoblogger_Logger::instance()->error(
|
||||
sprintf( 'GA4: OAuth token exchange failed (HTTP %d): %s', $token_status, $error_desc ),
|
||||
'ga4'
|
||||
);
|
||||
return '';
|
||||
}
|
||||
|
||||
return $data['access_token'];
|
||||
}
|
||||
}
|
||||
142
includes/core/class-idea-scorer.php
Executable file
142
includes/core/class-idea-scorer.php
Executable file
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Ranks and deduplicates article ideas from analysis results.
|
||||
*
|
||||
* Compares against existing published posts to avoid topic overlap,
|
||||
* scores ideas by relevance, frequency, and freshness, then returns
|
||||
* the top N ideas matching the daily target.
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 3).
|
||||
* Dependencies: WordPress $wpdb, WP_Query.
|
||||
*
|
||||
* @see core/class-content-analyzer.php — Produces the analysis results we consume.
|
||||
* @see core/class-content-generator.php — Consumes the ranked ideas we produce.
|
||||
* @see ARCHITECTURE.md — Data flow step 3.
|
||||
*/
|
||||
class Autoblogger_Idea_Scorer {
|
||||
|
||||
/**
|
||||
* Score, deduplicate, and rank article ideas.
|
||||
*
|
||||
* @param Autoblogger_Analysis_Result[] $analysis_results Raw analysis output.
|
||||
* @param int $target_count Number of ideas to return.
|
||||
*
|
||||
* @return Autoblogger_Article_Idea[] Top-ranked ideas, sorted by score descending.
|
||||
*/
|
||||
public function score_and_rank( array $analysis_results, int $target_count ): array {
|
||||
$exclusions = json_decode( get_option( 'autoblogger_topic_exclusions', '[]' ), true ) ?: [];
|
||||
$ideas = [];
|
||||
|
||||
foreach ( $analysis_results as $result ) {
|
||||
// Skip excluded topics.
|
||||
if ( $this->is_excluded( $result->get_topic(), $exclusions ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if we've already published something very similar.
|
||||
if ( $this->has_similar_post( $result->get_topic() ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$metadata = $result->get_metadata() ?? [];
|
||||
|
||||
$ideas[] = new Autoblogger_Article_Idea( [
|
||||
'topic' => $result->get_topic(),
|
||||
'article_type' => $this->map_type( $result->get_analysis_type() ),
|
||||
'suggested_title' => $metadata['suggested_title'] ?? $result->get_topic(),
|
||||
'summary' => $result->get_summary() ?? '',
|
||||
'score' => $this->compute_score( $result ),
|
||||
'analysis_id' => $result->get_id(),
|
||||
'source_ids' => $result->get_source_ids(),
|
||||
'key_points' => $metadata['key_points'] ?? [],
|
||||
'target_keywords' => $metadata['target_keywords'] ?? [],
|
||||
] );
|
||||
}
|
||||
|
||||
// Sort by score descending.
|
||||
usort( $ideas, static function ( Autoblogger_Article_Idea $a, Autoblogger_Article_Idea $b ): int {
|
||||
return $b->get_score() <=> $a->get_score();
|
||||
} );
|
||||
|
||||
return array_slice( $ideas, 0, $target_count );
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute a composite score for an analysis result.
|
||||
*
|
||||
* Factors: LLM relevance score (50%), frequency (30%), recency bonus (20%).
|
||||
*
|
||||
* @param Autoblogger_Analysis_Result $result
|
||||
*
|
||||
* @return float Score between 0 and 1.
|
||||
*/
|
||||
private function compute_score( Autoblogger_Analysis_Result $result ): float {
|
||||
$relevance = min( $result->get_relevance_score(), 1.0 );
|
||||
$frequency = min( $result->get_frequency() / 10.0, 1.0 );
|
||||
|
||||
// Recency: analyzed within last 24h gets full bonus.
|
||||
$hours_ago = ( time() - strtotime( $result->get_analyzed_at() ) ) / 3600.0;
|
||||
$recency = max( 0.0, 1.0 - ( $hours_ago / 48.0 ) );
|
||||
|
||||
return ( $relevance * 0.5 ) + ( $frequency * 0.3 ) + ( $recency * 0.2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a topic should be excluded based on user-configured exclusions.
|
||||
*
|
||||
* @param string $topic Topic text.
|
||||
* @param string[] $exclusions List of excluded terms/phrases.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function is_excluded( string $topic, array $exclusions ): bool {
|
||||
$topic_lower = strtolower( $topic );
|
||||
foreach ( $exclusions as $exclusion ) {
|
||||
if ( false !== strpos( $topic_lower, strtolower( trim( $exclusion ) ) ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a substantially similar post already exists.
|
||||
*
|
||||
* Uses a simple keyword overlap check against existing published post titles.
|
||||
*
|
||||
* @param string $topic Topic to check.
|
||||
*
|
||||
* @return bool True if a similar post exists.
|
||||
*/
|
||||
private function has_similar_post( string $topic ): bool {
|
||||
$query = new \WP_Query( [
|
||||
'post_type' => 'post',
|
||||
'post_status' => [ 'publish', 'draft', 'pending' ],
|
||||
'meta_key' => '_autoblogger_generated',
|
||||
'meta_value' => '1',
|
||||
's' => $topic,
|
||||
'posts_per_page' => 1,
|
||||
'fields' => 'ids',
|
||||
] );
|
||||
|
||||
return $query->found_posts > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map analysis type to a reader-friendly article type.
|
||||
*
|
||||
* @param string $analysis_type 'question', 'complaint', 'comparison'.
|
||||
*
|
||||
* @return string Article type label.
|
||||
*/
|
||||
private function map_type( string $analysis_type ): string {
|
||||
$map = [
|
||||
'question' => 'guide',
|
||||
'complaint' => 'solution',
|
||||
'comparison' => 'comparison',
|
||||
];
|
||||
return $map[ $analysis_type ] ?? 'article';
|
||||
}
|
||||
}
|
||||
220
includes/core/class-logger.php
Executable file
220
includes/core/class-logger.php
Executable file
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Structured logging with configurable verbosity levels.
|
||||
*
|
||||
* Writes log entries to a custom database table and optionally forwards
|
||||
* to PHP's error_log() for server-level monitoring. The log level is
|
||||
* user-configurable via Settings → AutoBlogger → General.
|
||||
*
|
||||
* Levels (ascending verbosity): error → warning → info → debug.
|
||||
* Setting the level to "info" captures error, warning, and info — not debug.
|
||||
*
|
||||
* Triggered by: Every class that previously called error_log() directly.
|
||||
* Dependencies: WordPress $wpdb.
|
||||
*
|
||||
* @see admin/class-log-viewer.php — Reads and displays log entries.
|
||||
* @see class-activator.php — Creates the ab_event_log table.
|
||||
* @see ARCHITECTURE.md — Logging architecture section.
|
||||
*/
|
||||
class Autoblogger_Logger {
|
||||
|
||||
/** Log levels, lower = more severe. */
|
||||
public const LEVEL_ERROR = 0;
|
||||
public const LEVEL_WARNING = 1;
|
||||
public const LEVEL_INFO = 2;
|
||||
public const LEVEL_DEBUG = 3;
|
||||
|
||||
private const LEVEL_MAP = [
|
||||
'error' => self::LEVEL_ERROR,
|
||||
'warning' => self::LEVEL_WARNING,
|
||||
'info' => self::LEVEL_INFO,
|
||||
'debug' => self::LEVEL_DEBUG,
|
||||
];
|
||||
|
||||
private const LEVEL_LABELS = [
|
||||
self::LEVEL_ERROR => 'error',
|
||||
self::LEVEL_WARNING => 'warning',
|
||||
self::LEVEL_INFO => 'info',
|
||||
self::LEVEL_DEBUG => 'debug',
|
||||
];
|
||||
|
||||
/** Singleton instance. */
|
||||
private static ?self $instance = null;
|
||||
|
||||
/** Cached numeric threshold from settings. */
|
||||
private int $threshold;
|
||||
|
||||
private function __construct() {
|
||||
$setting = get_option( 'autoblogger_log_level', 'info' );
|
||||
$this->threshold = self::LEVEL_MAP[ $setting ] ?? self::LEVEL_INFO;
|
||||
}
|
||||
|
||||
/** Get the singleton logger instance. */
|
||||
public static function instance(): self {
|
||||
if ( null === self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an error (always captured unless logging is completely off).
|
||||
*
|
||||
* @param string $message Human-readable description.
|
||||
* @param string $context Origin class or pipeline stage.
|
||||
* @param array<string, mixed> $meta Optional structured data.
|
||||
*/
|
||||
public function error( string $message, string $context = '', array $meta = [] ): void {
|
||||
$this->log( self::LEVEL_ERROR, $message, $context, $meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a warning (budget approaching, retries, degraded behavior).
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $context
|
||||
* @param array<string, mixed> $meta
|
||||
*/
|
||||
public function warning( string $message, string $context = '', array $meta = [] ): void {
|
||||
$this->log( self::LEVEL_WARNING, $message, $context, $meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an informational event (pipeline start/stop, articles generated).
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $context
|
||||
* @param array<string, mixed> $meta
|
||||
*/
|
||||
public function info( string $message, string $context = '', array $meta = [] ): void {
|
||||
$this->log( self::LEVEL_INFO, $message, $context, $meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Log debug detail (API token counts, timing, intermediate values).
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $context
|
||||
* @param array<string, mixed> $meta
|
||||
*/
|
||||
public function debug( string $message, string $context = '', array $meta = [] ): void {
|
||||
$this->log( self::LEVEL_DEBUG, $message, $context, $meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Core logging method. Writes to DB if level meets threshold.
|
||||
*
|
||||
* Side effects: database INSERT, optionally PHP error_log().
|
||||
*
|
||||
* @param int $level Numeric level constant.
|
||||
* @param string $message Human-readable message.
|
||||
* @param string $context Origin (class/stage).
|
||||
* @param array<string, mixed> $meta Structured data.
|
||||
*/
|
||||
private function log( int $level, string $message, string $context, array $meta ): void {
|
||||
if ( $level > $this->threshold ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$label = self::LEVEL_LABELS[ $level ] ?? 'info';
|
||||
|
||||
// Always forward errors to PHP error_log for server-level monitoring.
|
||||
if ( $level <= self::LEVEL_WARNING ) {
|
||||
error_log( sprintf( '[AutoBlogger][%s] %s — %s', strtoupper( $label ), $context, $message ) );
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_event_log';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->insert( $table, [
|
||||
'level' => $label,
|
||||
'context' => substr( $context, 0, 100 ),
|
||||
'message' => substr( $message, 0, 2000 ),
|
||||
'meta_json' => ! empty( $meta ) ? wp_json_encode( $meta ) : null,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Query log entries for the admin viewer.
|
||||
*
|
||||
* @param string $level_filter Filter by level: 'all', 'error', 'warning', 'info', 'debug'.
|
||||
* @param string $search Search within message/context.
|
||||
* @param int $page Page number (1-based).
|
||||
* @param int $per_page Results per page.
|
||||
*
|
||||
* @return array{rows: array, total: int}
|
||||
*/
|
||||
public static function query(
|
||||
string $level_filter = 'all',
|
||||
string $search = '',
|
||||
int $page = 1,
|
||||
int $per_page = 50
|
||||
): array {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_event_log';
|
||||
$where = [];
|
||||
$params = [];
|
||||
|
||||
if ( 'all' !== $level_filter && isset( self::LEVEL_MAP[ $level_filter ] ) ) {
|
||||
$where[] = 'level = %s';
|
||||
$params[] = $level_filter;
|
||||
}
|
||||
|
||||
if ( '' !== $search ) {
|
||||
$like = '%' . $wpdb->esc_like( $search ) . '%';
|
||||
$where[] = '(message LIKE %s OR context LIKE %s)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
|
||||
$where_sql = ! empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : '';
|
||||
$offset = ( $page - 1 ) * $per_page;
|
||||
|
||||
// Total count.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$total = (int) $wpdb->get_var(
|
||||
empty( $params )
|
||||
? "SELECT COUNT(*) FROM {$table} {$where_sql}"
|
||||
: $wpdb->prepare( "SELECT COUNT(*) FROM {$table} {$where_sql}", ...$params )
|
||||
);
|
||||
|
||||
// Rows.
|
||||
$query_params = $params;
|
||||
$query_params[] = $per_page;
|
||||
$query_params[] = $offset;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table} {$where_sql} ORDER BY created_at DESC LIMIT %d OFFSET %d",
|
||||
...$query_params
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
return [ 'rows' => $rows ?: [], 'total' => $total ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune log entries older than a given number of days.
|
||||
*
|
||||
* @param int $days Keep entries from the last N days.
|
||||
* @return int Number of rows deleted.
|
||||
*/
|
||||
public static function prune( int $days = 30 ): int {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_event_log';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
return (int) $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$table} WHERE created_at < %s",
|
||||
gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
179
includes/core/class-metrics-collector.php
Executable file
179
includes/core/class-metrics-collector.php
Executable file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Collects post performance metrics from WordPress native data and Google Analytics 4.
|
||||
*
|
||||
* Runs on a separate cron schedule (every 6 hours) to gather pageviews, bounce rate,
|
||||
* time on page, and comments for AutoBlogger-generated posts. Computes a composite
|
||||
* "content score" that feeds back into the analysis engine for self-improvement.
|
||||
*
|
||||
* Triggered by: WP-Cron hook `autoblogger_collect_metrics` (every 6 hours).
|
||||
* Dependencies: WordPress $wpdb, Autoblogger_GA4_Client (for GA4 API calls).
|
||||
*
|
||||
* @see core/class-ga4-client.php — Handles GA4 API authentication and requests.
|
||||
* @see core/class-content-analyzer.php — Reads scores for self-improvement loop.
|
||||
* @see admin/class-metrics-page.php — Displays collected metrics.
|
||||
* @see ARCHITECTURE.md — Data flow step 7.
|
||||
*/
|
||||
class Autoblogger_Metrics_Collector {
|
||||
|
||||
/**
|
||||
* Collect metrics for all AutoBlogger-generated posts.
|
||||
*
|
||||
* Gathers WordPress native metrics (comments) and GA4 data (if configured),
|
||||
* then computes composite scores.
|
||||
*
|
||||
* Side effects: GA4 API calls (if configured), database writes.
|
||||
*
|
||||
* @return int Number of posts scored.
|
||||
*/
|
||||
public function collect_all(): int {
|
||||
$posts = $this->get_generated_posts();
|
||||
if ( empty( $posts ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$ga4_client = new Autoblogger_GA4_Client();
|
||||
$ga4_data = $ga4_client->fetch_data( $posts );
|
||||
$scored = 0;
|
||||
|
||||
foreach ( $posts as $post ) {
|
||||
$post_id = (int) $post->ID;
|
||||
$wp_metrics = $this->get_wp_native_metrics( $post_id );
|
||||
|
||||
// Skip posts that were deleted between the query and metrics collection.
|
||||
if ( null === $wp_metrics ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ga_metrics = $ga4_data[ $post_id ] ?? [];
|
||||
|
||||
$score = $this->compute_composite_score( $wp_metrics, $ga_metrics, $post );
|
||||
$this->store_score( $post_id, $wp_metrics, $ga_metrics, $score );
|
||||
$scored++;
|
||||
}
|
||||
|
||||
Autoblogger_Logger::instance()->info( sprintf( 'Metrics collected for %d posts.', $scored ), 'metrics' );
|
||||
return $scored;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all AutoBlogger-generated published posts.
|
||||
*
|
||||
* @return \WP_Post[]
|
||||
*/
|
||||
private function get_generated_posts(): array {
|
||||
$query = new \WP_Query( [
|
||||
'post_type' => 'post',
|
||||
'post_status' => 'publish',
|
||||
'meta_key' => '_autoblogger_generated',
|
||||
'meta_value' => '1',
|
||||
'posts_per_page' => 100,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
] );
|
||||
|
||||
return $query->posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get WordPress native metrics for a post.
|
||||
*
|
||||
* @param int $post_id
|
||||
*
|
||||
* @return array{comment_count: int, days_published: int}|null Null if post no longer exists.
|
||||
*/
|
||||
private function get_wp_native_metrics( int $post_id ): ?array {
|
||||
$post = get_post( $post_id );
|
||||
|
||||
// Post may have been deleted between the WP_Query and this call.
|
||||
if ( null === $post ) {
|
||||
Autoblogger_Logger::instance()->debug( sprintf( 'Metrics: Post ID %d no longer exists, skipping.', $post_id ), 'metrics' );
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'comment_count' => (int) ( $post->comment_count ?? 0 ),
|
||||
'days_published' => max( 1, (int) ( ( time() - strtotime( $post->post_date ) ) / DAY_IN_SECONDS ) ),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Compute a composite content score (0-100) from multiple metrics.
|
||||
*
|
||||
* @param array $wp_metrics WordPress native metrics.
|
||||
* @param array $ga_metrics GA4 metrics (may be empty).
|
||||
* @param \WP_Post $post The post object.
|
||||
*
|
||||
* @return array{score: float, factors: array<string, float>}
|
||||
*/
|
||||
private function compute_composite_score( array $wp_metrics, array $ga_metrics, \WP_Post $post ): array {
|
||||
$factors = [];
|
||||
|
||||
// Comment engagement (0-25 points).
|
||||
$comments_per_day = $wp_metrics['comment_count'] / max( 1, $wp_metrics['days_published'] );
|
||||
$factors['comments'] = min( 25.0, $comments_per_day * 25.0 );
|
||||
|
||||
// Pageview performance (0-30 points, if GA4 available).
|
||||
if ( isset( $ga_metrics['pageviews'] ) ) {
|
||||
$views_per_day = $ga_metrics['pageviews'] / max( 1, $wp_metrics['days_published'] );
|
||||
$factors['pageviews'] = min( 30.0, $views_per_day * 3.0 );
|
||||
} else {
|
||||
$factors['pageviews'] = 0.0;
|
||||
}
|
||||
|
||||
// Time on page (0-25 points, if GA4 available).
|
||||
if ( isset( $ga_metrics['avg_time_on_page'] ) ) {
|
||||
// 3+ minutes is excellent for a blog post.
|
||||
$factors['time_on_page'] = min( 25.0, ( $ga_metrics['avg_time_on_page'] / 180.0 ) * 25.0 );
|
||||
} else {
|
||||
$factors['time_on_page'] = 0.0;
|
||||
}
|
||||
|
||||
// Low bounce rate bonus (0-20 points, if GA4 available).
|
||||
if ( isset( $ga_metrics['bounce_rate'] ) ) {
|
||||
// Lower bounce rate = better. 40% or below is excellent.
|
||||
$factors['bounce_rate'] = max( 0.0, 20.0 - ( $ga_metrics['bounce_rate'] * 20.0 ) );
|
||||
} else {
|
||||
$factors['bounce_rate'] = 0.0;
|
||||
}
|
||||
|
||||
$total = array_sum( $factors );
|
||||
|
||||
return [
|
||||
'score' => round( $total, 2 ),
|
||||
'factors' => $factors,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a content score in the database.
|
||||
*
|
||||
* @param int $post_id
|
||||
* @param array $wp_metrics
|
||||
* @param array $ga_metrics
|
||||
* @param array $score_data {score: float, factors: array}.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function store_score( int $post_id, array $wp_metrics, array $ga_metrics, array $score_data ): void {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_content_scores';
|
||||
|
||||
$entry = new Autoblogger_Content_Score( [
|
||||
'post_id' => $post_id,
|
||||
'pageviews' => $ga_metrics['pageviews'] ?? 0,
|
||||
'avg_time_on_page' => $ga_metrics['avg_time_on_page'] ?? 0.0,
|
||||
'bounce_rate' => $ga_metrics['bounce_rate'] ?? 0.0,
|
||||
'comment_count' => $wp_metrics['comment_count'] ?? 0,
|
||||
'composite_score' => $score_data['score'],
|
||||
'score_factors' => $score_data['factors'],
|
||||
'measured_at' => current_time( 'mysql' ),
|
||||
] );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->insert( $table, $entry->to_db_row() );
|
||||
}
|
||||
}
|
||||
128
includes/core/class-pipeline-runner.php
Executable file
128
includes/core/class-pipeline-runner.php
Executable file
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Executes the full content generation pipeline.
|
||||
*
|
||||
* Orchestrates: Budget check → Collect source data → Analyze patterns →
|
||||
* Score ideas → Generate content → Editorial review → Publish.
|
||||
*
|
||||
* Triggered by: Autoblogger::on_daily_generation() and Autoblogger::on_ajax_generate_now().
|
||||
* Dependencies: All core content classes (Collector, Analyzer, Scorer, Generator, Editor, Publisher).
|
||||
*
|
||||
* @see class-autoblogger.php — Instantiates this class and calls run().
|
||||
* @see core/class-cost-tracker.php — Tracks cumulative API costs throughout the run.
|
||||
* @see ARCHITECTURE.md — Data flow diagram showing pipeline steps.
|
||||
*/
|
||||
class Autoblogger_Pipeline_Runner {
|
||||
|
||||
/**
|
||||
* Execute the full content generation pipeline.
|
||||
*
|
||||
* Steps: Budget check → Collect source data → Analyze patterns →
|
||||
* Score ideas → Generate content → Editorial review → Publish.
|
||||
*
|
||||
* Side effects: API calls (OpenRouter, Reddit), database writes, post creation.
|
||||
*
|
||||
* @return array{generated: int, published: int, rejected: int, cost: float} Pipeline results.
|
||||
*
|
||||
* @throws \RuntimeException If budget is exceeded or critical step fails.
|
||||
*/
|
||||
public function run(): array {
|
||||
$cost_tracker = new Autoblogger_Cost_Tracker();
|
||||
|
||||
// Tag all log entries in this run with a unique ID so link_generation_logs()
|
||||
// can accurately attribute costs to the correct post in batch runs.
|
||||
$cost_tracker->set_run_id( wp_generate_uuid4() );
|
||||
|
||||
// Hard stop if monthly budget is exceeded.
|
||||
if ( $cost_tracker->is_budget_exceeded() ) {
|
||||
throw new \RuntimeException(
|
||||
__( 'Monthly API budget exceeded. Generation halted.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$target_count = absint( get_option( 'autoblogger_daily_article_target', 1 ) );
|
||||
|
||||
// Step 1: Collect source data.
|
||||
$collector = new Autoblogger_Source_Collector();
|
||||
$collector->collect_from_all_sources();
|
||||
|
||||
// Step 2: Analyze collected data for patterns.
|
||||
$llm = new Autoblogger_OpenRouter_Provider();
|
||||
$analyzer = new Autoblogger_Content_Analyzer( $llm, $cost_tracker );
|
||||
$analysis = $analyzer->analyze_recent_data();
|
||||
|
||||
// Step 3: Score and deduplicate ideas.
|
||||
$scorer = new Autoblogger_Idea_Scorer();
|
||||
$ideas = $scorer->score_and_rank( $analysis, $target_count );
|
||||
|
||||
if ( empty( $ideas ) ) {
|
||||
Autoblogger_Logger::instance()->info( 'No viable article ideas found. Skipping generation.', 'pipeline' );
|
||||
return [ 'generated' => 0, 'published' => 0, 'rejected' => 0, 'cost' => 0.0 ];
|
||||
}
|
||||
|
||||
// Step 4 & 5: Generate content and run through editor for each idea.
|
||||
$generator = new Autoblogger_Content_Generator( $llm, $cost_tracker );
|
||||
$editor = new Autoblogger_Chief_Editor( $llm, $cost_tracker );
|
||||
$publisher = new Autoblogger_Publisher();
|
||||
$auto_publish = in_array( get_option( 'autoblogger_auto_publish', '0' ), [ '1', 'yes' ], true );
|
||||
|
||||
$generated = 0;
|
||||
$published = 0;
|
||||
$rejected = 0;
|
||||
|
||||
foreach ( $ideas as $idea ) {
|
||||
// Re-check budget before each article — stop early if we hit the limit.
|
||||
if ( $cost_tracker->is_budget_exceeded() ) {
|
||||
Autoblogger_Logger::instance()->warning( 'Budget limit reached during generation. Stopping early.', 'pipeline' );
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
$content = $generator->generate( $idea );
|
||||
$generated++;
|
||||
|
||||
$review = $editor->review( $content, $idea );
|
||||
|
||||
if ( 'approved' === $review->get_verdict() || 'revised' === $review->get_verdict() ) {
|
||||
// Null-coalesce: if editor returns 'revised' verdict but
|
||||
// get_revised_content() is null (e.g. malformed LLM response),
|
||||
// fall back to the original generated content.
|
||||
$final_content = 'revised' === $review->get_verdict()
|
||||
? ( $review->get_revised_content() ?? $content )
|
||||
: $content;
|
||||
|
||||
if ( $auto_publish ) {
|
||||
$publisher->publish( $final_content, $idea, $review, $cost_tracker->get_run_id() );
|
||||
$published++;
|
||||
} else {
|
||||
// Auto-publish disabled: send to review queue as draft.
|
||||
$publisher->save_as_draft( $final_content, $idea, $review, $cost_tracker->get_run_id() );
|
||||
}
|
||||
} else {
|
||||
$publisher->save_as_draft( $content, $idea, $review, $cost_tracker->get_run_id() );
|
||||
$rejected++;
|
||||
Autoblogger_Logger::instance()->info( 'Article rejected by editor: ' . $idea->get_topic(), 'pipeline' );
|
||||
}
|
||||
} catch ( \Exception $e ) {
|
||||
Autoblogger_Logger::instance()->error( 'Failed to generate article for topic "' . $idea->get_topic() . '": ' . $e->getMessage(), 'pipeline' );
|
||||
// Continue with next idea — don't let one failure stop the batch.
|
||||
}
|
||||
}
|
||||
|
||||
$total_cost = $cost_tracker->get_current_run_cost();
|
||||
|
||||
Autoblogger_Logger::instance()->info(
|
||||
sprintf( 'Pipeline complete: %d generated, %d published, %d rejected. Cost: $%.4f', $generated, $published, $rejected, $total_cost ),
|
||||
'pipeline'
|
||||
);
|
||||
|
||||
return [
|
||||
'generated' => $generated,
|
||||
'published' => $published,
|
||||
'rejected' => $rejected,
|
||||
'cost' => $total_cost,
|
||||
];
|
||||
}
|
||||
}
|
||||
269
includes/core/class-publisher.php
Executable file
269
includes/core/class-publisher.php
Executable file
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Creates WordPress posts from generated and editor-approved content.
|
||||
*
|
||||
* Handles both publishing (editor-approved) and saving as draft (editor-rejected).
|
||||
* Stores all generation metadata as post_meta for transparency and auditability.
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 6).
|
||||
* Dependencies: WordPress wp_insert_post(), post meta API.
|
||||
*
|
||||
* @see core/class-chief-editor.php — Produces the editorial review we consume.
|
||||
* @see core/class-content-generator.php — Produces the content we publish.
|
||||
* @see ARCHITECTURE.md — Data flow step 6.
|
||||
*/
|
||||
class Autoblogger_Publisher {
|
||||
|
||||
/**
|
||||
* Publish an editor-approved article.
|
||||
*
|
||||
* Creates a WordPress post with 'publish' status and stores all generation
|
||||
* metadata as post_meta.
|
||||
*
|
||||
* Side effects: Creates a WordPress post, writes post_meta.
|
||||
*
|
||||
* @param string $content The final HTML content.
|
||||
* @param Autoblogger_Article_Idea $idea The original article idea.
|
||||
* @param Autoblogger_Editorial_Review $review The editor's review.
|
||||
* @param string|null $run_id Pipeline run ID for log linking.
|
||||
*
|
||||
* @return int The created post ID.
|
||||
*
|
||||
* @throws \RuntimeException If post creation fails.
|
||||
*/
|
||||
public function publish(
|
||||
string $content,
|
||||
Autoblogger_Article_Idea $idea,
|
||||
Autoblogger_Editorial_Review $review,
|
||||
?string $run_id = null
|
||||
): int {
|
||||
return $this->create_post( $content, $idea, $review, 'publish', $run_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save an editor-rejected article as a draft for human review.
|
||||
*
|
||||
* @param string $content The generated HTML content (pre-revision).
|
||||
* @param Autoblogger_Article_Idea $idea The original article idea.
|
||||
* @param Autoblogger_Editorial_Review $review The editor's review with rejection notes.
|
||||
* @param string|null $run_id Pipeline run ID for log linking.
|
||||
*
|
||||
* @return int The created post ID.
|
||||
*
|
||||
* @throws \RuntimeException If post creation fails.
|
||||
*/
|
||||
public function save_as_draft(
|
||||
string $content,
|
||||
Autoblogger_Article_Idea $idea,
|
||||
Autoblogger_Editorial_Review $review,
|
||||
?string $run_id = null
|
||||
): int {
|
||||
return $this->create_post( $content, $idea, $review, 'draft', $run_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a WordPress post with generation metadata.
|
||||
*
|
||||
* @param string $content HTML content.
|
||||
* @param Autoblogger_Article_Idea $idea Article idea.
|
||||
* @param Autoblogger_Editorial_Review $review Editorial review.
|
||||
* @param string $post_status 'publish' or 'draft'.
|
||||
* @param string|null $run_id Pipeline run ID for log linking.
|
||||
*
|
||||
* @return int Post ID.
|
||||
*
|
||||
* @throws \RuntimeException If wp_insert_post fails.
|
||||
*/
|
||||
private function create_post(
|
||||
string $content,
|
||||
Autoblogger_Article_Idea $idea,
|
||||
Autoblogger_Editorial_Review $review,
|
||||
string $post_status,
|
||||
?string $run_id = null
|
||||
): int {
|
||||
$post_data = [
|
||||
'post_title' => sanitize_text_field( $idea->get_suggested_title() ),
|
||||
'post_content' => wp_kses_post( $content ),
|
||||
'post_status' => $post_status,
|
||||
'post_type' => 'post',
|
||||
'post_author' => $this->get_default_author_id(),
|
||||
'meta_input' => $this->build_meta( $idea, $review ),
|
||||
];
|
||||
|
||||
/**
|
||||
* Fires before an AutoBlogger post is created.
|
||||
*
|
||||
* Listeners registered in: class-autoblogger.php (main loader).
|
||||
*
|
||||
* @param array $post_data Post data array.
|
||||
* @param Autoblogger_Article_Idea $idea The article idea.
|
||||
* @param Autoblogger_Editorial_Review $review The editorial review.
|
||||
*/
|
||||
$post_data = apply_filters( 'autoblogger_filter_post_data', $post_data, $idea, $review );
|
||||
|
||||
$post_id = wp_insert_post( $post_data, true );
|
||||
|
||||
if ( is_wp_error( $post_id ) ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
/* translators: %s: WordPress error message */
|
||||
__( 'Failed to create post: %s', 'autoblogger' ),
|
||||
$post_id->get_error_message()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Assign categories/tags based on article type and keywords.
|
||||
$this->assign_taxonomy_terms( $post_id, $idea );
|
||||
|
||||
// Update generation log entries to reference this post.
|
||||
$this->link_generation_logs( $post_id, $run_id );
|
||||
|
||||
Autoblogger_Logger::instance()->info(
|
||||
sprintf( 'Post created: ID=%d, status=%s, title="%s"', $post_id, $post_status, $idea->get_suggested_title() ),
|
||||
'publisher'
|
||||
);
|
||||
|
||||
/**
|
||||
* Fires after an AutoBlogger post is successfully created.
|
||||
*
|
||||
* @param int $post_id The new post ID.
|
||||
* @param string $post_status 'publish' or 'draft'.
|
||||
* @param Autoblogger_Article_Idea $idea The article idea.
|
||||
* @param Autoblogger_Editorial_Review $review The editorial review.
|
||||
*/
|
||||
do_action( 'autoblogger_post_created', $post_id, $post_status, $idea, $review );
|
||||
|
||||
return $post_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build post_meta array for generation metadata.
|
||||
*
|
||||
* @param Autoblogger_Article_Idea $idea
|
||||
* @param Autoblogger_Editorial_Review $review
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function build_meta(
|
||||
Autoblogger_Article_Idea $idea,
|
||||
Autoblogger_Editorial_Review $review
|
||||
): array {
|
||||
$pipeline_mode = get_option( 'autoblogger_writing_pipeline', 'multi_step' );
|
||||
$model = get_option( 'autoblogger_writing_model', AUTOBLOGGER_DEFAULT_WRITING_MODEL );
|
||||
|
||||
return [
|
||||
'_autoblogger_generated' => '1',
|
||||
'_autoblogger_analysis_id' => $idea->get_analysis_id(),
|
||||
'_autoblogger_source_ids' => wp_json_encode( $idea->get_source_ids() ),
|
||||
'_autoblogger_model_used' => $model,
|
||||
'_autoblogger_pipeline_mode' => $pipeline_mode,
|
||||
'_autoblogger_editor_verdict' => $review->get_verdict(),
|
||||
'_autoblogger_editor_notes' => $review->get_notes(),
|
||||
'_autoblogger_quality_score' => $review->get_quality_score(),
|
||||
'_autoblogger_seo_score' => $review->get_seo_score(),
|
||||
'_autoblogger_generated_at' => gmdate( 'c' ),
|
||||
'_autoblogger_topic' => $idea->get_topic(),
|
||||
'_autoblogger_article_type' => $idea->get_article_type(),
|
||||
'_autoblogger_target_keywords' => wp_json_encode( $idea->get_target_keywords() ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign category and tags to a generated post.
|
||||
*
|
||||
* @param int $post_id
|
||||
* @param Autoblogger_Article_Idea $idea
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function assign_taxonomy_terms( int $post_id, Autoblogger_Article_Idea $idea ): void {
|
||||
$type_category_map = [
|
||||
'guide' => 'Guides',
|
||||
'solution' => 'Solutions',
|
||||
'comparison' => 'Comparisons',
|
||||
'article' => 'Articles',
|
||||
];
|
||||
|
||||
$category_name = $type_category_map[ $idea->get_article_type() ] ?? 'Articles';
|
||||
|
||||
$category = get_term_by( 'name', $category_name, 'category' );
|
||||
if ( ! $category ) {
|
||||
$result = wp_insert_term( $category_name, 'category' );
|
||||
if ( ! is_wp_error( $result ) ) {
|
||||
wp_set_post_categories( $post_id, [ $result['term_id'] ] );
|
||||
}
|
||||
} else {
|
||||
wp_set_post_categories( $post_id, [ $category->term_id ] );
|
||||
}
|
||||
|
||||
$keywords = $idea->get_target_keywords();
|
||||
if ( ! empty( $keywords ) ) {
|
||||
wp_set_post_tags( $post_id, $keywords, true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Link generation log entries to the newly created post using run_id.
|
||||
*
|
||||
* The previous timestamp-based approach could misattribute costs in batch runs
|
||||
* where multiple articles are generated in the same pipeline execution. Using
|
||||
* run_id ensures each post is linked only to the log entries from its own run.
|
||||
*
|
||||
* Falls back to timestamp-based linking if no run_id is set (e.g. legacy data
|
||||
* from before the run_id migration).
|
||||
*
|
||||
* @param int $post_id The newly created post ID.
|
||||
* @param string|null $run_id Pipeline run identifier, or null for legacy fallback.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function link_generation_logs( int $post_id, ?string $run_id = null ): void {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_generation_log';
|
||||
|
||||
if ( null !== $run_id && '' !== $run_id ) {
|
||||
// Precise linking via run_id — no risk of cross-article misattribution.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"UPDATE {$table} SET post_id = %d WHERE post_id IS NULL AND run_id = %s",
|
||||
$post_id,
|
||||
$run_id
|
||||
)
|
||||
);
|
||||
} else {
|
||||
// Legacy fallback: timestamp-based linking for pre-migration log entries.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"UPDATE {$table} SET post_id = %d WHERE post_id IS NULL AND created_at >= %s",
|
||||
$post_id,
|
||||
gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default author ID for generated posts.
|
||||
*
|
||||
* @return int WordPress user ID.
|
||||
*/
|
||||
private function get_default_author_id(): int {
|
||||
$author_id = absint( get_option( 'autoblogger_default_author', 0 ) );
|
||||
if ( $author_id > 0 ) {
|
||||
return $author_id;
|
||||
}
|
||||
|
||||
$admins = get_users( [
|
||||
'role' => 'administrator',
|
||||
'number' => 1,
|
||||
'fields' => 'ID',
|
||||
] );
|
||||
|
||||
return ! empty( $admins ) ? (int) $admins[0] : 1;
|
||||
}
|
||||
}
|
||||
167
includes/core/class-source-collector.php
Executable file
167
includes/core/class-source-collector.php
Executable file
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Orchestrates data collection from all enabled source providers.
|
||||
*
|
||||
* Iterates through enabled sources (Reddit, TikTok, etc.), calls their
|
||||
* collect_data() method, and stores results in the ab_source_data table.
|
||||
* Handles deduplication via UNIQUE index on (source_type, source_id).
|
||||
*
|
||||
* Triggered by: Autoblogger::run_generation_pipeline() (step 1).
|
||||
* Dependencies: Source provider implementations, WordPress $wpdb.
|
||||
*
|
||||
* @see providers/interface-source-provider.php — Interface providers implement.
|
||||
* @see providers/class-reddit-provider.php — Primary source provider.
|
||||
* @see ARCHITECTURE.md — Data flow step 1.
|
||||
*/
|
||||
class Autoblogger_Source_Collector {
|
||||
|
||||
/**
|
||||
* Collect data from all enabled source providers and store in database.
|
||||
*
|
||||
* Side effects: HTTP requests to source APIs, database inserts.
|
||||
*
|
||||
* @return int Total number of new records inserted.
|
||||
*/
|
||||
public function collect_from_all_sources(): int {
|
||||
$enabled = json_decode( get_option( 'autoblogger_enabled_sources', '["reddit"]' ), true );
|
||||
if ( ! is_array( $enabled ) ) {
|
||||
$enabled = [ 'reddit' ];
|
||||
}
|
||||
|
||||
$total_inserted = 0;
|
||||
|
||||
foreach ( $enabled as $source_type ) {
|
||||
$provider = $this->get_provider( $source_type );
|
||||
if ( null === $provider ) {
|
||||
Autoblogger_Logger::instance()->warning( "No provider found for source type: {$source_type}", 'collector' );
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$data = $provider->collect_data( $this->get_config_for_source( $source_type ) );
|
||||
$inserted = $this->store_data( $data );
|
||||
$total_inserted += $inserted;
|
||||
|
||||
Autoblogger_Logger::instance()->info(
|
||||
sprintf( 'Collected %d items from %s (%d new).', count( $data ), $source_type, $inserted ),
|
||||
'collector'
|
||||
);
|
||||
} catch ( \Exception $e ) {
|
||||
Autoblogger_Logger::instance()->error( "Collection from {$source_type} FAILED: " . $e->getMessage(), 'collector' );
|
||||
// Continue with other sources — one failure shouldn't stop everything.
|
||||
}
|
||||
}
|
||||
|
||||
return $total_inserted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store collected source data in the database.
|
||||
*
|
||||
* Uses INSERT IGNORE to handle duplicates gracefully (UNIQUE index).
|
||||
*
|
||||
* Side effects: database inserts.
|
||||
*
|
||||
* @param Autoblogger_Source_Data[] $items
|
||||
*
|
||||
* @return int Number of new records inserted.
|
||||
*/
|
||||
private function store_data( array $items ): int {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'autoblogger_source_data';
|
||||
$inserted = 0;
|
||||
|
||||
foreach ( $items as $item ) {
|
||||
$row = $item->to_db_row();
|
||||
|
||||
// Use INSERT IGNORE so duplicate (source_type, source_id) pairs are silently skipped.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$result = $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"INSERT IGNORE INTO {$table}
|
||||
(source_type, source_id, subreddit, title, content, author, score, comment_count, permalink, collected_at, metadata_json)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %d, %d, %s, %s, %s)",
|
||||
$row['source_type'],
|
||||
$row['source_id'],
|
||||
$row['subreddit'],
|
||||
$row['title'],
|
||||
$row['content'],
|
||||
$row['author'],
|
||||
$row['score'],
|
||||
$row['comment_count'],
|
||||
$row['permalink'],
|
||||
$row['collected_at'],
|
||||
$row['metadata_json']
|
||||
)
|
||||
);
|
||||
|
||||
if ( false !== $result && $result > 0 ) {
|
||||
$inserted++;
|
||||
}
|
||||
}
|
||||
|
||||
return $inserted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the provider instance for a given source type.
|
||||
*
|
||||
* @param string $source_type Source type identifier.
|
||||
*
|
||||
* @return Autoblogger_Source_Provider_Interface|null
|
||||
*/
|
||||
private function get_provider( string $source_type ): ?Autoblogger_Source_Provider_Interface {
|
||||
$providers = [
|
||||
'reddit' => Autoblogger_Reddit_Provider::class,
|
||||
// Future providers: 'tiktok', 'instagram', 'youtube'
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter the registered source providers.
|
||||
*
|
||||
* @param array<string, string> $providers Map of source_type => class name.
|
||||
*/
|
||||
$providers = apply_filters( 'autoblogger_filter_source_providers', $providers );
|
||||
|
||||
if ( ! isset( $providers[ $source_type ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$class = $providers[ $source_type ];
|
||||
|
||||
// Guard against unloadable provider classes (e.g. stub providers not yet
|
||||
// autoloadable, or classes removed during development).
|
||||
if ( ! class_exists( $class ) ) {
|
||||
Autoblogger_Logger::instance()->error(
|
||||
sprintf( 'Provider class "%s" for source type "%s" does not exist.', $class, $source_type ),
|
||||
'collector'
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
return new $class();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the configuration array for a specific source type from plugin settings.
|
||||
*
|
||||
* @param string $source_type Source type identifier.
|
||||
*
|
||||
* @return array<string, mixed> Configuration for the provider.
|
||||
*/
|
||||
private function get_config_for_source( string $source_type ): array {
|
||||
if ( 'reddit' === $source_type ) {
|
||||
return [
|
||||
'subreddits' => json_decode( get_option( 'autoblogger_target_subreddits', '[]' ), true ) ?: [],
|
||||
'limit' => 25,
|
||||
'time_filter' => 'day',
|
||||
'include_comments' => true,
|
||||
'comments_per_post' => 10,
|
||||
];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
102
includes/models/class-analysis-result.php
Executable file
102
includes/models/class-analysis-result.php
Executable file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object representing an analyzed topic pattern (recurring question,
|
||||
* complaint, or comparison detected in source data).
|
||||
*
|
||||
* Triggered by: Content_Analyzer creates these; Idea_Scorer consumes them.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-content-analyzer.php — Creates these from source data + LLM analysis.
|
||||
* @see core/class-idea-scorer.php — Ranks these into article ideas.
|
||||
*/
|
||||
class Autoblogger_Analysis_Result {
|
||||
|
||||
private int $id;
|
||||
private string $analysis_type;
|
||||
private string $topic;
|
||||
private ?string $summary;
|
||||
private int $frequency;
|
||||
private float $relevance_score;
|
||||
private array $source_ids;
|
||||
private string $analyzed_at;
|
||||
private ?array $metadata;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* id?: int,
|
||||
* analysis_type: string,
|
||||
* topic: string,
|
||||
* summary?: string|null,
|
||||
* frequency?: int,
|
||||
* relevance_score?: float,
|
||||
* source_ids?: int[],
|
||||
* analyzed_at?: string,
|
||||
* metadata?: array|null,
|
||||
* } $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->id = (int) ( $data['id'] ?? 0 );
|
||||
$this->analysis_type = $data['analysis_type'];
|
||||
$this->topic = $data['topic'];
|
||||
$this->summary = $data['summary'] ?? null;
|
||||
$this->frequency = (int) ( $data['frequency'] ?? 1 );
|
||||
$this->relevance_score = (float) ( $data['relevance_score'] ?? 0.0 );
|
||||
$this->source_ids = $data['source_ids'] ?? [];
|
||||
$this->analyzed_at = $data['analyzed_at'] ?? current_time( 'mysql' );
|
||||
$this->metadata = $data['metadata'] ?? null;
|
||||
}
|
||||
|
||||
public function get_id(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function get_analysis_type(): string {
|
||||
return $this->analysis_type;
|
||||
}
|
||||
|
||||
public function get_topic(): string {
|
||||
return $this->topic;
|
||||
}
|
||||
|
||||
public function get_summary(): ?string {
|
||||
return $this->summary;
|
||||
}
|
||||
|
||||
public function get_frequency(): int {
|
||||
return $this->frequency;
|
||||
}
|
||||
|
||||
public function get_relevance_score(): float {
|
||||
return $this->relevance_score;
|
||||
}
|
||||
|
||||
public function get_source_ids(): array {
|
||||
return $this->source_ids;
|
||||
}
|
||||
|
||||
public function get_analyzed_at(): string {
|
||||
return $this->analyzed_at;
|
||||
}
|
||||
|
||||
public function get_metadata(): ?array {
|
||||
return $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function to_db_row(): array {
|
||||
return [
|
||||
'analysis_type' => $this->analysis_type,
|
||||
'topic' => $this->topic,
|
||||
'summary' => $this->summary,
|
||||
'frequency' => $this->frequency,
|
||||
'relevance_score' => $this->relevance_score,
|
||||
'source_ids_json' => wp_json_encode( $this->source_ids ),
|
||||
'analyzed_at' => $this->analyzed_at,
|
||||
'metadata_json' => null !== $this->metadata ? wp_json_encode( $this->metadata ) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
87
includes/models/class-article-idea.php
Executable file
87
includes/models/class-article-idea.php
Executable file
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object representing a scored article idea ready for content generation.
|
||||
*
|
||||
* Created by the Idea_Scorer from Analysis_Results. Consumed by Content_Generator.
|
||||
*
|
||||
* Triggered by: Idea_Scorer creates these; Content_Generator and Chief_Editor consume them.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-idea-scorer.php — Creates and ranks these.
|
||||
* @see core/class-content-generator.php — Uses these as generation input.
|
||||
*/
|
||||
class Autoblogger_Article_Idea {
|
||||
|
||||
private string $topic;
|
||||
private string $article_type;
|
||||
private string $suggested_title;
|
||||
private string $summary;
|
||||
private float $score;
|
||||
private int $analysis_id;
|
||||
private array $source_ids;
|
||||
private array $key_points;
|
||||
private array $target_keywords;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* topic: string,
|
||||
* article_type: string,
|
||||
* suggested_title: string,
|
||||
* summary: string,
|
||||
* score?: float,
|
||||
* analysis_id?: int,
|
||||
* source_ids?: int[],
|
||||
* key_points?: string[],
|
||||
* target_keywords?: string[],
|
||||
* } $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->topic = $data['topic'];
|
||||
$this->article_type = $data['article_type'];
|
||||
$this->suggested_title = $data['suggested_title'];
|
||||
$this->summary = $data['summary'];
|
||||
$this->score = (float) ( $data['score'] ?? 0.0 );
|
||||
$this->analysis_id = (int) ( $data['analysis_id'] ?? 0 );
|
||||
$this->source_ids = $data['source_ids'] ?? [];
|
||||
$this->key_points = $data['key_points'] ?? [];
|
||||
$this->target_keywords = $data['target_keywords'] ?? [];
|
||||
}
|
||||
|
||||
public function get_topic(): string {
|
||||
return $this->topic;
|
||||
}
|
||||
|
||||
public function get_article_type(): string {
|
||||
return $this->article_type;
|
||||
}
|
||||
|
||||
public function get_suggested_title(): string {
|
||||
return $this->suggested_title;
|
||||
}
|
||||
|
||||
public function get_summary(): string {
|
||||
return $this->summary;
|
||||
}
|
||||
|
||||
public function get_score(): float {
|
||||
return $this->score;
|
||||
}
|
||||
|
||||
public function get_analysis_id(): int {
|
||||
return $this->analysis_id;
|
||||
}
|
||||
|
||||
public function get_source_ids(): array {
|
||||
return $this->source_ids;
|
||||
}
|
||||
|
||||
public function get_key_points(): array {
|
||||
return $this->key_points;
|
||||
}
|
||||
|
||||
public function get_target_keywords(): array {
|
||||
return $this->target_keywords;
|
||||
}
|
||||
}
|
||||
70
includes/models/class-content-request.php
Executable file
70
includes/models/class-content-request.php
Executable file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object encapsulating all parameters for a content generation request.
|
||||
*
|
||||
* Bundles the article idea with user-configured generation preferences
|
||||
* (tone, word count, pipeline mode) into a single object passed through the pipeline.
|
||||
*
|
||||
* Triggered by: Content_Generator creates these from Article_Ideas + settings.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-content-generator.php — Creates and consumes these.
|
||||
*/
|
||||
class Autoblogger_Content_Request {
|
||||
|
||||
private Autoblogger_Article_Idea $idea;
|
||||
private string $pipeline_mode;
|
||||
private string $tone;
|
||||
private int $min_word_count;
|
||||
private int $max_word_count;
|
||||
private string $niche_description;
|
||||
private array $topic_exclusions;
|
||||
|
||||
public function __construct(
|
||||
Autoblogger_Article_Idea $idea,
|
||||
string $pipeline_mode,
|
||||
string $tone,
|
||||
int $min_word_count,
|
||||
int $max_word_count,
|
||||
string $niche_description,
|
||||
array $topic_exclusions = []
|
||||
) {
|
||||
$this->idea = $idea;
|
||||
$this->pipeline_mode = $pipeline_mode;
|
||||
$this->tone = $tone;
|
||||
$this->min_word_count = $min_word_count;
|
||||
$this->max_word_count = $max_word_count;
|
||||
$this->niche_description = $niche_description;
|
||||
$this->topic_exclusions = $topic_exclusions;
|
||||
}
|
||||
|
||||
public function get_idea(): Autoblogger_Article_Idea {
|
||||
return $this->idea;
|
||||
}
|
||||
|
||||
public function get_pipeline_mode(): string {
|
||||
return $this->pipeline_mode;
|
||||
}
|
||||
|
||||
public function get_tone(): string {
|
||||
return $this->tone;
|
||||
}
|
||||
|
||||
public function get_min_word_count(): int {
|
||||
return $this->min_word_count;
|
||||
}
|
||||
|
||||
public function get_max_word_count(): int {
|
||||
return $this->max_word_count;
|
||||
}
|
||||
|
||||
public function get_niche_description(): string {
|
||||
return $this->niche_description;
|
||||
}
|
||||
|
||||
public function get_topic_exclusions(): array {
|
||||
return $this->topic_exclusions;
|
||||
}
|
||||
}
|
||||
65
includes/models/class-content-score.php
Executable file
65
includes/models/class-content-score.php
Executable file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object for a post's composite performance score.
|
||||
*
|
||||
* Triggered by: Metrics_Collector creates these; Content_Analyzer reads them for self-improvement.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-metrics-collector.php — Creates these from WP + GA4 data.
|
||||
* @see core/class-content-analyzer.php — Reads past scores to refine analysis.
|
||||
*/
|
||||
class Autoblogger_Content_Score {
|
||||
|
||||
private int $id;
|
||||
private int $post_id;
|
||||
private int $pageviews;
|
||||
private float $avg_time_on_page;
|
||||
private float $bounce_rate;
|
||||
private int $comment_count;
|
||||
private float $composite_score;
|
||||
private ?array $score_factors;
|
||||
private string $measured_at;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->id = (int) ( $data['id'] ?? 0 );
|
||||
$this->post_id = (int) ( $data['post_id'] ?? 0 );
|
||||
$this->pageviews = (int) ( $data['pageviews'] ?? 0 );
|
||||
$this->avg_time_on_page = (float) ( $data['avg_time_on_page'] ?? 0.0 );
|
||||
$this->bounce_rate = (float) ( $data['bounce_rate'] ?? 0.0 );
|
||||
$this->comment_count = (int) ( $data['comment_count'] ?? 0 );
|
||||
$this->composite_score = (float) ( $data['composite_score'] ?? 0.0 );
|
||||
$this->score_factors = $data['score_factors'] ?? null;
|
||||
$this->measured_at = $data['measured_at'] ?? current_time( 'mysql' );
|
||||
}
|
||||
|
||||
public function get_id(): int { return $this->id; }
|
||||
public function get_post_id(): int { return $this->post_id; }
|
||||
public function get_pageviews(): int { return $this->pageviews; }
|
||||
public function get_avg_time_on_page(): float { return $this->avg_time_on_page; }
|
||||
public function get_bounce_rate(): float { return $this->bounce_rate; }
|
||||
public function get_comment_count(): int { return $this->comment_count; }
|
||||
public function get_composite_score(): float { return $this->composite_score; }
|
||||
public function get_score_factors(): ?array { return $this->score_factors; }
|
||||
public function get_measured_at(): string { return $this->measured_at; }
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function to_db_row(): array {
|
||||
return [
|
||||
'post_id' => $this->post_id,
|
||||
'pageviews' => $this->pageviews,
|
||||
'avg_time_on_page' => $this->avg_time_on_page,
|
||||
'bounce_rate' => $this->bounce_rate,
|
||||
'comment_count' => $this->comment_count,
|
||||
'composite_score' => $this->composite_score,
|
||||
'score_factors_json' => null !== $this->score_factors ? wp_json_encode( $this->score_factors ) : null,
|
||||
'measured_at' => $this->measured_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
64
includes/models/class-editorial-review.php
Executable file
64
includes/models/class-editorial-review.php
Executable file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object representing the chief editor agent's review of generated content.
|
||||
*
|
||||
* Triggered by: Chief_Editor creates these; Publisher consumes them.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-chief-editor.php — Creates these after reviewing content.
|
||||
* @see core/class-publisher.php — Uses verdict to decide publish vs. draft.
|
||||
*/
|
||||
class Autoblogger_Editorial_Review {
|
||||
|
||||
private string $verdict;
|
||||
private string $notes;
|
||||
private ?string $revised_content;
|
||||
private float $quality_score;
|
||||
private float $seo_score;
|
||||
private array $issues;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* verdict: string,
|
||||
* notes: string,
|
||||
* revised_content?: string|null,
|
||||
* quality_score?: float,
|
||||
* seo_score?: float,
|
||||
* issues?: string[],
|
||||
* } $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->verdict = $data['verdict']; // 'approved', 'revised', 'rejected'
|
||||
$this->notes = $data['notes'];
|
||||
$this->revised_content = $data['revised_content'] ?? null;
|
||||
$this->quality_score = (float) ( $data['quality_score'] ?? 0.0 );
|
||||
$this->seo_score = (float) ( $data['seo_score'] ?? 0.0 );
|
||||
$this->issues = $data['issues'] ?? [];
|
||||
}
|
||||
|
||||
public function get_verdict(): string {
|
||||
return $this->verdict;
|
||||
}
|
||||
|
||||
public function get_notes(): string {
|
||||
return $this->notes;
|
||||
}
|
||||
|
||||
public function get_revised_content(): ?string {
|
||||
return $this->revised_content;
|
||||
}
|
||||
|
||||
public function get_quality_score(): float {
|
||||
return $this->quality_score;
|
||||
}
|
||||
|
||||
public function get_seo_score(): float {
|
||||
return $this->seo_score;
|
||||
}
|
||||
|
||||
public function get_issues(): array {
|
||||
return $this->issues;
|
||||
}
|
||||
}
|
||||
81
includes/models/class-generation-log.php
Executable file
81
includes/models/class-generation-log.php
Executable file
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object for an API call log entry (cost tracking).
|
||||
*
|
||||
* Triggered by: Cost_Tracker creates these; Metrics_Page displays them.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see core/class-cost-tracker.php — Writes these to ab_generation_log table.
|
||||
* @see admin/class-metrics-page.php — Reads and displays these.
|
||||
*/
|
||||
class Autoblogger_Generation_Log {
|
||||
|
||||
private int $id;
|
||||
private ?int $post_id;
|
||||
private ?string $run_id;
|
||||
private string $stage;
|
||||
private string $provider;
|
||||
private string $model;
|
||||
private int $prompt_tokens;
|
||||
private int $completion_tokens;
|
||||
private float $estimated_cost;
|
||||
private ?string $request_json;
|
||||
private string $response_status;
|
||||
private ?string $error_message;
|
||||
private string $created_at;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->id = (int) ( $data['id'] ?? 0 );
|
||||
$this->post_id = isset( $data['post_id'] ) ? (int) $data['post_id'] : null;
|
||||
$this->run_id = $data['run_id'] ?? null;
|
||||
$this->stage = $data['stage'] ?? '';
|
||||
$this->provider = $data['provider'] ?? '';
|
||||
$this->model = $data['model'] ?? '';
|
||||
$this->prompt_tokens = (int) ( $data['prompt_tokens'] ?? 0 );
|
||||
$this->completion_tokens = (int) ( $data['completion_tokens'] ?? 0 );
|
||||
$this->estimated_cost = (float) ( $data['estimated_cost'] ?? 0.0 );
|
||||
$this->request_json = $data['request_json'] ?? null;
|
||||
$this->response_status = $data['response_status'] ?? 'success';
|
||||
$this->error_message = $data['error_message'] ?? null;
|
||||
$this->created_at = $data['created_at'] ?? current_time( 'mysql' );
|
||||
}
|
||||
|
||||
public function get_id(): int { return $this->id; }
|
||||
public function get_post_id(): ?int { return $this->post_id; }
|
||||
public function get_run_id(): ?string { return $this->run_id; }
|
||||
public function get_stage(): string { return $this->stage; }
|
||||
public function get_provider(): string { return $this->provider; }
|
||||
public function get_model(): string { return $this->model; }
|
||||
public function get_prompt_tokens(): int { return $this->prompt_tokens; }
|
||||
public function get_completion_tokens(): int { return $this->completion_tokens; }
|
||||
public function get_estimated_cost(): float { return $this->estimated_cost; }
|
||||
public function get_request_json(): ?string { return $this->request_json; }
|
||||
public function get_response_status(): string { return $this->response_status; }
|
||||
public function get_error_message(): ?string { return $this->error_message; }
|
||||
public function get_created_at(): string { return $this->created_at; }
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function to_db_row(): array {
|
||||
return [
|
||||
'post_id' => $this->post_id,
|
||||
'run_id' => $this->run_id,
|
||||
'stage' => $this->stage,
|
||||
'provider' => $this->provider,
|
||||
'model' => $this->model,
|
||||
'prompt_tokens' => $this->prompt_tokens,
|
||||
'completion_tokens' => $this->completion_tokens,
|
||||
'estimated_cost' => $this->estimated_cost,
|
||||
'request_json' => $this->request_json,
|
||||
'response_status' => $this->response_status,
|
||||
'error_message' => $this->error_message,
|
||||
'created_at' => $this->created_at,
|
||||
];
|
||||
}
|
||||
}
|
||||
128
includes/models/class-source-data.php
Executable file
128
includes/models/class-source-data.php
Executable file
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Value object representing a single piece of collected social media data
|
||||
* (a Reddit post, a TikTok comment, etc.).
|
||||
*
|
||||
* Triggered by: Source providers create these; Content_Analyzer consumes them.
|
||||
* Dependencies: None — pure data object.
|
||||
*
|
||||
* @see providers/interface-source-provider.php — Providers return arrays of these.
|
||||
* @see core/class-content-analyzer.php — Consumes these for pattern detection.
|
||||
*/
|
||||
class Autoblogger_Source_Data {
|
||||
|
||||
private int $id;
|
||||
private string $source_type;
|
||||
private string $source_id;
|
||||
private ?string $subreddit;
|
||||
private ?string $title;
|
||||
private ?string $content;
|
||||
private ?string $author;
|
||||
private int $score;
|
||||
private int $comment_count;
|
||||
private ?string $permalink;
|
||||
private string $collected_at;
|
||||
private ?array $metadata;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* id?: int,
|
||||
* source_type: string,
|
||||
* source_id: string,
|
||||
* subreddit?: string|null,
|
||||
* title?: string|null,
|
||||
* content?: string|null,
|
||||
* author?: string|null,
|
||||
* score?: int,
|
||||
* comment_count?: int,
|
||||
* permalink?: string|null,
|
||||
* collected_at?: string,
|
||||
* metadata?: array|null,
|
||||
* } $data
|
||||
*/
|
||||
public function __construct( array $data ) {
|
||||
$this->id = (int) ( $data['id'] ?? 0 );
|
||||
$this->source_type = $data['source_type'];
|
||||
$this->source_id = $data['source_id'];
|
||||
$this->subreddit = $data['subreddit'] ?? null;
|
||||
$this->title = $data['title'] ?? null;
|
||||
$this->content = $data['content'] ?? null;
|
||||
$this->author = $data['author'] ?? null;
|
||||
$this->score = (int) ( $data['score'] ?? 0 );
|
||||
$this->comment_count = (int) ( $data['comment_count'] ?? 0 );
|
||||
$this->permalink = $data['permalink'] ?? null;
|
||||
$this->collected_at = $data['collected_at'] ?? current_time( 'mysql' );
|
||||
$this->metadata = $data['metadata'] ?? null;
|
||||
}
|
||||
|
||||
public function get_id(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function get_source_type(): string {
|
||||
return $this->source_type;
|
||||
}
|
||||
|
||||
public function get_source_id(): string {
|
||||
return $this->source_id;
|
||||
}
|
||||
|
||||
public function get_subreddit(): ?string {
|
||||
return $this->subreddit;
|
||||
}
|
||||
|
||||
public function get_title(): ?string {
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
public function get_content(): ?string {
|
||||
return $this->content;
|
||||
}
|
||||
|
||||
public function get_author(): ?string {
|
||||
return $this->author;
|
||||
}
|
||||
|
||||
public function get_score(): int {
|
||||
return $this->score;
|
||||
}
|
||||
|
||||
public function get_comment_count(): int {
|
||||
return $this->comment_count;
|
||||
}
|
||||
|
||||
public function get_permalink(): ?string {
|
||||
return $this->permalink;
|
||||
}
|
||||
|
||||
public function get_collected_at(): string {
|
||||
return $this->collected_at;
|
||||
}
|
||||
|
||||
public function get_metadata(): ?array {
|
||||
return $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert to array for database insertion.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function to_db_row(): array {
|
||||
return [
|
||||
'source_type' => $this->source_type,
|
||||
'source_id' => $this->source_id,
|
||||
'subreddit' => $this->subreddit,
|
||||
'title' => $this->title,
|
||||
'content' => $this->content,
|
||||
'author' => $this->author,
|
||||
'score' => $this->score,
|
||||
'comment_count' => $this->comment_count,
|
||||
'permalink' => $this->permalink,
|
||||
'collected_at' => $this->collected_at,
|
||||
'metadata_json' => null !== $this->metadata ? wp_json_encode( $this->metadata ) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
39
includes/providers/class-instagram-provider.php
Executable file
39
includes/providers/class-instagram-provider.php
Executable file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Instagram source provider — STUB for future implementation.
|
||||
*
|
||||
* Will integrate with Instagram's Graph API to collect post captions,
|
||||
* comments, and hashtag trends. Requires Meta developer app credentials.
|
||||
*
|
||||
* Triggered by: Source_Collector when 'instagram' is in enabled_sources.
|
||||
* Dependencies: TBD — Instagram Graph API credentials.
|
||||
*
|
||||
* @see interface-source-provider.php — Interface this class implements.
|
||||
*/
|
||||
class Autoblogger_Instagram_Provider implements Autoblogger_Source_Provider_Interface {
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config
|
||||
* @return Autoblogger_Source_Data[]
|
||||
* @throws \RuntimeException Always — not yet implemented.
|
||||
*/
|
||||
public function collect_data( array $config ): array {
|
||||
throw new \RuntimeException(
|
||||
__( 'Instagram source provider is not yet implemented. Remove "instagram" from enabled sources.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
public function get_source_type(): string {
|
||||
return 'instagram';
|
||||
}
|
||||
|
||||
public function validate_credentials(): bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
public function get_rate_limit_status(): array {
|
||||
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
|
||||
}
|
||||
}
|
||||
137
includes/providers/class-openrouter-pricing.php
Executable file
137
includes/providers/class-openrouter-pricing.php
Executable file
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* OpenRouter model pricing and availability lookup.
|
||||
*
|
||||
* Manages pricing tables, model lists, and cost estimation. Decoupled from
|
||||
* the request logic for easy updates and testing.
|
||||
*
|
||||
* Triggered by: Autoblogger_OpenRouter_Provider calls pricing methods.
|
||||
* Dependencies: None — pure data + calculation, no external calls by default.
|
||||
*
|
||||
* @see providers/class-openrouter-provider.php — Instantiates this class.
|
||||
* @see ARCHITECTURE.md — Model selection flow.
|
||||
*/
|
||||
class Autoblogger_OpenRouter_Pricing {
|
||||
|
||||
/**
|
||||
* Known model pricing (per million tokens, in USD).
|
||||
* Updated periodically. Falls back to API-reported pricing if available.
|
||||
*
|
||||
* @var array<string, array{prompt: float, completion: float}>
|
||||
*/
|
||||
private const MODEL_PRICING = [
|
||||
'anthropic/claude-3.5-haiku' => [ 'prompt' => 0.80, 'completion' => 4.00 ],
|
||||
'anthropic/claude-sonnet-4' => [ 'prompt' => 3.00, 'completion' => 15.00 ],
|
||||
'anthropic/claude-opus-4' => [ 'prompt' => 15.00, 'completion' => 75.00 ],
|
||||
'openai/gpt-4o' => [ 'prompt' => 2.50, 'completion' => 10.00 ],
|
||||
'openai/gpt-4o-mini' => [ 'prompt' => 0.15, 'completion' => 0.60 ],
|
||||
'google/gemini-2.0-flash' => [ 'prompt' => 0.10, 'completion' => 0.40 ],
|
||||
'meta-llama/llama-3.3-70b' => [ 'prompt' => 0.40, 'completion' => 0.40 ],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get available models from OpenRouter's /models endpoint.
|
||||
*
|
||||
* Caches the result in a transient for 24 hours to avoid repeated API calls.
|
||||
*
|
||||
* Side effects: HTTP request (if cache miss), sets transient.
|
||||
*
|
||||
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}>
|
||||
*/
|
||||
public function get_available_models(): array {
|
||||
$cached = get_transient( 'autoblogger_openrouter_models' );
|
||||
if ( false !== $cached && is_array( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$response = wp_remote_get(
|
||||
'https://openrouter.ai/api/v1/models',
|
||||
[
|
||||
'timeout' => 30,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $api_key,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
|
||||
Autoblogger_Logger::instance()->warning( 'Failed to fetch OpenRouter models list.', 'openrouter' );
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
$models = [];
|
||||
|
||||
if ( isset( $data['data'] ) && is_array( $data['data'] ) ) {
|
||||
foreach ( $data['data'] as $model ) {
|
||||
$models[] = [
|
||||
'id' => $model['id'] ?? '',
|
||||
'name' => $model['name'] ?? $model['id'] ?? '',
|
||||
'context_length' => (int) ( $model['context_length'] ?? 0 ),
|
||||
'pricing' => [
|
||||
'prompt' => (float) ( $model['pricing']['prompt'] ?? 0 ) * 1000000,
|
||||
'completion' => (float) ( $model['pricing']['completion'] ?? 0 ) * 1000000,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
set_transient( 'autoblogger_openrouter_models', $models, DAY_IN_SECONDS );
|
||||
return $models;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the cost of an API call in USD.
|
||||
*
|
||||
* Uses hardcoded pricing first, falls back to cached model data.
|
||||
*
|
||||
* @param string $model Model identifier.
|
||||
* @param int $prompt_tokens Input tokens.
|
||||
* @param int $completion_tokens Output tokens.
|
||||
*
|
||||
* @return float Estimated cost in USD.
|
||||
*/
|
||||
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float {
|
||||
$pricing = self::MODEL_PRICING[ $model ] ?? null;
|
||||
|
||||
// Fall back to cached model list pricing.
|
||||
if ( null === $pricing ) {
|
||||
$models = $this->get_available_models();
|
||||
foreach ( $models as $m ) {
|
||||
if ( $m['id'] === $model && isset( $m['pricing'] ) ) {
|
||||
$pricing = $m['pricing'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( null === $pricing ) {
|
||||
// Unknown model — use a conservative estimate.
|
||||
Autoblogger_Logger::instance()->warning( "Unknown model pricing for '{$model}'. Using conservative estimate.", 'openrouter' );
|
||||
$pricing = [ 'prompt' => 10.0, 'completion' => 30.0 ];
|
||||
}
|
||||
|
||||
return ( $prompt_tokens * $pricing['prompt'] / 1000000 )
|
||||
+ ( $completion_tokens * $pricing['completion'] / 1000000 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decrypted API key from options.
|
||||
*
|
||||
* @return string Decrypted API key, or empty string if not set.
|
||||
*/
|
||||
private function get_api_key(): string {
|
||||
$encrypted = get_option( 'autoblogger_openrouter_api_key', '' );
|
||||
if ( '' === $encrypted ) {
|
||||
return '';
|
||||
}
|
||||
return Autoblogger_Encryption::decrypt( $encrypted );
|
||||
}
|
||||
}
|
||||
253
includes/providers/class-openrouter-provider.php
Executable file
253
includes/providers/class-openrouter-provider.php
Executable file
@@ -0,0 +1,253 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* OpenRouter API integration for all LLM calls (analysis, writing, editing).
|
||||
*
|
||||
* OpenRouter provides a unified API to access models from Anthropic, OpenAI,
|
||||
* Google, Meta, and others. This lets users pick any model without us maintaining
|
||||
* separate provider integrations.
|
||||
*
|
||||
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
|
||||
* Dependencies: Autoblogger_Encryption (for API key decryption), wp_remote_post(), Autoblogger_OpenRouter_Pricing.
|
||||
*
|
||||
* @see interface-llm-provider.php — Interface this class implements.
|
||||
* @see class-openrouter-pricing.php — Pricing and model list lookups.
|
||||
* @see class-cost-tracker.php — Called after every request to log token usage.
|
||||
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
||||
*/
|
||||
class Autoblogger_OpenRouter_Provider implements Autoblogger_LLM_Provider_Interface {
|
||||
|
||||
private const API_BASE_URL = 'https://openrouter.ai/api/v1';
|
||||
|
||||
/**
|
||||
* Send a chat completion request to OpenRouter.
|
||||
*
|
||||
* Retries with exponential backoff on transient failures (5xx, timeout).
|
||||
* Logs every attempt. Fails loudly after exhausting retries.
|
||||
*
|
||||
* Side effects: HTTP request to OpenRouter API.
|
||||
*
|
||||
* @param array<int, array{role: string, content: string}> $messages Chat messages.
|
||||
* @param string $model Model identifier (e.g., 'anthropic/claude-sonnet-4').
|
||||
* @param array{
|
||||
* temperature?: float,
|
||||
* max_tokens?: int,
|
||||
* response_format?: array{type: string},
|
||||
* } $options Optional parameters.
|
||||
*
|
||||
* @return array{
|
||||
* content: string,
|
||||
* model: string,
|
||||
* prompt_tokens: int,
|
||||
* completion_tokens: int,
|
||||
* total_tokens: int,
|
||||
* finish_reason: string,
|
||||
* }
|
||||
*
|
||||
* @throws \RuntimeException On API error after retries exhausted.
|
||||
*/
|
||||
public function send_chat_completion( array $messages, string $model, array $options = [] ): array {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
throw new \RuntimeException(
|
||||
__( 'OpenRouter API key is not configured. Go to AutoBlogger → Settings.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$body = [
|
||||
'model' => $model,
|
||||
'messages' => $messages,
|
||||
];
|
||||
|
||||
if ( isset( $options['temperature'] ) ) {
|
||||
$body['temperature'] = $options['temperature'];
|
||||
}
|
||||
if ( isset( $options['max_tokens'] ) ) {
|
||||
$body['max_tokens'] = $options['max_tokens'];
|
||||
}
|
||||
if ( isset( $options['response_format'] ) ) {
|
||||
$body['response_format'] = $options['response_format'];
|
||||
}
|
||||
|
||||
$last_error = '';
|
||||
|
||||
for ( $attempt = 1; $attempt <= AUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
||||
$response = wp_remote_post(
|
||||
self::API_BASE_URL . '/chat/completions',
|
||||
[
|
||||
'timeout' => AUTOBLOGGER_API_TIMEOUT_SECONDS,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $api_key,
|
||||
'Content-Type' => 'application/json',
|
||||
'HTTP-Referer' => home_url(),
|
||||
'X-Title' => 'AutoBlogger WordPress Plugin',
|
||||
],
|
||||
'body' => wp_json_encode( $body ),
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$last_error = $response->get_error_message();
|
||||
Autoblogger_Logger::instance()->warning(
|
||||
sprintf( 'OpenRouter request failed (attempt %d/%d): %s', $attempt, AUTOBLOGGER_MAX_RETRIES, $last_error ),
|
||||
'openrouter'
|
||||
);
|
||||
|
||||
if ( $attempt < AUTOBLOGGER_MAX_RETRIES ) {
|
||||
$delay = AUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * pow( 2, $attempt - 1 );
|
||||
sleep( (int) $delay );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$status_code = wp_remote_retrieve_response_code( $response );
|
||||
$body_raw = wp_remote_retrieve_body( $response );
|
||||
$data = json_decode( $body_raw, true );
|
||||
|
||||
// Rate limited or server error — retry.
|
||||
if ( $status_code >= 429 || $status_code >= 500 ) {
|
||||
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
|
||||
Autoblogger_Logger::instance()->warning(
|
||||
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, AUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
|
||||
'openrouter'
|
||||
);
|
||||
|
||||
if ( $attempt < AUTOBLOGGER_MAX_RETRIES ) {
|
||||
// Respect Retry-After header if present.
|
||||
$retry_after = wp_remote_retrieve_header( $response, 'retry-after' );
|
||||
$delay = $retry_after
|
||||
? min( (int) $retry_after, 60 )
|
||||
: AUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * pow( 2, $attempt - 1 );
|
||||
sleep( (int) $delay );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Client error — don't retry, fail immediately.
|
||||
if ( $status_code >= 400 ) {
|
||||
$error_msg = isset( $data['error']['message'] )
|
||||
? $data['error']['message']
|
||||
: 'HTTP ' . $status_code;
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
/* translators: %d: HTTP status code, %s: error message */
|
||||
__( 'OpenRouter API error (HTTP %1$d): %2$s', 'autoblogger' ),
|
||||
$status_code,
|
||||
$error_msg
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Success — parse response.
|
||||
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
|
||||
throw new \RuntimeException(
|
||||
__( 'OpenRouter returned unexpected response format.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$usage = $data['usage'] ?? [];
|
||||
|
||||
return [
|
||||
'content' => $data['choices'][0]['message']['content'],
|
||||
'model' => $data['model'] ?? $model,
|
||||
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
|
||||
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
|
||||
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
|
||||
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
|
||||
];
|
||||
}
|
||||
|
||||
// All retries exhausted.
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
/* translators: %d: max retries, %s: last error message */
|
||||
__( 'OpenRouter API failed after %1$d attempts. Last error: %2$s', 'autoblogger' ),
|
||||
AUTOBLOGGER_MAX_RETRIES,
|
||||
$last_error
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available models from OpenRouter's /models endpoint.
|
||||
*
|
||||
* Caches the result in a transient for 24 hours to avoid repeated API calls.
|
||||
*
|
||||
* Side effects: HTTP request (if cache miss), sets transient.
|
||||
*
|
||||
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}>
|
||||
*/
|
||||
public function get_available_models(): array {
|
||||
$pricing = new Autoblogger_OpenRouter_Pricing();
|
||||
return $pricing->get_available_models();
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the cost of an API call in USD.
|
||||
*
|
||||
* Uses hardcoded pricing first, falls back to cached model data.
|
||||
*
|
||||
* @param string $model Model identifier.
|
||||
* @param int $prompt_tokens Input tokens.
|
||||
* @param int $completion_tokens Output tokens.
|
||||
*
|
||||
* @return float Estimated cost in USD.
|
||||
*/
|
||||
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float {
|
||||
$pricing = new Autoblogger_OpenRouter_Pricing();
|
||||
return $pricing->estimate_cost( $model, $prompt_tokens, $completion_tokens );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function get_provider_name(): string {
|
||||
return 'OpenRouter';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that the OpenRouter API key is configured and working.
|
||||
*
|
||||
* Makes a lightweight request to the /auth/key endpoint.
|
||||
*
|
||||
* Side effects: HTTP request to OpenRouter.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function validate_credentials(): bool {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$response = wp_remote_get(
|
||||
self::API_BASE_URL . '/auth/key',
|
||||
[
|
||||
'timeout' => 15,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $api_key,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 200 === wp_remote_retrieve_response_code( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decrypted API key from options.
|
||||
*
|
||||
* @return string Decrypted API key, or empty string if not set.
|
||||
*/
|
||||
private function get_api_key(): string {
|
||||
$encrypted = get_option( 'autoblogger_openrouter_api_key', '' );
|
||||
if ( '' === $encrypted ) {
|
||||
return '';
|
||||
}
|
||||
return Autoblogger_Encryption::decrypt( $encrypted );
|
||||
}
|
||||
}
|
||||
207
includes/providers/class-reddit-api-client.php
Executable file
207
includes/providers/class-reddit-api-client.php
Executable file
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Reddit API HTTP client for authenticated requests.
|
||||
*
|
||||
* Encapsulates OAuth2 token management, rate limit tracking, and HTTP methods
|
||||
* for the Reddit API. Decoupled from collection logic for testability.
|
||||
*
|
||||
* Triggered by: Autoblogger_Reddit_Provider calls fetch methods here.
|
||||
* Dependencies: Autoblogger_Encryption (for client secret), wp_remote_post/get().
|
||||
*
|
||||
* @see providers/class-reddit-provider.php — Instantiates this class.
|
||||
* @see ARCHITECTURE.md — External API integrations table.
|
||||
*/
|
||||
class Autoblogger_Reddit_API_Client {
|
||||
|
||||
private const AUTH_URL = 'https://www.reddit.com/api/v1/access_token';
|
||||
private const API_BASE = 'https://oauth.reddit.com';
|
||||
private const USER_AGENT = 'AutoBlogger/0.1.0 (WordPress Plugin)';
|
||||
|
||||
/**
|
||||
* Get an OAuth2 access token, using cached transient if available.
|
||||
*
|
||||
* Reddit script apps use client_credentials grant type.
|
||||
*
|
||||
* Side effects: HTTP request, sets transient.
|
||||
*
|
||||
* @param bool $force_refresh Bypass cache and request a new token.
|
||||
*
|
||||
* @return string Access token, or empty string on failure.
|
||||
*/
|
||||
public function get_access_token( bool $force_refresh = false ): string {
|
||||
if ( ! $force_refresh ) {
|
||||
$cached = get_transient( 'autoblogger_reddit_token' );
|
||||
if ( false !== $cached && is_string( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
$client_id = get_option( 'autoblogger_reddit_client_id', '' );
|
||||
$client_secret = Autoblogger_Encryption::decrypt(
|
||||
get_option( 'autoblogger_reddit_client_secret', '' )
|
||||
);
|
||||
|
||||
if ( '' === $client_id || '' === $client_secret ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$response = wp_remote_post(
|
||||
self::AUTH_URL,
|
||||
[
|
||||
'timeout' => 15,
|
||||
'headers' => [
|
||||
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
'Authorization' => 'Basic ' . base64_encode( $client_id . ':' . $client_secret ),
|
||||
'User-Agent' => self::USER_AGENT,
|
||||
],
|
||||
'body' => [
|
||||
'grant_type' => 'client_credentials',
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Reddit OAuth failed: ' . $response->get_error_message(), 'reddit' );
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Reddit OAuth HTTP ' . wp_remote_retrieve_response_code( $response ), 'reddit' );
|
||||
return '';
|
||||
}
|
||||
|
||||
$data = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
if ( ! isset( $data['access_token'] ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Reddit OAuth response missing access_token.', 'reddit' );
|
||||
return '';
|
||||
}
|
||||
|
||||
$token = $data['access_token'];
|
||||
$expires = isset( $data['expires_in'] ) ? (int) $data['expires_in'] - 60 : 3540;
|
||||
|
||||
set_transient( 'autoblogger_reddit_token', $token, $expires );
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch posts from a subreddit.
|
||||
*
|
||||
* @param string $token OAuth access token.
|
||||
* @param string $subreddit Subreddit name (without r/ prefix).
|
||||
* @param int $limit Max posts to fetch.
|
||||
* @param string $time_filter Time filter for /top (hour, day, week, month, year, all).
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Array of post data.
|
||||
*/
|
||||
public function fetch_posts( string $token, string $subreddit, int $limit, string $time_filter ): array {
|
||||
$url = sprintf(
|
||||
'%s/r/%s/hot?limit=%d&t=%s',
|
||||
self::API_BASE,
|
||||
rawurlencode( $subreddit ),
|
||||
min( $limit, 100 ),
|
||||
rawurlencode( $time_filter )
|
||||
);
|
||||
|
||||
$response = $this->api_get( $token, $url );
|
||||
if ( null === $response || ! isset( $response['data']['children'] ) ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$posts = [];
|
||||
foreach ( $response['data']['children'] as $child ) {
|
||||
if ( isset( $child['data'] ) ) {
|
||||
$posts[] = $child['data'];
|
||||
}
|
||||
}
|
||||
|
||||
return $posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch top comments for a specific post.
|
||||
*
|
||||
* @param string $token OAuth access token.
|
||||
* @param string $subreddit Subreddit name.
|
||||
* @param string $post_id Reddit post ID (without t3_ prefix).
|
||||
* @param int $limit Max comments to fetch.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Array of comment data.
|
||||
*/
|
||||
public function fetch_comments( string $token, string $subreddit, string $post_id, int $limit ): array {
|
||||
$url = sprintf(
|
||||
'%s/r/%s/comments/%s?limit=%d&sort=top&depth=1',
|
||||
self::API_BASE,
|
||||
rawurlencode( $subreddit ),
|
||||
rawurlencode( $post_id ),
|
||||
min( $limit, 50 )
|
||||
);
|
||||
|
||||
$response = $this->api_get( $token, $url );
|
||||
|
||||
// Comments endpoint returns [post_listing, comments_listing].
|
||||
if ( ! is_array( $response ) || ! isset( $response[1]['data']['children'] ) ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$comments = [];
|
||||
foreach ( $response[1]['data']['children'] as $child ) {
|
||||
if ( isset( $child['data'] ) && 't1' === ( $child['kind'] ?? '' ) ) {
|
||||
$comments[] = $child['data'];
|
||||
}
|
||||
}
|
||||
|
||||
return $comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an authenticated GET request to the Reddit API.
|
||||
*
|
||||
* Updates rate limit tracking from response headers.
|
||||
*
|
||||
* @param string $token OAuth access token.
|
||||
* @param string $url Full API URL.
|
||||
*
|
||||
* @return array<string, mixed>|null Decoded response, or null on failure.
|
||||
*/
|
||||
public function api_get( string $token, string $url ): ?array {
|
||||
$response = wp_remote_get(
|
||||
$url,
|
||||
[
|
||||
'timeout' => 30,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'User-Agent' => self::USER_AGENT,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
Autoblogger_Logger::instance()->error( 'Reddit API GET failed: ' . $response->get_error_message(), 'reddit' );
|
||||
return null;
|
||||
}
|
||||
|
||||
// Track rate limits from response headers.
|
||||
$rate_remaining = wp_remote_retrieve_header( $response, 'x-ratelimit-remaining' );
|
||||
$rate_limit = wp_remote_retrieve_header( $response, 'x-ratelimit-used' );
|
||||
$rate_reset = wp_remote_retrieve_header( $response, 'x-ratelimit-reset' );
|
||||
|
||||
if ( '' !== $rate_remaining ) {
|
||||
set_transient( 'autoblogger_reddit_rate_limit', [
|
||||
'remaining' => (int) $rate_remaining,
|
||||
'limit' => (int) $rate_limit + (int) $rate_remaining,
|
||||
'resets_at' => gmdate( 'Y-m-d H:i:s', time() + (int) $rate_reset ),
|
||||
], 120 );
|
||||
}
|
||||
|
||||
$status_code = wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status_code ) {
|
||||
Autoblogger_Logger::instance()->error( sprintf( 'Reddit API HTTP %d: %s', $status_code, substr( wp_remote_retrieve_body( $response ), 0, 300 ) ), 'reddit' );
|
||||
return null;
|
||||
}
|
||||
|
||||
return json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
}
|
||||
}
|
||||
178
includes/providers/class-reddit-provider.php
Executable file
178
includes/providers/class-reddit-provider.php
Executable file
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Reddit API integration for collecting posts and comments from target subreddits.
|
||||
*
|
||||
* Uses Reddit's OAuth2 "script" app type for server-to-server authentication.
|
||||
* Collects hot/top posts and their top comments from configured subreddits,
|
||||
* storing them in the ab_source_data table.
|
||||
*
|
||||
* Triggered by: Source_Collector calls collect_data() on each enabled provider.
|
||||
* Dependencies: Autoblogger_Reddit_API_Client (for HTTP calls and auth).
|
||||
*
|
||||
* @see interface-source-provider.php — Interface this class implements.
|
||||
* @see providers/class-reddit-api-client.php — HTTP client for Reddit API.
|
||||
* @see core/class-source-collector.php — Orchestrates collection from all providers.
|
||||
* @see ARCHITECTURE.md — External API integrations table.
|
||||
*/
|
||||
class Autoblogger_Reddit_Provider implements Autoblogger_Source_Provider_Interface {
|
||||
|
||||
/**
|
||||
* Collect posts and comments from configured subreddits.
|
||||
*
|
||||
* For each subreddit: fetches hot posts, then fetches top comments for
|
||||
* the most-engaged posts. Returns an array of Source_Data objects.
|
||||
*
|
||||
* Side effects: HTTP requests to Reddit API, uses/sets transients for OAuth token.
|
||||
*
|
||||
* @param array{
|
||||
* subreddits?: string[],
|
||||
* limit?: int,
|
||||
* time_filter?: string,
|
||||
* include_comments?: bool,
|
||||
* comments_per_post?: int,
|
||||
* } $config Collection configuration.
|
||||
*
|
||||
* @return Autoblogger_Source_Data[]
|
||||
*
|
||||
* @throws \RuntimeException On authentication failure or API error.
|
||||
*/
|
||||
public function collect_data( array $config ): array {
|
||||
$api_client = new Autoblogger_Reddit_API_Client();
|
||||
$token = $api_client->get_access_token();
|
||||
if ( '' === $token ) {
|
||||
throw new \RuntimeException(
|
||||
__( 'Reddit authentication failed. Check client ID and secret in settings.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$subreddits = $config['subreddits'] ?? $this->get_configured_subreddits();
|
||||
$limit = $config['limit'] ?? 25;
|
||||
$time_filter = $config['time_filter'] ?? 'day';
|
||||
$include_comments = $config['include_comments'] ?? true;
|
||||
$comments_limit = $config['comments_per_post'] ?? 10;
|
||||
|
||||
$collected = [];
|
||||
|
||||
foreach ( $subreddits as $subreddit ) {
|
||||
$subreddit = sanitize_text_field( $subreddit );
|
||||
|
||||
try {
|
||||
$posts = $api_client->fetch_posts( $token, $subreddit, $limit, $time_filter );
|
||||
|
||||
foreach ( $posts as $post ) {
|
||||
$collected[] = new Autoblogger_Source_Data( [
|
||||
'source_type' => 'reddit',
|
||||
'source_id' => 't3_' . $post['id'],
|
||||
'subreddit' => $subreddit,
|
||||
'title' => $post['title'] ?? '',
|
||||
'content' => $post['selftext'] ?? '',
|
||||
'author' => $post['author'] ?? '[deleted]',
|
||||
'score' => (int) ( $post['score'] ?? 0 ),
|
||||
'comment_count' => (int) ( $post['num_comments'] ?? 0 ),
|
||||
'permalink' => 'https://reddit.com' . ( $post['permalink'] ?? '' ),
|
||||
'collected_at' => current_time( 'mysql' ),
|
||||
'metadata' => [
|
||||
'post_type' => $post['is_self'] ? 'self' : 'link',
|
||||
'flair' => $post['link_flair_text'] ?? null,
|
||||
'created_utc' => $post['created_utc'] ?? 0,
|
||||
'upvote_ratio' => $post['upvote_ratio'] ?? 0,
|
||||
'is_original' => $post['is_original_content'] ?? false,
|
||||
],
|
||||
] );
|
||||
|
||||
// Collect top comments for high-engagement posts.
|
||||
if ( $include_comments && ( $post['num_comments'] ?? 0 ) > 5 ) {
|
||||
$comments = $api_client->fetch_comments(
|
||||
$token,
|
||||
$subreddit,
|
||||
$post['id'],
|
||||
$comments_limit
|
||||
);
|
||||
|
||||
foreach ( $comments as $comment ) {
|
||||
$collected[] = new Autoblogger_Source_Data( [
|
||||
'source_type' => 'reddit',
|
||||
'source_id' => 't1_' . $comment['id'],
|
||||
'subreddit' => $subreddit,
|
||||
'title' => null,
|
||||
'content' => $comment['body'] ?? '',
|
||||
'author' => $comment['author'] ?? '[deleted]',
|
||||
'score' => (int) ( $comment['score'] ?? 0 ),
|
||||
'comment_count' => 0,
|
||||
'permalink' => 'https://reddit.com' . ( $comment['permalink'] ?? '' ),
|
||||
'collected_at' => current_time( 'mysql' ),
|
||||
'metadata' => [
|
||||
'parent_post_id' => 't3_' . $post['id'],
|
||||
'parent_title' => $post['title'] ?? '',
|
||||
'is_comment' => true,
|
||||
'created_utc' => $comment['created_utc'] ?? 0,
|
||||
],
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch ( \Exception $e ) {
|
||||
// Log but continue with other subreddits.
|
||||
Autoblogger_Logger::instance()->error(
|
||||
sprintf( 'Reddit: Failed to collect from r/%s: %s', $subreddit, $e->getMessage() ),
|
||||
'reddit'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $collected;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function get_source_type(): string {
|
||||
return 'reddit';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Reddit API credentials.
|
||||
*
|
||||
* Side effects: HTTP request to Reddit OAuth endpoint.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function validate_credentials(): bool {
|
||||
$api_client = new Autoblogger_Reddit_API_Client();
|
||||
$token = $api_client->get_access_token( true );
|
||||
return '' !== $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current rate limit status from last response headers.
|
||||
*
|
||||
* @return array{remaining: int, limit: int, resets_at: string}
|
||||
*/
|
||||
public function get_rate_limit_status(): array {
|
||||
// Reddit rate limits are tracked per-response via headers.
|
||||
// We store the last seen values in a transient.
|
||||
$status = get_transient( 'autoblogger_reddit_rate_limit' );
|
||||
if ( is_array( $status ) ) {
|
||||
return $status;
|
||||
}
|
||||
return [
|
||||
'remaining' => 100,
|
||||
'limit' => 100,
|
||||
'resets_at' => '',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the list of subreddits configured in plugin settings.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function get_configured_subreddits(): array {
|
||||
$json = get_option( 'autoblogger_target_subreddits', '[]' );
|
||||
$list = json_decode( $json, true );
|
||||
return is_array( $list ) ? $list : [];
|
||||
}
|
||||
}
|
||||
40
includes/providers/class-tiktok-provider.php
Executable file
40
includes/providers/class-tiktok-provider.php
Executable file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* TikTok source provider — STUB for future implementation.
|
||||
*
|
||||
* Will integrate with TikTok's API to collect video descriptions, comments,
|
||||
* and trending topics. Requires TikTok developer app credentials.
|
||||
*
|
||||
* Triggered by: Source_Collector when 'tiktok' is in enabled_sources.
|
||||
* Dependencies: TBD — TikTok API credentials.
|
||||
*
|
||||
* @see interface-source-provider.php — Interface this class implements.
|
||||
* @see ARCHITECTURE.md — Planned source providers.
|
||||
*/
|
||||
class Autoblogger_Tiktok_Provider implements Autoblogger_Source_Provider_Interface {
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config
|
||||
* @return Autoblogger_Source_Data[]
|
||||
* @throws \RuntimeException Always — not yet implemented.
|
||||
*/
|
||||
public function collect_data( array $config ): array {
|
||||
throw new \RuntimeException(
|
||||
__( 'TikTok source provider is not yet implemented. Remove "tiktok" from enabled sources.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
public function get_source_type(): string {
|
||||
return 'tiktok';
|
||||
}
|
||||
|
||||
public function validate_credentials(): bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
public function get_rate_limit_status(): array {
|
||||
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
|
||||
}
|
||||
}
|
||||
39
includes/providers/class-youtube-provider.php
Executable file
39
includes/providers/class-youtube-provider.php
Executable file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* YouTube source provider — STUB for future implementation.
|
||||
*
|
||||
* Will integrate with YouTube Data API v3 to collect video titles,
|
||||
* descriptions, comments, and trending topics. Requires Google API key.
|
||||
*
|
||||
* Triggered by: Source_Collector when 'youtube' is in enabled_sources.
|
||||
* Dependencies: TBD — YouTube Data API key.
|
||||
*
|
||||
* @see interface-source-provider.php — Interface this class implements.
|
||||
*/
|
||||
class Autoblogger_Youtube_Provider implements Autoblogger_Source_Provider_Interface {
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config
|
||||
* @return Autoblogger_Source_Data[]
|
||||
* @throws \RuntimeException Always — not yet implemented.
|
||||
*/
|
||||
public function collect_data( array $config ): array {
|
||||
throw new \RuntimeException(
|
||||
__( 'YouTube source provider is not yet implemented. Remove "youtube" from enabled sources.', 'autoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
public function get_source_type(): string {
|
||||
return 'youtube';
|
||||
}
|
||||
|
||||
public function validate_credentials(): bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
public function get_rate_limit_status(): array {
|
||||
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
|
||||
}
|
||||
}
|
||||
71
includes/providers/interface-llm-provider.php
Executable file
71
includes/providers/interface-llm-provider.php
Executable file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Contract for any LLM provider integration (OpenRouter, direct Anthropic, OpenAI, etc.).
|
||||
*
|
||||
* Any class implementing this interface can be swapped in without changing the
|
||||
* content generation, analysis, or editor logic.
|
||||
*
|
||||
* @see class-openrouter-provider.php — Primary implementation (OpenRouter).
|
||||
* @see CONVENTIONS.md — "How To: Add a New LLM Provider".
|
||||
* @see ARCHITECTURE.md — External API integrations table.
|
||||
*/
|
||||
interface Autoblogger_LLM_Provider_Interface {
|
||||
|
||||
/**
|
||||
* Send a chat completion request to the LLM.
|
||||
*
|
||||
* @param array<int, array{role: string, content: string}> $messages Chat messages array.
|
||||
* @param string $model Model identifier (e.g., 'anthropic/claude-sonnet-4').
|
||||
* @param array{
|
||||
* temperature?: float,
|
||||
* max_tokens?: int,
|
||||
* response_format?: array{type: string},
|
||||
* } $options Optional parameters for the API call.
|
||||
*
|
||||
* @return array{
|
||||
* content: string,
|
||||
* model: string,
|
||||
* prompt_tokens: int,
|
||||
* completion_tokens: int,
|
||||
* total_tokens: int,
|
||||
* finish_reason: string,
|
||||
* } Normalized response.
|
||||
*
|
||||
* @throws \RuntimeException On API error after retries exhausted.
|
||||
*/
|
||||
public function send_chat_completion( array $messages, string $model, array $options = [] ): array;
|
||||
|
||||
/**
|
||||
* Get the list of available models from the provider.
|
||||
*
|
||||
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}> Available models.
|
||||
*/
|
||||
public function get_available_models(): array;
|
||||
|
||||
/**
|
||||
* Estimate the cost of an API call based on token counts.
|
||||
*
|
||||
* @param string $model Model identifier.
|
||||
* @param int $prompt_tokens Number of input tokens.
|
||||
* @param int $completion_tokens Number of output tokens.
|
||||
*
|
||||
* @return float Estimated cost in USD.
|
||||
*/
|
||||
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float;
|
||||
|
||||
/**
|
||||
* Get the human-readable name of this provider.
|
||||
*
|
||||
* @return string Provider name (e.g., 'OpenRouter').
|
||||
*/
|
||||
public function get_provider_name(): string;
|
||||
|
||||
/**
|
||||
* Validate that the provider's credentials are configured and working.
|
||||
*
|
||||
* @return bool True if credentials are valid.
|
||||
*/
|
||||
public function validate_credentials(): bool;
|
||||
}
|
||||
58
includes/providers/interface-source-provider.php
Executable file
58
includes/providers/interface-source-provider.php
Executable file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Contract for any social media source provider (Reddit, TikTok, Instagram, YouTube).
|
||||
*
|
||||
* Any class implementing this interface can be registered as a data source.
|
||||
* The Source_Collector iterates through enabled providers and calls collect_data().
|
||||
*
|
||||
* @see class-reddit-provider.php — Primary implementation (Reddit API).
|
||||
* @see core/class-source-collector.php — Orchestrates collection from all providers.
|
||||
* @see CONVENTIONS.md — "How To: Add a New Source Provider".
|
||||
*/
|
||||
interface Autoblogger_Source_Provider_Interface {
|
||||
|
||||
/**
|
||||
* Collect posts/comments from this social platform.
|
||||
*
|
||||
* @param array{
|
||||
* subreddits?: string[],
|
||||
* limit?: int,
|
||||
* time_filter?: string,
|
||||
* keywords?: string[],
|
||||
* } $config Source-specific configuration.
|
||||
*
|
||||
* @return Autoblogger_Source_Data[] Array of collected data objects.
|
||||
*
|
||||
* @throws \RuntimeException On API error after retries exhausted.
|
||||
*/
|
||||
public function collect_data( array $config ): array;
|
||||
|
||||
/**
|
||||
* Get the source type identifier for this provider.
|
||||
*
|
||||
* Must match a valid value for ab_source_data.source_type.
|
||||
*
|
||||
* @return string Source type (e.g., 'reddit', 'tiktok', 'youtube').
|
||||
*/
|
||||
public function get_source_type(): string;
|
||||
|
||||
/**
|
||||
* Validate that the provider's API credentials are configured and working.
|
||||
*
|
||||
* @return bool True if credentials are valid and API is reachable.
|
||||
*/
|
||||
public function validate_credentials(): bool;
|
||||
|
||||
/**
|
||||
* Get current rate limit status for this provider's API.
|
||||
*
|
||||
* @return array{
|
||||
* remaining: int,
|
||||
* limit: int,
|
||||
* resets_at: string,
|
||||
* } Rate limit information.
|
||||
*/
|
||||
public function get_rate_limit_status(): array;
|
||||
}
|
||||
Reference in New Issue
Block a user