prefix . 'sg_' . $name; } public static function goal( int $id ): ?array { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'goals' ) . ' WHERE id = %d', $id ), ARRAY_A ); return $row ?: null; } /** @return array[] */ public static function active_goals(): array { global $wpdb; $rows = $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'active' ORDER BY id ASC", ARRAY_A ); $now = time(); return array_values( array_filter( (array) $rows, static fn( array $g ): bool => OrderValidator::goalIsOpen( $g, $now ) ) ); } public static function find( int $id ): ?object { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id = %d', $id ) ) ?: null; } public static function find_by_order( string $orderId ): ?object { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_order_id = %s ORDER BY id DESC LIMIT 1', $orderId ) ) ?: null; } public static function find_by_capture( string $captureId ): ?object { global $wpdb; if ( '' === $captureId ) { return null; } return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_capture_id = %s', $captureId ) ) ?: null; } /** @param array $v Output of OrderValidator::validate(). @return int Donation id (0 on failure). */ public static function insert_pending( array $v ): int { global $wpdb; $ok = $wpdb->insert( self::t( 'donations' ), array( 'goal_id' => $v['goal_id'], 'paypal_order_id' => '', 'base_minor' => $v['base_minor'], 'fee_minor' => $v['fee_minor'], 'total_minor' => $v['total_minor'], 'currency' => $v['currency'], 'donor_name' => $v['donor_name'], 'is_anonymous' => $v['is_anonymous'] ? 1 : 0, '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', '%s' ) ); return $ok ? (int) $wpdb->insert_id : 0; } public static function set_order_id( int $id, string $orderId ): void { global $wpdb; $wpdb->update( self::t( 'donations' ), array( 'paypal_order_id' => $orderId ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); } public static function delete( int $id ): void { global $wpdb; $wpdb->delete( self::t( 'donations' ), array( 'id' => $id ), array( '%d' ) ); } /** Atomic pending -> completed. True only for the single caller that wins the transition. */ public static function mark_completed( int $id, string $captureId ): bool { global $wpdb; $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET status = 'completed', paypal_capture_id = %s WHERE id = %d AND status = 'pending'", $captureId, $id ) ); return 1 === $n; } /** * Remember the PayPal capture id of a capture that is not final yet (PENDING / under review). Only touches a * still-pending row that has no capture id; never changes the status. This is the "PayPal took the money" evidence * that keeps Maintenance::purge_abandoned away and lets the COMPLETED webhook find the row by capture id. */ public static function record_capture_id( int $id, string $captureId ): bool { global $wpdb; if ( '' === $captureId ) { return false; } $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET paypal_capture_id = %s WHERE id = %d AND status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '')", $captureId, $id ) ); return 1 === $n; } /** * 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. 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. if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) { $ok = false; } 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 ): 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; } } /** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */ public static function reached_goals(): array { global $wpdb; 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 ): bool { $row = self::find( $id ); if ( ! $row ) { return false; // vanished row: nothing to apply, and never claim success } try { $donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row ); \StreamGoals\Rules\Engine::withGoalLock( $donation->goalId, static function () use ( $method, $donation ): void { \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; } } }