Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 c7f2dcffeb Make bonus rules visible: highlighted BONUS line on the alerts overlay, streamgoals_bonus action
Test and Release / test (push) Successful in 1m14s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:07:06 -08:00
shadowdaoandClaude Sonnet 5.5 1e2ca96eed README: updates need no token now that the repository is public
Test and Release / test (push) Successful in 1m35s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:59:53 -08:00
shadowdaoandClaude Sonnet 5.5 4cec93067c Add in-WordPress updater: checks Gitea releases, one-click and auto updates
Test and Release / test (push) Successful in 1m15s
Test and Release / release (push) Successful in 7s
- Update\ReleaseParser (pure, host-pinned, https only) and Update\Updater (WP hooks, cached, failure-safe)
- Settings: optional access token for a private repo, 'Check for updates now'

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:53:42 -08:00
shadowdaoandClaude Sonnet 5.5 27646c1001 Fix Rules screen crash: Store::rules() discarded decoded config (by-ref foreach over a cast copy)
Test and Release / test (push) Successful in 1m14s
Test and Release / release (push) Successful in 5s
Also make an unreadable rule non-fatal on the Rules screen, and add a regression test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:47:13 -08:00
shadowdaoandClaude Sonnet 5.5 3bbd77b661 Settings: show which address/proxy headers the server passes to the plugin
Test and Release / test (push) Successful in 1m17s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:43:18 -08:00
19 changed files with 728 additions and 7 deletions

No files matched your search

