Hold donations with flagged donor names for moderation; reconcile lost side effects (schema v6)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
473fe192cd
commit
353f7ca5be
16 files changed
+681
-41
No files matched your search
@@ -6,21 +6,27 @@ namespace StreamGoals\Actions;
|
||||
/** Queues the on-stream actions a completed donation triggers. */
|
||||
final class Recorder {
|
||||
|
||||
/** Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events. */
|
||||
public static function forDonation( int $donationId ): void {
|
||||
/**
|
||||
* Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events.
|
||||
*
|
||||
* @return bool False only when something failed (so the caller must not mark the donation's effects as applied).
|
||||
*/
|
||||
public static function forDonation( int $donationId ): bool {
|
||||
try {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, base_minor, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
|
||||
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) ) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
$repo = new ActionRepository( $wpdb );
|
||||
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
|
||||
if ( $matches ) {
|
||||
$repo->recordEvents( $donationId, $matches );
|
||||
}
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ final class DonationsPage {
|
||||
echo Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
|
||||
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Fee' ) . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td>' . Admin::td( 'Total paid' ) . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
|
||||
echo Admin::td( 'Goal' ) . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
|
||||
echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
|
||||
echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (string) $r['moderation'] ) . '</span>' ) . '</td>';
|
||||
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td></tr>';
|
||||
}
|
||||
echo Admin::tableClose();
|
||||
@@ -72,22 +72,22 @@ final class DonationsPage {
|
||||
}
|
||||
|
||||
public static function renderModeration(): void {
|
||||
Admin::open( 'Message moderation' );
|
||||
Admin::open( 'Moderation' );
|
||||
if ( ! Settings::get( 'moderate_messages' ) ) {
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.</p></div>';
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. A donor name that trips the profanity filter is still held here, and anything else waiting below was submitted earlier.</p></div>';
|
||||
}
|
||||
echo '<p class="description">Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.</p>';
|
||||
echo '<p class="description">Held donations stay out of alerts (and the public donor feed) until you approve them. Rejected ones are never shown. A donor name that trips the profanity filter is held here too; it is already masked (for example f***), and approving shows it masked. The donation itself still counts towards your goal, timer and counters either way.</p>';
|
||||
$res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 );
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>Nothing waiting for review.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Decision' ), 'Messages waiting for review' );
|
||||
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Flagged', 'Decision' ), 'Donations waiting for review' );
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
echo '<tr>' . Admin::td( 'Date' ) . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>' . Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . '</td>';
|
||||
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Decision', 'sg-actions' );
|
||||
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Flagged' ) . esc_html( Format::flaggedLabel( $r ) ) . '</td>' . Admin::td( 'Decision', 'sg-actions' );
|
||||
foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) {
|
||||
Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' );
|
||||
echo '<button class="button' . ( 'approved' === $to ? ' button-primary' : '' ) . '">' . esc_html( $lbl ) . '</button></form> ';
|
||||
@@ -104,7 +104,7 @@ final class DonationsPage {
|
||||
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
|
||||
$to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : '';
|
||||
$ok = $id && Store::setModeration( $id, $to );
|
||||
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' );
|
||||
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Donation approved.' : 'Donation rejected.' ) : 'That donation could not be updated (it may already be reviewed).' );
|
||||
}
|
||||
|
||||
public static function handleExport(): void {
|
||||
|
||||
@@ -61,4 +61,15 @@ final class Format {
|
||||
}
|
||||
return (string) $row['donor_name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* What is being held for review, from sg_donations.moderation_flags: 'Name', 'Message' or 'Name and message'.
|
||||
* Rows held before flags existed (empty value) were always held for their message.
|
||||
*/
|
||||
public static function flaggedLabel( array $row ): string {
|
||||
$flags = array_filter( array_map( 'trim', explode( ',', (string) ( $row['moderation_flags'] ?? '' ) ) ) );
|
||||
$name = in_array( 'name', $flags, true );
|
||||
$msg = in_array( 'message', $flags, true ) || ! $name;
|
||||
return $name && $msg ? 'Name and message' : ( $name ? 'Name' : 'Message' );
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ final class SettingsPage {
|
||||
|
||||
echo '<div class="sg-card"><h2>Messages</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Moderation</th><td><label><input type="checkbox" name="moderate_messages" value="1"' . checked( ! empty( $s['moderate_messages'] ), true, false ) . '> Hold messages for my approval before they can be shown in alerts</label></td></tr>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Filter bad language in messages and names</label><br>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Mask bad language in messages and donor names</label> <span class="description">A donor name that trips the filter is masked and the donation is held on the Moderation screen before its alert can show (it still counts towards your goal).</span><br>';
|
||||
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
|
||||
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ final class DonationRepository {
|
||||
|
||||
/** @return int|null new id, or null on failure (e.g. duplicate capture id). */
|
||||
public function insert( array $d ): ?int {
|
||||
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation' );
|
||||
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation', 'moderation_flags' );
|
||||
$row = array_intersect_key( $d, array_flip( $allowed ) );
|
||||
$row += array( 'status' => 'pending', 'moderation' => 'approved', 'fee_minor' => 0 );
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
|
||||
@@ -8,10 +8,10 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '5';
|
||||
public const DB_VERSION = '6';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
self::install_schema( get_option( 'sg_db_version' ) );
|
||||
if ( false === get_option( 'sg_settings' ) ) {
|
||||
add_option( 'sg_settings', Settings::defaults(), '', false );
|
||||
}
|
||||
@@ -20,12 +20,33 @@ final class Installer {
|
||||
|
||||
/** Run on plugins_loaded so upgrades apply without re-activation. */
|
||||
public static function maybe_upgrade(): void {
|
||||
if ( get_option( 'sg_db_version' ) !== self::DB_VERSION ) {
|
||||
self::install_schema();
|
||||
$from = get_option( 'sg_db_version' );
|
||||
if ( $from !== self::DB_VERSION ) {
|
||||
self::install_schema( $from );
|
||||
}
|
||||
}
|
||||
|
||||
private static function install_schema(): void {
|
||||
/** Schema v6 added sg_donations.effects_applied_at; rows completed before that must not be replayed. */
|
||||
public static function needsEffectsBackfill( mixed $from ): bool {
|
||||
return false === $from || '' === $from || version_compare( (string) $from, '6', '<' );
|
||||
}
|
||||
|
||||
/**
|
||||
* One-time upgrade step: every donation that is ALREADY completed had its side effects applied by the code that
|
||||
* completed it (or was lost before this feature existed and is not worth replaying), so stamp it. Without this the
|
||||
* reconciler would replay the whole history. Only touches NULL rows, so re-running is harmless. False on DB error.
|
||||
*/
|
||||
public static function backfill_effects_applied(): bool {
|
||||
global $wpdb;
|
||||
$n = $wpdb->query( $wpdb->prepare(
|
||||
'UPDATE ' . $wpdb->prefix . "sg_donations SET effects_applied_at = %s WHERE status = 'completed' AND effects_applied_at IS NULL",
|
||||
gmdate( 'Y-m-d H:i:s' )
|
||||
) );
|
||||
return false !== $n;
|
||||
}
|
||||
|
||||
/** @param mixed $from Previously installed sg_db_version (false when never installed). */
|
||||
private static function install_schema( mixed $from = false ): void {
|
||||
global $wpdb;
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
$c = $wpdb->get_charset_collate();
|
||||
@@ -59,6 +80,8 @@ final class Installer {
|
||||
message VARCHAR(500) NOT NULL DEFAULT '',
|
||||
status VARCHAR(12) NOT NULL DEFAULT 'pending',
|
||||
moderation VARCHAR(10) NOT NULL DEFAULT 'approved',
|
||||
moderation_flags VARCHAR(16) NOT NULL DEFAULT '',
|
||||
effects_applied_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY capture (paypal_capture_id),
|
||||
@@ -159,6 +182,11 @@ final class Installer {
|
||||
KEY reached_donation (reached_donation_id)
|
||||
) $c;" );
|
||||
|
||||
// Backfill BEFORE recording the new version: if it fails, the next load retries instead of replaying history.
|
||||
if ( self::needsEffectsBackfill( $from ) && ! self::backfill_effects_applied() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,87 @@ final class Maintenance {
|
||||
public const HOOK = 'sg_purge_abandoned';
|
||||
public const MAX_AGE_DAYS = 7;
|
||||
|
||||
/** Reconcile "completed but side effects lost" donations (see reconcile_effects()). */
|
||||
public const RECONCILE_HOOK = 'sg_reconcile_effects';
|
||||
public const RECONCILE_SCHEDULE = 'sg_five_minutes';
|
||||
/** A donation must be this old before it is replayed, so a request still applying its effects is left alone. */
|
||||
public const RECONCILE_MIN_AGE = 120;
|
||||
/** Older donations are not retried (a row that can never succeed must not be replayed forever). */
|
||||
public const RECONCILE_MAX_AGE_DAYS = 30;
|
||||
public const RECONCILE_BATCH = 25;
|
||||
|
||||
public static function register(): void {
|
||||
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
|
||||
if ( ! wp_next_scheduled( self::HOOK ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
|
||||
}
|
||||
add_filter( 'cron_schedules', array( self::class, 'cron_schedules' ) );
|
||||
add_action( self::RECONCILE_HOOK, array( self::class, 'reconcile_effects' ) );
|
||||
if ( ! wp_next_scheduled( self::RECONCILE_HOOK ) ) {
|
||||
wp_schedule_event( time() + 300, self::RECONCILE_SCHEDULE, self::RECONCILE_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array $schedules @return array */
|
||||
public static function cron_schedules( $schedules ): array {
|
||||
$schedules = is_array( $schedules ) ? $schedules : array();
|
||||
$schedules[ self::RECONCILE_SCHEDULE ] = array( 'interval' => 300, 'display' => 'Every five minutes (StreamGoals)' );
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
public static function unschedule(): void {
|
||||
wp_clear_scheduled_hook( self::HOOK );
|
||||
wp_clear_scheduled_hook( self::RECONCILE_HOOK );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the side effects (rules/timer/counter, rewards, tiers, end-at-target) of completed donations whose request
|
||||
* died before DonationStore::notify_applied() could stamp effects_applied_at. Safe by construction: every effect is
|
||||
* idempotent per (rule, donation) / (donation, action) / tier, and the donation row itself is never touched here.
|
||||
* Single-flight through a MySQL named lock so overlapping cron runs do not pile up.
|
||||
*
|
||||
* @return int Donations whose effects were confirmed applied by this run.
|
||||
*/
|
||||
public static function reconcile_effects(): int {
|
||||
global $wpdb;
|
||||
$locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'sg_reconcile_effects' ) );
|
||||
if ( ! $locked ) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return self::reconcile(
|
||||
time(),
|
||||
array( \StreamGoals\PayPal\DonationStore::class, 'unapplied_completed_ids' ),
|
||||
array( \StreamGoals\PayPal\DonationStore::class, 'notify_applied' )
|
||||
);
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: reconcile failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return 0;
|
||||
} finally {
|
||||
$wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'sg_reconcile_effects' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure orchestration (unit-tested).
|
||||
*
|
||||
* @param callable $find fn(string $notAfter, string $notBefore, int $limit): int[]
|
||||
* @param callable $apply fn(int $donationId): bool true once the donation is stamped as applied
|
||||
*/
|
||||
public static function reconcile( int $now, callable $find, callable $apply ): int {
|
||||
$notAfter = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MIN_AGE );
|
||||
$notBefore = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MAX_AGE_DAYS * 86400 );
|
||||
$done = 0;
|
||||
foreach ( (array) $find( $notAfter, $notBefore, self::RECONCILE_BATCH ) as $id ) {
|
||||
try {
|
||||
if ( $apply( (int) $id ) ) {
|
||||
++$done;
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: reconcile of donation ' . (int) $id . ' failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
}
|
||||
return $done;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -58,8 +58,23 @@ final class ProfanityFilter {
|
||||
return $this->enabled && array() !== $this->words;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when at least one word of $text is listed, i.e. filter() would change it. Same rules as filter()
|
||||
* (whole words, leetspeak, case-insensitive). Used to hold a donor name for moderation. Never throws.
|
||||
*/
|
||||
public function matches( string $text ): bool {
|
||||
$hit = false;
|
||||
$this->scan( $text, $hit );
|
||||
return $hit;
|
||||
}
|
||||
|
||||
/** Mask every listed word; everything else is returned byte-for-byte (after UTF-8 scrubbing). */
|
||||
public function filter( string $text ): string {
|
||||
$hit = false;
|
||||
return $this->scan( $text, $hit );
|
||||
}
|
||||
|
||||
private function scan( string $text, bool &$hit ): string {
|
||||
if ( ! $this->isEnabled() || '' === $text ) {
|
||||
return $text;
|
||||
}
|
||||
@@ -70,13 +85,14 @@ final class ProfanityFilter {
|
||||
$text = mb_scrub( $text, 'UTF-8' );
|
||||
$out = preg_replace_callback(
|
||||
'/[\p{L}\p{M}\p{N}@$!]+/u',
|
||||
function ( array $m ): string {
|
||||
function ( array $m ) use ( &$hit ): string {
|
||||
$tok = $m[0];
|
||||
// "!" is only a leet char inside a word; trailing/leading punctuation is not part of it.
|
||||
$core = trim( $tok, '!' );
|
||||
if ( '' === $core || ! $this->isListed( $core ) ) {
|
||||
return $tok;
|
||||
}
|
||||
$hit = true;
|
||||
$lead = (int) strspn( $tok, '!' );
|
||||
$trail = strlen( $tok ) - strlen( rtrim( $tok, '!' ) );
|
||||
return str_repeat( '!', $lead ) . str_repeat( '*', mb_strlen( $core ) ) . str_repeat( '!', $trail );
|
||||
|
||||
@@ -82,6 +82,7 @@ final class Uninstaller {
|
||||
public static function run_site( object $wpdb ): void {
|
||||
$delete = self::wants_data_deleted( get_option( 'sg_settings', array() ) );
|
||||
wp_clear_scheduled_hook( self::CRON_HOOK );
|
||||
wp_clear_scheduled_hook( Maintenance::RECONCILE_HOOK );
|
||||
self::delete_dynamic_transients( $wpdb );
|
||||
if ( $delete ) {
|
||||
self::drop_tables( $wpdb );
|
||||
|
||||
@@ -60,9 +60,10 @@ final class DonationStore {
|
||||
'message' => $v['message'],
|
||||
'status' => 'pending',
|
||||
'moderation' => $v['moderation'],
|
||||
'moderation_flags' => (string) ( $v['moderation_flags'] ?? '' ),
|
||||
'created_at' => gmdate( 'Y-m-d H:i:s' ),
|
||||
),
|
||||
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
|
||||
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' )
|
||||
);
|
||||
return $ok ? (int) $wpdb->insert_id : 0;
|
||||
}
|
||||
@@ -98,37 +99,71 @@ final class DonationStore {
|
||||
return 1 === $n;
|
||||
}
|
||||
|
||||
/** Hand a freshly completed donation to the rules engine (if present). Never throws. */
|
||||
public static function notify_applied( int $id ): void {
|
||||
self::call_engine( 'applyDonation', $id );
|
||||
/**
|
||||
* Run every side effect of a completed donation (rules/timer/counter, rewards, tiers, end-at-target) and, only if ALL of
|
||||
* them finished without error, stamp sg_donations.effects_applied_at. Never throws. Every step is idempotent, so this is
|
||||
* also what Maintenance::reconcile_effects() replays for a donation whose request died after mark_completed().
|
||||
*
|
||||
* @return bool True when the donation is (now) marked as fully applied.
|
||||
*/
|
||||
public static function notify_applied( int $id ): bool {
|
||||
$ok = self::call_engine( 'applyDonation', $id );
|
||||
// Donation actions (rewards). Not under the goal lock: events are idempotent via a UNIQUE key. Never throws.
|
||||
try {
|
||||
\StreamGoals\Actions\Recorder::forDonation( $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
if ( ! \StreamGoals\Actions\Recorder::forDonation( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
|
||||
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
|
||||
try {
|
||||
\StreamGoals\Tiers\Recorder::forDonation( $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: tier unlock failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
self::close_goal_if_target_reached( $id );
|
||||
if ( ! self::close_goal_if_target_reached( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
return $ok && self::mark_effects_applied( $id );
|
||||
}
|
||||
|
||||
/** Stamp "side effects applied" once. Only a completed row with a NULL stamp is touched (first stamp wins). */
|
||||
public static function mark_effects_applied( int $id ): bool {
|
||||
global $wpdb;
|
||||
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET effects_applied_at = %s WHERE id = %d AND status = 'completed' AND effects_applied_at IS NULL", gmdate( 'Y-m-d H:i:s' ), $id ) );
|
||||
return false !== $n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed donations whose side effects were never confirmed: completed, effects_applied_at NULL, a real goal
|
||||
* (test rows use goal_id 0), created between $notBefore and $notAfter (UTC 'Y-m-d H:i:s'; the lower bound keeps a
|
||||
* permanently failing row from being retried forever, the upper bound leaves in-flight requests alone). Oldest first.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public static function unapplied_completed_ids( string $notAfter, string $notBefore, int $limit ): array {
|
||||
global $wpdb;
|
||||
$ids = $wpdb->get_col( $wpdb->prepare(
|
||||
'SELECT id FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0 AND created_at < %s AND created_at >= %s ORDER BY id ASC LIMIT %d",
|
||||
$notAfter,
|
||||
$notBefore,
|
||||
max( 1, $limit )
|
||||
) );
|
||||
return array_map( 'intval', (array) $ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
|
||||
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
|
||||
*
|
||||
* @return bool False when the check failed.
|
||||
*/
|
||||
public static function close_goal_if_target_reached( int $donationId ): void {
|
||||
public static function close_goal_if_target_reached( int $donationId ): bool {
|
||||
try {
|
||||
$row = self::find( $donationId );
|
||||
if ( $row && (int) $row->goal_id > 0 ) {
|
||||
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
|
||||
}
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,10 +173,10 @@ final class DonationStore {
|
||||
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): void {
|
||||
private static function call_engine( string $method, int $id ): bool {
|
||||
$row = self::find( $id );
|
||||
if ( ! $row ) {
|
||||
return;
|
||||
return false; // vanished row: nothing to apply, and never claim success
|
||||
}
|
||||
try {
|
||||
$donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row );
|
||||
@@ -151,8 +186,10 @@ final class DonationStore {
|
||||
\StreamGoals\Rules\Engine::default()->$method( $donation );
|
||||
}
|
||||
);
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ final class OrderValidator {
|
||||
* @param array $input Raw client params (goal_id, amount, display_name, anonymous, message, cover_fees).
|
||||
* @param array $goal sg_goals row as array (id, currency, status, starts_at, ends_at).
|
||||
* @param array $settings Settings::all()-shaped array.
|
||||
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string}
|
||||
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string,moderation_flags:string}
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function validate( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
|
||||
@@ -59,9 +59,20 @@ final class OrderValidator {
|
||||
}
|
||||
|
||||
// Mask profanity before anything is stored (same-length masking, so length checks above still hold).
|
||||
$filter = new ProfanityFilter( $settings );
|
||||
$name = $filter->filter( $name );
|
||||
$message = $filter->filter( $message );
|
||||
// A donor name that trips the filter is stored masked AND held for moderation (the donation still completes
|
||||
// and counts). Anonymous names were blanked above, so they can never flag.
|
||||
$filter = new ProfanityFilter( $settings );
|
||||
$nameFlagged = '' !== $name && $filter->matches( $name );
|
||||
$name = $filter->filter( $name );
|
||||
$message = $filter->filter( $message );
|
||||
$msgHeld = ! empty( $settings['moderate_messages'] ) && '' !== $message;
|
||||
$flags = array();
|
||||
if ( $nameFlagged ) {
|
||||
$flags[] = 'name';
|
||||
}
|
||||
if ( $msgHeld ) {
|
||||
$flags[] = 'message';
|
||||
}
|
||||
|
||||
return array(
|
||||
'goal_id' => (int) $goal['id'],
|
||||
@@ -73,7 +84,8 @@ final class OrderValidator {
|
||||
'is_anonymous' => $anon,
|
||||
'message' => $message,
|
||||
'cover_fees' => $cover,
|
||||
'moderation' => ( ! empty( $settings['moderate_messages'] ) && '' !== $message ) ? 'pending' : 'approved',
|
||||
'moderation' => $flags ? 'pending' : 'approved',
|
||||
'moderation_flags' => implode( ',', $flags ), // '', 'name', 'message' or 'name,message' (why it is held)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ final class Recorder {
|
||||
* @return int[] ids of the tiers this call unlocked.
|
||||
*/
|
||||
public static function forDonation( int $donationId ): array {
|
||||
return self::forDonationChecked( $donationId ) ?? array();
|
||||
}
|
||||
|
||||
/** Same as forDonation() but null (instead of an empty list) when something failed. Never throws. @return int[]|null */
|
||||
public static function forDonationChecked( int $donationId ): ?array {
|
||||
try {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
|
||||
@@ -27,7 +32,7 @@ final class Recorder {
|
||||
return $repo->markReached( $goalId, $raised, $donationId );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return array();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user