+7
View File
@@ -55,6 +55,13 @@ with the Live credentials and switch the mode to Live in Settings.
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
counters are not adjusted.
## Updates
New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen), checked against
this repository's releases. The repository is public, so no token is needed. (If you run a private fork, paste an
access token with read access to releases in StreamGoals > Settings > Advanced > Plugin updates.) You can switch
automatic updates on or off for this plugin on the Plugins screen, and use "Check for updates now" in
StreamGoals > Settings > Advanced to look straight away.
## Development
```
composer install
+6 -1
View File
@@ -27,7 +27,12 @@ body.sg-offline #sg-root{opacity:.6}
.sg-alert-head{font-weight:800;font-size:1.2em}
.sg-alert-head b{color:var(--sg-accent2)}
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
.sg-alert.sg-bonus{border-width:.14em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both,sg-glow 1.4s ease-in-out .6s infinite}
.sg-alert.sg-bonus.sg-out{animation:sg-out .5s ease-in both}
.sg-bonus-line{margin-top:.3em;display:inline-block;padding:.1em .6em;border-radius:999px;font-weight:900;font-size:.95em;letter-spacing:.06em;text-transform:uppercase;color:#fff;background:linear-gradient(90deg,var(--sg-accent),var(--sg-accent2));text-shadow:0 1px 3px rgba(0,0,0,.6);box-shadow:0 0 0 .08em rgba(0,0,0,.45)}
.sg-bonus-line+.sg-bonus-line{margin-left:.4em}
@keyframes sg-glow{0%,100%{box-shadow:0 0 .4em var(--sg-accent),0 0 .9em var(--sg-accent2)}50%{box-shadow:0 0 .9em var(--sg-accent),0 0 1.9em var(--sg-accent2)}}
@keyframes sg-in{from{opacity:0;transform:translateY(40%) scale(.9)}to{opacity:1;transform:none}}
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
@keyframes sg-blink{50%{opacity:.4}}
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out{animation:none}}
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
+7
View File
@@ -108,6 +108,13 @@
head.appendChild(document.createTextNode(' donated '));
head.appendChild(el('b', null, a.amount_display));
card.appendChild(head);
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
if (bonuses.length) {
card.classList.add('sg-bonus');
for (var j = 0; j < bonuses.length; j++) {
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
}
}
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
root.appendChild(card);
setTimeout(function () {
+7 -1
View File
@@ -197,7 +197,13 @@ final class GoalsPage {
foreach ( $rules as $r ) {
$rid = (int) $r['id'];
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
echo '<td>' . esc_html( RuleConfig::summary( (string) $r['type'], $r['config'], $cur ) ) . '</td><td class="sg-actions">';
try {
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
} catch ( \Throwable $e ) {
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
}
echo '<td>' . esc_html( $summary ) . '</td><td class="sg-actions">';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
+34 -1
View File
@@ -56,16 +56,45 @@ final class SettingsPage {
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
}
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p></td></tr></table></div>';
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
echo '</td></tr></table></div>';
$rel = \StreamGoals\Update\Updater::latest();
echo '<div class="sg-card"><h2>Plugin updates</h2><table class="form-table" role="presentation">';
echo '<tr><th scope="row">Installed version</th><td><code>' . esc_html( STREAMGOALS_VERSION ) . '</code></td></tr>';
echo '<tr><th scope="row">Latest release</th><td>' . ( $rel ? '<code>' . esc_html( $rel['version'] ) . '</code>' . ( \StreamGoals\Update\ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? ' (update available)' : ' (up to date)' ) : 'Not found yet (or the check failed).' ) . ' <button type="submit" form="sg_update_check_form" class="button">Check for updates now</button></td></tr>';
echo '<tr><th scope="row"><label for="sg_utoken">Access token (only needed while the update repository is private)</label></th><td><input type="password" id="sg_utoken" name="update_token" class="regular-text code" autocomplete="new-password" spellcheck="false" value="" placeholder="' . esc_attr( '' !== (string) $s['update_token'] ? Input::maskSecret( (string) $s['update_token'] ) : 'Paste a read-only token' ) . '">';
echo '<p class="description">' . ( '' !== (string) $s['update_token'] ? 'A token is saved. Leave this empty to keep it, or paste a new one to replace it.' : 'Not needed once the repository is public.' ) . '</p></td></tr></table></div>';
echo '<div class="sg-card"><h2>PayPal fee estimate</h2>';
echo '<p>When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (<strong>3.49% + $0.49</strong>) are <strong>US domestic estimates</strong>. Fees for international (cross-border) payments and currency conversion are higher and are <strong>not</strong> included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.</p>';
echo '<table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_pct">Percentage fee</label></th><td><input type="text" id="sg_pct" name="fee_percent" class="small-text" inputmode="decimal" value="' . esc_attr( number_format( (int) $s['fee_percent_bps'] / 100, 2, '.', '' ) ) . '"> %</td></tr>';
echo '<tr><th scope="row"><label for="sg_fix">Fixed fee (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_fix" name="fee_fixed" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( (int) $s['fee_fixed_minor'], $cur ) ) . '"></td></tr></table></div>';
echo '<p><button class="button button-primary button-hero">Save settings</button></p></form>';
echo '<form id="sg_update_check_form" method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '"><input type="hidden" name="action" value="' . esc_attr( \StreamGoals\Update\Updater::ACTION_CHECK ) . '">';
wp_nonce_field( \StreamGoals\Update\Updater::ACTION_CHECK );
echo '</form>';
Admin::close();
}
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
private static function ipDiagnostics( string $mode ): void {
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
$server = array();
foreach ( $keys as $k => $_ ) {
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
}
}
echo '<details class="sg-ipdiag"><summary>What does my server see right now?</summary><table class="widefat striped" style="max-width:36rem"><tbody>';
foreach ( $keys as $k => $label ) {
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
}
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
}
public static function handleSave(): void {
Admin::guard( 'sg_settings_save' );
$post = Admin::post_raw();
@@ -110,6 +139,10 @@ final class SettingsPage {
} else {
$upd['visitor_ip_header'] = $ipMode;
}
$tok = $post['update_token'] ?? '';
if ( ! Input::secretUnchanged( is_string( $tok ) ? $tok : '' ) ) {
$upd['update_token'] = Input::text( $tok, 300 );
}
$upd['funding_card'] = ! empty( $post['funding_card'] );
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
+5 -2
View File
@@ -26,11 +26,14 @@ final class Store {
public static function rules( int $goalId ): array {
global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A );
foreach ( (array) $rows as &$r ) {
$rows = (array) $rows;
// Iterate $rows itself by reference: `foreach ( (array) $rows as &$r )` would modify a temporary copy and discard the decoding.
foreach ( $rows as &$r ) {
$cfg = json_decode( (string) $r['config'], true );
$r['config'] = is_array( $cfg ) ? $cfg : array();
}
return (array) $rows;
unset( $r );
return $rows;
}
public static function rule( int $ruleId, int $goalId ): ?array {
+1
View File
@@ -14,6 +14,7 @@ final class Plugin {
\StreamGoals\Rest\WebhookController::class,
\StreamGoals\Rest\OverlayController::class,
\StreamGoals\Admin\Admin::class,
\StreamGoals\Update\Updater::class,
);
public static function boot(): void {
+1
View File
@@ -37,6 +37,7 @@ final class Settings {
'overlay_token' => '',
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
'funding_paylater' => false, // show PayPal "Pay Later" button
'update_token' => '', // optional Gitea read token (only while the update repo is private)
'funding_card' => true, // show the Debit/Credit Card button
);
}
+9
View File
@@ -28,4 +28,13 @@ interface OverlayDataSource {
* @return array<int,array<string,mixed>>
*/
public function donations( ?int $sinceId, int $limit ): array;
/**
* Bonus event names that fired (and were not reversed) per donation, in firing order. One lookup
* for the whole page. Raw stored strings; Payloads sanitizes them. Donations without bonuses may be omitted.
*
* @param int[] $donationIds
* @return array<int,string[]> donation id => event names
*/
public function bonusesFor( array $donationIds ): array;
}
+7 -1
View File
@@ -26,7 +26,13 @@ final class OverlayService {
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
return Payloads::counter( $c['label'], $c['value'] );
case 'alerts':
return Payloads::alerts( $this->source->donations( $since, 20 ), $since );
$rows = $this->source->donations( $since, 20 );
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
$bonuses = ( null !== $since && $ids ) ? $this->source->bonusesFor( $ids ) : array();
foreach ( $rows as $i => $r ) {
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
}
return Payloads::alerts( $rows, $since );
}
return null;
}
+30
View File
@@ -107,6 +107,7 @@ final class Payloads {
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
'currency' => $cur,
'message' => (string) ( $r['message'] ?? '' ),
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
);
}
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
@@ -116,6 +117,35 @@ final class Payloads {
return array( 'alerts' => $alerts, 'last_id' => $lastId );
}
/**
* Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped
* anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped.
*
* @param mixed $events
* @return string[]
*/
public static function bonuses( mixed $events ): array {
$out = array();
foreach ( is_array( $events ) ? $events : array() as $e ) {
if ( ! is_string( $e ) ) {
continue;
}
$clean = substr( (string) preg_replace( '/[^A-Za-z0-9_-]/', '', $e ), 0, 40 );
$label = trim( (string) preg_replace( '/[_-]+/', ' ', $clean ) );
if ( '' === $label ) {
continue;
}
$label = ucfirst( strtolower( $label ) );
if ( ! in_array( $label, $out, true ) ) {
$out[] = $label;
}
if ( count( $out ) >= 5 ) {
break;
}
}
return $out;
}
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
public static function etag( array $payload ): string {
unset( $payload['server_now'] );
+25
View File
@@ -62,6 +62,31 @@ final class WpdbDataSource implements OverlayDataSource {
return array( 'label' => $label, 'value' => $total );
}
public function bonusesFor( array $donationIds ): array {
global $wpdb;
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
if ( ! $ids ) {
return array();
}
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT e.donation_id, r.config FROM {$this->t('rule_events')} e
INNER JOIN {$this->t('rules')} r ON r.id = e.rule_id
WHERE r.type = 'bonus' AND e.reversed = 0 AND e.delta > 0 AND e.donation_id IN ($in)
ORDER BY e.id ASC",
$ids
), ARRAY_A );
$out = array();
foreach ( (array) $rows as $row ) {
$cfg = json_decode( (string) $row['config'], true );
$ev = is_array( $cfg ) && isset( $cfg['event'] ) && is_string( $cfg['event'] ) ? $cfg['event'] : '';
if ( '' !== $ev ) {
$out[ (int) $row['donation_id'] ][] = $ev;
}
}
return $out;
}
public function donations( ?int $sinceId, int $limit ): array {
global $wpdb;
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
+14 -1
View File
@@ -19,7 +19,20 @@ final class Engine {
/** Production wiring: $wpdb-backed stores. */
public static function default(): self {
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore() );
$onBonus = static function ( string $event, RuleDef $rule, Donation $d, bool $reversed ): void {
if ( function_exists( 'do_action' ) ) {
/**
* Fires when a big-donation bonus rule triggers (or is reversed by a refund).
*
* @param string $event Rule's event name.
* @param int $donationId Donation id.
* @param int $ruleId Rule id.
* @param bool $reversed True when the bonus was undone.
*/
do_action( 'streamgoals_bonus', $event, $d->id, $rule->id, $reversed );
}
};
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore(), null, $onBonus );
}
/**
+137
View File
@@ -0,0 +1,137 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Update;
/**
* Pure (WordPress-free) parsing of a Gitea release payload.
*/
final class ReleaseParser {
public const ASSET_NAME = 'streamgoals-donate.zip';
private const DATE_TAG = '/^\d{4}\.\d{2}\.\d{2}-\d{4}$/';
private const SEMVER = '/^\d+\.\d+\.\d+$/';
/**
* @param array $release Decoded Gitea release JSON.
* @param string $host The only host a package URL may point to (e.g. repo.anhonesthost.net).
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
*/
public static function parse( array $release, string $host ): ?array {
if ( ! empty( $release['draft'] ) || ! empty( $release['prerelease'] ) ) {
return null;
}
$version = self::normalizeVersion( $release['tag_name'] ?? null );
if ( null === $version ) {
return null;
}
$assets = isset( $release['assets'] ) && is_array( $release['assets'] ) ? $release['assets'] : array();
$package = self::pickPackage( $assets, $host );
if ( null === $package ) {
return null;
}
$url = $release['html_url'] ?? '';
return array(
'version' => $version,
'package' => $package,
'url' => is_string( $url ) && self::isAllowedUrl( $url, $host ) ? $url : '',
'notes' => is_string( $release['body'] ?? null ) ? $release['body'] : '',
'published' => is_string( $release['published_at'] ?? null ) ? $release['published_at'] : '',
);
}
public static function normalizeVersion( mixed $tag ): ?string {
if ( ! is_string( $tag ) ) {
return null;
}
$t = trim( $tag );
if ( '' !== $t && ( 'v' === $t[0] || 'V' === $t[0] ) ) {
$t = substr( $t, 1 );
}
return 1 === preg_match( self::DATE_TAG, $t ) || 1 === preg_match( self::SEMVER, $t ) ? $t : null;
}
public static function isNewer( string $remote, string $current ): bool {
$r = self::normalizeVersion( $remote );
if ( null === $r ) {
return false;
}
return version_compare( $r, ltrim( $current, 'vV' ), '>' );
}
/** https URL on exactly the configured host (no userinfo tricks). */
public static function isAllowedUrl( string $url, string $host ): bool {
$p = parse_url( $url );
if ( ! is_array( $p ) || ! isset( $p['scheme'], $p['host'] ) || isset( $p['user'] ) || isset( $p['pass'] ) ) {
return false;
}
return 'https' === strtolower( $p['scheme'] ) && '' !== $host && strtolower( $p['host'] ) === strtolower( $host );
}
private static function pickPackage( array $assets, string $host ): ?string {
$exact = null;
$first = null;
foreach ( $assets as $a ) {
if ( ! is_array( $a ) || ! is_string( $a['name'] ?? null ) || ! is_string( $a['browser_download_url'] ?? null ) ) {
continue;
}
if ( ! self::isAllowedUrl( $a['browser_download_url'], $host ) ) {
continue;
}
if ( self::ASSET_NAME === $a['name'] ) {
$exact = $exact ?? $a['browser_download_url'];
} elseif ( null === $first && str_ends_with( strtolower( $a['name'] ), '.zip' ) ) {
$first = $a['browser_download_url'];
}
}
return $exact ?? $first;
}
/** Minimal markdown to safe HTML: everything is escaped first; only paragraphs, headings (as <h4>) and lists. */
public static function changelogHtml( string $markdown ): string {
$lines = preg_split( '/\r\n|\r|\n/', $markdown ) ?: array();
$out = '';
$list = false;
$para = array();
$flush = static function () use ( &$out, &$para ): void {
if ( $para ) {
$out .= '<p>' . implode( ' ', $para ) . '</p>';
$para = array();
}
};
foreach ( $lines as $line ) {
$t = trim( $line );
if ( 1 === preg_match( '/^[*\-+]\s+(.*)$/', $t, $m ) ) {
$flush();
if ( ! $list ) {
$out .= '<ul>';
$list = true;
}
$out .= '<li>' . self::esc( $m[1] ) . '</li>';
continue;
}
if ( $list ) {
$out .= '</ul>';
$list = false;
}
if ( '' === $t ) {
$flush();
} elseif ( 1 === preg_match( '/^#{1,6}\s+(.*)$/', $t, $m ) ) {
$flush();
$out .= '<h4>' . self::esc( $m[1] ) . '</h4>';
} else {
$para[] = self::esc( $t );
}
}
$flush();
if ( $list ) {
$out .= '</ul>';
}
return $out;
}
private static function esc( string $s ): string {
return htmlspecialchars( $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
}
}
+201
View File
@@ -0,0 +1,201 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Update;
use StreamGoals\Admin\Admin;
use StreamGoals\Core\Settings;
/**
* Self-updater: checks the Gitea repo's latest release and feeds WordPress' plugin update machinery.
* Every network/parse failure degrades to "no update known"; nothing here throws into WP screens.
*/
final class Updater {
public const SLUG = 'streamgoals-donate';
public const BASE_URL = 'https://repo.anhonesthost.net';
public const OWNER = 'wp-plugins';
public const REPO = 'wp-donations';
public const CACHE_KEY = 'sg_update_release';
public const CACHE_OK = HOUR_IN_SECONDS;
public const CACHE_FAIL = 10 * MINUTE_IN_SECONDS;
public const TIMEOUT = 8;
public const ACTION_CHECK = 'sg_update_check';
public static function register(): void {
if ( ! self::enabled() ) {
return;
}
add_filter( 'pre_set_site_transient_update_plugins', array( self::class, 'inject' ) );
add_filter( 'plugins_api', array( self::class, 'pluginInfo' ), 10, 3 );
add_filter( 'http_request_args', array( self::class, 'authorize' ), 10, 2 );
add_action( 'upgrader_process_complete', array( self::class, 'afterUpgrade' ), 10, 2 );
add_action( 'admin_post_' . self::ACTION_CHECK, array( self::class, 'handleCheck' ) );
}
public static function enabled(): bool {
return (bool) apply_filters( 'streamgoals_updates_enabled', true );
}
/** @return array{base:string,owner:string,repo:string,host:string} */
public static function repo(): array {
$r = apply_filters( 'streamgoals_update_repo', array( 'base' => self::BASE_URL, 'owner' => self::OWNER, 'repo' => self::REPO ) );
$r = is_array( $r ) ? $r : array();
$base = rtrim( is_string( $r['base'] ?? null ) ? $r['base'] : self::BASE_URL, '/' );
$host = parse_url( $base, PHP_URL_HOST );
return array(
'base' => $base,
'owner' => is_string( $r['owner'] ?? null ) ? $r['owner'] : self::OWNER,
'repo' => is_string( $r['repo'] ?? null ) ? $r['repo'] : self::REPO,
'host' => is_string( $host ) ? strtolower( $host ) : '',
);
}
/**
* Cached latest release (parsed) or null. Failures are cached briefly so WP never re-hits a broken endpoint.
*
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
*/
public static function latest( bool $force = false ): ?array {
try {
if ( ! $force ) {
$c = get_site_transient( self::CACHE_KEY );
if ( is_array( $c ) && array_key_exists( 'release', $c ) ) {
return is_array( $c['release'] ) ? $c['release'] : null;
}
}
$release = self::fetch();
set_site_transient( self::CACHE_KEY, array( 'release' => $release ), null === $release ? self::CACHE_FAIL : self::CACHE_OK );
return $release;
} catch ( \Throwable $e ) {
return null;
}
}
public static function clearCache(): void {
delete_site_transient( self::CACHE_KEY );
}
private static function fetch(): ?array {
$repo = self::repo();
if ( '' === $repo['host'] || 'https' !== strtolower( (string) parse_url( $repo['base'], PHP_URL_SCHEME ) ) ) {
return null;
}
$url = $repo['base'] . '/api/v1/repos/' . rawurlencode( $repo['owner'] ) . '/' . rawurlencode( $repo['repo'] ) . '/releases/latest';
$resp = wp_remote_get( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 2, 'headers' => array( 'Accept' => 'application/json' ) ) );
if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
return null;
}
$data = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
return is_array( $data ) ? ReleaseParser::parse( $data, $repo['host'] ) : null;
}
public static function pluginFile(): string {
return plugin_basename( STREAMGOALS_FILE );
}
private static function entry( array $rel ): object {
$e = new \stdClass();
$e->id = $rel['url'] ?: self::BASE_URL;
$e->slug = self::SLUG;
$e->plugin = self::pluginFile();
$e->new_version = $rel['version'];
$e->url = $rel['url'];
$e->package = $rel['package'];
$e->requires = '6.8';
$e->requires_php = '8.1';
return $e;
}
public static function inject( mixed $transient ): mixed {
try {
if ( ! is_object( $transient ) ) {
return $transient;
}
$rel = self::latest();
$file = self::pluginFile();
unset( $transient->response[ $file ], $transient->no_update[ $file ] );
if ( null === $rel ) {
return $transient;
}
$entry = self::entry( $rel );
if ( ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ) {
$transient->response = is_array( $transient->response ?? null ) ? $transient->response : array();
$transient->response[ $file ] = $entry;
} else {
$entry->new_version = STREAMGOALS_VERSION;
$transient->no_update = is_array( $transient->no_update ?? null ) ? $transient->no_update : array();
$transient->no_update[ $file ] = $entry;
}
} catch ( \Throwable $e ) {
// Never break the Updates screen.
}
return $transient;
}
public static function pluginInfo( mixed $result, mixed $action = '', mixed $args = null ): mixed {
try {
if ( 'plugin_information' !== $action || ! is_object( $args ) || ( $args->slug ?? '' ) !== self::SLUG ) {
return $result;
}
$rel = self::latest();
if ( null === $rel ) {
return $result;
}
$i = new \stdClass();
$i->name = 'StreamGoals Donate';
$i->slug = self::SLUG;
$i->version = $rel['version'];
$i->author = 'StreamGoals';
$i->homepage = $rel['url'];
$i->requires = '6.8';
$i->requires_php = '8.1';
$i->last_updated = $rel['published'];
$i->download_link = $rel['package'];
$i->sections = array(
'description' => 'PayPal donations with multiple goals, fee coverage, and OBS stream overlays.',
'changelog' => '' !== $rel['notes'] ? ReleaseParser::changelogHtml( $rel['notes'] ) : '<p>No release notes.</p>',
);
return $i;
} catch ( \Throwable $e ) {
return $result;
}
}
/** Adds the token ONLY for https requests to the configured Gitea host. */
public static function authorize( mixed $args, mixed $url ): mixed {
try {
if ( ! is_array( $args ) || ! is_string( $url ) ) {
return $args;
}
$token = trim( (string) Settings::get( 'update_token', '' ) );
$host = self::repo()['host'];
if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) {
return $args;
}
$args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
$args['headers']['Authorization'] = 'token ' . $token;
} catch ( \Throwable $e ) {
// Fall through without credentials.
}
return $args;
}
public static function afterUpgrade( mixed $upgrader, mixed $options ): void {
if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) {
self::clearCache();
}
}
public static function handleCheck(): void {
Admin::guard( self::ACTION_CHECK );
self::clearCache();
delete_site_transient( 'update_plugins' );
$rel = self::latest( true );
$back = Admin::url( 'streamgoals-settings' );
if ( null === $rel ) {
Admin::redirect( $back, 'warning', 'Could not read the latest release. Check your connection and, if the update repository is private, the access token.' );
}
Admin::redirect( $back, 'success', ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? 'Version ' . $rel['version'] . ' is available. See Dashboard > Updates.' : 'You are up to date.' );
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\Store;
/**
* Regression: Store::rules() must return rules whose `config` is a decoded array, not the raw JSON string.
* (A by-reference foreach over a cast temporary once discarded the decoding and crashed the Rules screen.)
*/
final class AdminStoreRulesTest extends TestCase {
private $previous;
protected function setUp(): void {
if ( ! defined( 'ARRAY_A' ) ) {
define( 'ARRAY_A', 'ARRAY_A' ); // WordPress constant; not loaded in plain PHPUnit
}
$this->previous = $GLOBALS['wpdb'] ?? null;
$GLOBALS['wpdb'] = new class() {
public string $prefix = 'wp_';
public function prepare( string $q, ...$args ): string { return $q; }
public function get_results( string $q, $output = null ): array {
return array(
array( 'id' => '1', 'goal_id' => '1', 'type' => 'add_time', 'config' => '{"seconds_per_unit":60,"unit_minor":100,"max_timer_seconds":5400}', 'enabled' => '1', 'sort' => '0' ),
array( 'id' => '2', 'goal_id' => '1', 'type' => 'counter', 'config' => 'not json', 'enabled' => '0', 'sort' => '1' ),
array( 'id' => '3', 'goal_id' => '1', 'type' => 'bonus', 'config' => '{"min_minor":5000}', 'enabled' => '1', 'sort' => '2' ),
);
}
};
}
protected function tearDown(): void {
$GLOBALS['wpdb'] = $this->previous;
}
public function test_every_rule_config_is_a_decoded_array(): void {
$rules = Store::rules( 1 );
$this->assertCount( 3, $rules );
foreach ( $rules as $r ) {
$this->assertIsArray( $r['config'], 'rule ' . $r['id'] . ' config was not decoded' );
}
$this->assertSame( 5400, $rules[0]['config']['max_timer_seconds'] );
$this->assertSame( array(), $rules[1]['config'], 'invalid JSON becomes an empty config, not a crash' );
$this->assertSame( 5000, $rules[2]['config']['min_minor'] );
}
public function test_rule_lookup_returns_decoded_config(): void {
$r = Store::rule( 3, 1 );
$this->assertIsArray( $r['config'] );
$this->assertNull( Store::rule( 99, 1 ) );
}
}
@@ -39,6 +39,7 @@ final class EngineToOverlayIntegrationTest extends TestCase {
}
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => $this->s->getInt( $goalId, 'counter:2' ) ); }
public function donations( ?int $sinceId, int $limit ): array { return array(); }
public function bonusesFor( array $donationIds ): array { return array(); }
} );
$d = new Donation( 7, 1, 2500, 0, 2500, 'USD' ); // $25 -> +25 min, counter +2
@@ -53,4 +54,55 @@ final class EngineToOverlayIntegrationTest extends TestCase {
$engine->reverseDonation( $d );
$this->assertSame( 0, $svc->payload( 'counter', $now )['value'] );
}
private function bonusOverlay( FakeEventStore $events, array $donations ): OverlayService {
return new OverlayService( new class( $events, $donations ) implements OverlayDataSource {
public function __construct( private FakeEventStore $ev, private array $rows ) {}
public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'G', 'target_minor' => 5000, 'currency' => 'USD' ); }
public function raisedMinor( array $goal ): int { return 0; }
public function stateValue( int $goalId, string $key ): ?string { return null; }
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
public function donations( ?int $sinceId, int $limit ): array { return $this->rows; }
public function bonusesFor( array $donationIds ): array {
$out = array();
foreach ( $this->ev->events as $k => $e ) {
[ , $did ] = array_map( 'intval', explode( ':', $k ) );
if ( 1 === $e[0] && ! $e[1] && in_array( $did, $donationIds, true ) ) {
$out[ $did ][] = 'big_donation';
}
}
return $out;
}
} );
}
public function test_bonus_over_threshold_visible_in_alerts_below_is_not_and_refund_removes(): void {
$events = new FakeEventStore();
$fired = array();
$engine = new Engine(
new FakeRuleStore( array( new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 5000, 'event' => 'big_donation' ) ) ) ),
$events,
new FakeStateRepository(),
null,
function ( string $event, RuleDef $r, Donation $d, bool $rev ) use ( &$fired ): void {
$fired[] = array( $event, $d->id, $rev );
}
);
$big = new Donation( 10, 1, 5000, 0, 5000, 'USD' );
$small = new Donation( 11, 1, 4999, 0, 4999, 'USD' );
$engine->applyDonation( $big );
$engine->applyDonation( $small );
$this->assertSame( array( array( 'big_donation', 10, false ) ), $fired );
$row = static fn( int $id ): array => array( 'id' => $id, 'base_minor' => 5000, 'currency' => 'USD', 'donor_name' => 'A',
'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
$svc = $this->bonusOverlay( $events, array( $row( 10 ), $row( 11 ) ) );
$alerts = $svc->payload( 'alerts', 1, 0 )['alerts'];
$this->assertSame( array( 'Big donation' ), $alerts[0]['bonuses'] );
$this->assertSame( array(), $alerts[1]['bonuses'] );
$engine->reverseDonation( $big );
$this->assertSame( array(), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
$this->assertSame( true, $fired[1][2] );
}
}
+37
View File
@@ -96,6 +96,41 @@ final class OverlayPayloadsTest extends TestCase {
$this->assertSame( Payloads::etag( $g ), Payloads::etag( $g ) );
}
public function test_alert_bonuses_humanized_and_empty_when_none(): void {
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( 'big_donation', 'mega-win' ) ) ), $this->don( 2 ) ), 0 );
$this->assertSame( array( 'Big donation', 'Mega win' ), $out['alerts'][0]['bonuses'] );
$this->assertSame( array(), $out['alerts'][1]['bonuses'] );
}
public function test_alert_bonuses_sanitize_hostile_event(): void {
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( '<img src=x onerror=alert(1)>', '"><script>', '<>', 42, 'big_donation', 'BIG_DONATION' ) ) ) ), 0 );
$b = $out['alerts'][0]['bonuses'];
$this->assertSame( 'Imgsrcxonerroralert1', $b[0] );
foreach ( $b as $label ) {
$this->assertMatchesRegularExpression( '/^[A-Za-z0-9 ]+$/', $label );
}
$this->assertSame( 1, count( array_keys( $b, 'Big donation', true ) ) ); // deduped
}
public function test_bonuses_do_not_affect_masking_moderation_or_since(): void {
$rows = array(
$this->don( 1, array( 'bonuses' => array( 'big_donation' ) ) ),
$this->don( 2, array( 'is_anonymous' => 1, 'donor_name' => 'Secret Sam', 'bonuses' => array( 'big_donation' ) ) ),
$this->don( 3, array( 'moderation' => 'pending', 'bonuses' => array( 'big_donation' ) ) ),
);
$out = Payloads::alerts( $rows, 1 );
$this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) );
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
$this->assertStringNotContainsString( 'Secret Sam', json_encode( $out ) );
$this->assertSame( array(), Payloads::alerts( $rows, null )['alerts'] );
}
public function test_etag_changes_when_bonus_added(): void {
$plain = Payloads::alerts( array( $this->don( 5 ) ), 0 );
$bonus = Payloads::alerts( array( $this->don( 5, array( 'bonuses' => array( 'big_donation' ) ) ) ), 0 );
$this->assertNotSame( Payloads::etag( $plain ), Payloads::etag( $bonus ) );
}
public function test_style_sanitizes(): void {
$s = Style::fromQuery( array( 'theme' => 'bogus', 'accent' => '#FF00AA', 'color' => 'red;}</style>', 'bg' => '11223344',
'font' => 'x;}body{', 'scale' => '99' ) );
@@ -114,6 +149,7 @@ final class OverlayPayloadsTest extends TestCase {
public function raisedMinor( array $goal ): int { return 250; }
public function stateValue( int $goalId, string $key ): ?string { return 'timer_ends_at' === $key ? '2000' : null; }
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => 4 ); }
public function bonusesFor( array $donationIds ): array { return array( 3 => array( 'big_donation' ) ); }
public function donations( ?int $sinceId, int $limit ): array { return array( array( 'id' => 3, 'base_minor' => 100, 'currency' => 'USD', 'donor_name' => 'Z', 'is_anonymous' => 1, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ) ); }
};
$svc = new OverlayService( $src );
@@ -121,6 +157,7 @@ final class OverlayPayloadsTest extends TestCase {
$this->assertSame( 2000, $svc->payload( 'timer', 1500 )['ends_at'] );
$this->assertSame( 4, $svc->payload( 'counter', 1 )['value'] );
$this->assertSame( 'Anonymous', $svc->payload( 'alerts', 1, 0 )['alerts'][0]['name'] );
$this->assertSame( array( 'Big donation' ), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
$this->assertNull( $svc->payload( 'nope', 1 ) );
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Update\ReleaseParser;
final class UpdateReleaseParserTest extends TestCase {
private const HOST = 'repo.anhonesthost.net';
private const ZIP = 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/download/2026.11.15-1941/streamgoals-donate.zip';
private function release( array $over = array() ): array {
return array_merge(
array(
'tag_name' => '2026.11.15-1941',
'draft' => false,
'prerelease' => false,
'body' => "## What's New\n\n* one\n* two",
'html_url' => 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/tag/2026.11.15-1941',
'published_at' => '2026-11-15T19:41:00Z',
'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) ),
),
$over
);
}
public function test_valid_release(): void {
$r = ReleaseParser::parse( $this->release(), self::HOST );
$this->assertSame( '2026.11.15-1941', $r['version'] );
$this->assertSame( self::ZIP, $r['package'] );
$this->assertSame( '2026-11-15T19:41:00Z', $r['published'] );
$this->assertStringContainsString( 'releases/tag', $r['url'] );
}
public function test_draft_and_prerelease_ignored(): void {
$this->assertNull( ReleaseParser::parse( $this->release( array( 'draft' => true ) ), self::HOST ) );
$this->assertNull( ReleaseParser::parse( $this->release( array( 'prerelease' => true ) ), self::HOST ) );
}
public function test_bad_tag(): void {
foreach ( array( 'nightly', '2026.1.15-1941', '', null, array() ) as $t ) {
$this->assertNull( ReleaseParser::parse( $this->release( array( 'tag_name' => $t ) ), self::HOST ) );
}
}
public function test_v_prefix_and_semver(): void {
$this->assertSame( '2026.11.15-1941', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v2026.11.15-1941' ) ), self::HOST )['version'] );
$this->assertSame( '1.2.3', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v1.2.3' ) ), self::HOST )['version'] );
}
public function test_wrong_host_and_non_https_rejected(): void {
foreach ( array( 'https://evil.example/streamgoals-donate.zip', 'http://repo.anhonesthost.net/x.zip', 'https://repo.anhonesthost.net@evil.example/x.zip', 'https://repo.anhonesthost.net.evil.example/x.zip', '//repo.anhonesthost.net/x.zip' ) as $u ) {
$rel = $this->release( array( 'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => $u ) ) ) );
$this->assertNull( ReleaseParser::parse( $rel, self::HOST ), $u );
}
}
public function test_missing_asset(): void {
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array() ) ), self::HOST ) );
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array( array( 'name' => 'notes.txt', 'browser_download_url' => self::ZIP ) ) ) ), self::HOST ) );
$this->assertNull( ReleaseParser::parse( array( 'tag_name' => '1.0.0' ), self::HOST ) );
}
public function test_picks_right_asset(): void {
$other = 'https://repo.anhonesthost.net/dl/other.zip';
$a = array( array( 'name' => 'source.zip', 'browser_download_url' => $other ), array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) );
$this->assertSame( self::ZIP, ReleaseParser::parse( $this->release( array( 'assets' => $a ) ), self::HOST )['package'] );
$this->assertSame( $other, ReleaseParser::parse( $this->release( array( 'assets' => array( $a[0] ) ) ), self::HOST )['package'] );
}
public function test_version_comparison(): void {
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1830', '2026.11.15-0930' ) );
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-1830' ) );
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-0930' ) );
$this->assertTrue( ReleaseParser::isNewer( 'v2026.11.16-0001', '2026.11.15-2359' ) );
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1941', '0.1.0' ) );
$this->assertFalse( ReleaseParser::isNewer( 'garbage', '0.1.0' ) );
}
public function test_changelog_escapes_html(): void {
$h = ReleaseParser::changelogHtml( "<script>alert(1)</script>\n\n* <b>bold</b> & \"q\"\n* two" );
$this->assertStringNotContainsString( '<script', $h );
$this->assertStringNotContainsString( '<b>', $h );
$this->assertStringContainsString( '&lt;script&gt;', $h );
$this->assertStringContainsString( '<ul><li>&lt;b&gt;bold&lt;/b&gt; &amp; &quot;q&quot;</li><li>two</li></ul>', $h );
}
public function test_changelog_paragraphs_and_headings(): void {
$this->assertSame( '<h4>What&#039;s New</h4><p>a b</p><ul><li>x</li></ul>', ReleaseParser::changelogHtml( "## What's New\n\na\nb\n\n- x" ) );
}
}