Compare commits

...
Author SHA1 Message Date
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
shadowdaoandClaude Sonnet 5.5 e4d9042aba Add visitor-IP header setting, checkout-button toggles, and configurable timer maximum
Test and Release / test (push) Successful in 1m13s
Test and Release / release (push) Successful in 5s
- Core\ClientIp: trusted-header resolution for rate limiting behind Cloudflare/proxies
- Settings: show/hide Pay Later and Debit/Credit Card (Pay Later off by default)
- add_time rule: optional max_timer_seconds (uncapped by default), editable in rule form

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:40:06 -08:00
shadowdaoandClaude Sonnet 5.5 4f92cfdade Show donate form messages above the PayPal buttons
Test and Release / test (push) Successful in 2m48s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 10:51:44 -08:00
16 changed files with 365 additions and 20 deletions

No files matched your search

+5 -2
View File
@@ -42,7 +42,8 @@
if ( ! c.unit_minor ) { return null; }
var d = Math.floor( amount * c.seconds_per_unit / c.unit_minor );
if ( c.cap_seconds_per_donation != null ) { d = Math.min( d, c.cap_seconds_per_donation ); }
return d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added';
var note = c.max_timer_seconds != null ? ' (the timer never goes above ' + duration( c.max_timer_seconds ) + ')' : '';
return ( d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added' ) + note;
}
if ( rule.type === 'counter' ) {
if ( ! c.per_minor ) { return null; }
@@ -74,6 +75,7 @@
/* Type switch + preview of the rule being edited. */
if ( ! form ) { return; }
var typeSel = document.getElementById( 'sg-rule-type' );
var typeHidden = form.querySelector( 'input[name="type"]' );
var formPrev = document.getElementById( 'sg-form-preview' );
@@ -93,7 +95,8 @@
var n = parseInt( val( g, 'time_amount' ), 10 );
if ( ! unit || ! n ) { return null; }
var cap = parseInt( val( g, 'cap_minutes' ), 10 );
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null } };
var clock = parseInt( val( g, 'max_timer_minutes' ), 10 );
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null, max_timer_seconds: clock > 0 ? clock * 60 : null } };
}
if ( type === 'counter' ) {
var step = parseInt( val( g, 'step' ), 10 );
+3 -2
View File
@@ -41,7 +41,8 @@
var s = document.createElement('script');
s.id = 'sg-paypal-sdk';
s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) +
'&currency=' + encodeURIComponent(currency) + '&intent=capture&components=buttons';
'&currency=' + encodeURIComponent(currency) + '&intent=capture&components=buttons' +
((C.disableFunding && C.disableFunding.length) ? '&disable-funding=' + encodeURIComponent(C.disableFunding.join(',')) : '');
s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); };
s.onerror = function () { reject(new Error(T.sdkError)); };
document.head.appendChild(s);
@@ -106,8 +107,8 @@
tip
]));
root.appendChild(row([total]));
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
root.appendChild(buttons);
root.appendChild(status);
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
function amountStr() { return amount.value.trim().replace(',', '.'); }
+2 -2
View File
@@ -37,9 +37,9 @@ Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is r
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
```
Rule `config` examples:
Rule `config` examples (`max_total_seconds` caps what one rule has added over time; `max_timer_seconds` caps how long the timer can ever get, null = uncapped):
```json
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"basis":"base"}
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"max_timer_seconds":null,"basis":"base"}
{"type":"counter","step":1,"per_minor":1000,"carry_over":true,"basis":"base","label":"Pies"}
{"type":"bonus","min_minor":5000,"event":"big_donation"}
```
+9 -2
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> ';
@@ -249,9 +255,10 @@ final class GoalsPage {
echo '<option value="' . esc_attr( $u ) . '"' . selected( 'add_time' === $type ? ( $vals['time_unit'] ?? 'minutes' ) : 'minutes', $u, false ) . '>' . esc_html( $u ) . '</option>';
}
echo '</select> to the timer for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" name="rule[add_time][unit_amount]" class="small-text" data-f="unit_amount" value="' . $v( 'add_time', 'unit_amount', 0 === Money::exponent( $cur ) ? '100' : '1.00' ) . '"> donated.</p>';
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' || ( $vals['max_timer_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
echo '<p><label>Most minutes one donation can add <input type="number" min="1" class="small-text" name="rule[add_time][cap_minutes]" data-f="cap_minutes" value="' . $v( 'add_time', 'cap_minutes' ) . '"></label></p>';
echo '<p><label>Most minutes this rule can add in total <input type="number" min="1" class="small-text" name="rule[add_time][max_total_minutes]" data-f="max_total_minutes" value="' . $v( 'add_time', 'max_total_minutes' ) . '"></label></p>';
echo '<p><label>Longest the timer can ever get (minutes) <input type="number" min="1" class="small-text" name="rule[add_time][max_timer_minutes]" data-f="max_timer_minutes" value="' . $v( 'add_time', 'max_timer_minutes' ) . '"></label> <span class="description">Leave empty for no limit. For example, 1440 means the clock never shows more than 24 hours.</span></p>';
echo '<p><label>Count ' . $basisOpts( 'add_time' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped parts
// counter
echo '<div class="sg-rule-group" data-type="counter"' . ( 'counter' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" class="small-text" name="rule[counter][step]" data-f="step" value="' . $v( 'counter', 'step', '1' ) . '"> to the counter for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[counter][unit_amount]" data-f="unit_amount" value="' . $v( 'counter', 'unit_amount', 0 === Money::exponent( $cur ) ? '1000' : '10.00' ) . '"> donated.</p>';
+9
View File
@@ -46,6 +46,7 @@ final class RuleConfig {
}
$cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors );
$max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors );
$clk = self::optionalMinutes( $in['max_timer_minutes'] ?? '', 'The longest the timer can get', $errors );
if ( $errors ) {
return array( 'config' => null, 'errors' => $errors );
}
@@ -59,6 +60,7 @@ final class RuleConfig {
'unit_minor' => $unit,
'cap_seconds_per_donation' => $cap,
'max_total_seconds' => $max,
'max_timer_seconds' => $clk,
'basis' => $basis,
),
'errors' => array(),
@@ -128,6 +130,9 @@ final class RuleConfig {
if ( isset( $c['max_total_seconds'] ) ) {
$s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total';
}
if ( isset( $c['max_timer_seconds'] ) ) {
$s .= ', up to ' . Format::duration( (int) $c['max_timer_seconds'] ) . ' on the clock';
}
return $s;
case 'counter':
$label = (string) ( $c['label'] ?? '' );
@@ -158,6 +163,9 @@ final class RuleConfig {
if ( 'add_time' === $type ) {
$res = AddTimeRule::fromConfig( $cfg )->apply( $d, 0, 0, 0 );
$lines[] = $res['delta'] > 0 ? 'Timer: +' . Format::duration( $res['delta'] ) : 'Timer: no time added';
if ( isset( $cfg['max_timer_seconds'] ) ) {
$lines[ count( $lines ) - 1 ] .= ' (the timer never goes above ' . Format::duration( (int) $cfg['max_timer_seconds'] ) . ')';
}
} elseif ( 'counter' === $type ) {
$res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 );
$lbl = (string) ( $cfg['label'] ?? '' );
@@ -182,6 +190,7 @@ final class RuleConfig {
$f['unit_amount'] = Format::decimal( (int) ( $c['unit_minor'] ?? 100 ), $currency );
$f['cap_minutes'] = isset( $c['cap_seconds_per_donation'] ) ? (string) intdiv( (int) $c['cap_seconds_per_donation'], 60 ) : '';
$f['max_total_minutes'] = isset( $c['max_total_seconds'] ) ? (string) intdiv( (int) $c['max_total_seconds'], 60 ) : '';
$f['max_timer_minutes'] = isset( $c['max_timer_seconds'] ) ? (string) intdiv( (int) $c['max_timer_seconds'], 60 ) : '';
} elseif ( 'counter' === $type ) {
$f['step'] = (int) ( $c['step'] ?? 1 );
$f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency );
+38
View File
@@ -47,6 +47,19 @@ final class SettingsPage {
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>';
echo '<div class="sg-card"><h2>Checkout buttons</h2><table class="form-table" role="presentation"><tr><th scope="row">Payment options</th><td>';
echo '<label><input type="checkbox" name="funding_card" value="1"' . checked( ! empty( $s['funding_card'] ), true, false ) . '> Show "Debit or Credit Card" (donors without a PayPal account)</label><br>';
echo '<label><input type="checkbox" name="funding_paylater" value="1"' . checked( ! empty( $s['funding_paylater'] ), true, false ) . '> Show "Pay Later" (donors pay in instalments; you are still paid in full)</label>';
echo '<p class="description">The PayPal button is always shown. Which extra buttons appear can also depend on the donor\'s country.</p></td></tr></table></div>';
echo '<div class="sg-card"><h2>Advanced</h2><table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_ip">Visitor IP address</label></th><td><select id="sg_ip" name="visitor_ip_header">';
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>';
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
echo '</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>';
@@ -55,6 +68,23 @@ final class SettingsPage {
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();
@@ -93,6 +123,14 @@ final class SettingsPage {
} else {
$upd['anonymity_policy'] = $pol;
}
$ipMode = isset( $post['visitor_ip_header'] ) && is_string( $post['visitor_ip_header'] ) ? $post['visitor_ip_header'] : '';
if ( ! array_key_exists( $ipMode, \StreamGoals\Core\ClientIp::MODES ) ) {
$errors[] = 'Please choose a visitor IP option.';
} else {
$upd['visitor_ip_header'] = $ipMode;
}
$upd['funding_card'] = ! empty( $post['funding_card'] );
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
+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 -1
View File
@@ -28,7 +28,7 @@ final class Templates {
$rules = array();
if ( 'subathon' === $key ) {
$rules[] = array( 'type' => 'add_time', 'config' => array(
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'basis' => 'base',
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base',
) );
} elseif ( 'counter' === $key ) {
$rules[] = array( 'type' => 'counter', 'config' => array(
+56
View File
@@ -0,0 +1,56 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Works out the visitor's IP for rate limiting. Pure (takes the $_SERVER values as an array) so it is unit-testable.
*
* Behind a CDN or reverse proxy, PHP's REMOTE_ADDR is the proxy's address, so every visitor would share one rate
* limit. The owner can name the header their proxy sets. A header is ONLY trusted when the owner selected it, and
* only if it holds a valid IP address; otherwise we fall back to REMOTE_ADDR.
*/
final class ClientIp {
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
public const MODES = array(
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
self::MODE_REAL_IP => 'X-Real-IP header',
self::MODE_FORWARDED => 'X-Forwarded-For header (one proxy in front)',
);
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
$fromHeader = null;
switch ( $mode ) {
case self::MODE_CLOUDFLARE:
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
break;
case self::MODE_REAL_IP:
$fromHeader = self::valid( $server['HTTP_X_REAL_IP'] ?? null );
break;
case self::MODE_FORWARDED:
$raw = $server['HTTP_X_FORWARDED_FOR'] ?? null;
if ( is_string( $raw ) && '' !== trim( $raw ) ) {
$parts = array_map( 'trim', explode( ',', $raw ) );
$fromHeader = self::valid( end( $parts ) ); // the entry our proxy appended; earlier ones are client-supplied
}
break;
}
return $fromHeader ?? $remote ?? 'unknown';
}
private static function valid( mixed $v ): ?string {
if ( ! is_string( $v ) ) {
return null;
}
$v = trim( $v );
return false !== filter_var( $v, FILTER_VALIDATE_IP ) ? $v : null;
}
}
+3
View File
@@ -35,6 +35,9 @@ final class Settings {
'message_max_length' => 200,
'min_donation_minor' => 100,
'overlay_token' => '',
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
'funding_paylater' => false, // show PayPal "Pay Later" button
'funding_card' => true, // show the Debit/Credit Card button
);
}
+8 -1
View File
@@ -179,6 +179,7 @@ final class DonateController {
'policy' => (string) $s['anonymity_policy'],
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
'messageMax' => min( 500, (int) $s['message_max_length'] ),
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
'goals' => $goals,
'i18n' => array(
'goal' => __( 'Goal', 'streamgoals-donate' ),
@@ -231,7 +232,13 @@ final class DonateController {
}
private static function limit( string $bucket, int $max, int $window ): ?\WP_Error {
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
$server = array();
foreach ( array( 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR' ) as $k ) {
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
}
}
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
+13 -6
View File
@@ -6,7 +6,8 @@ namespace StreamGoals\Rules;
/**
* Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor).
* cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds
* this rule may ever add (net of reversals). The timer is an absolute ends_at timestamp.
* this rule may ever add (net of reversals). maxTimer caps the remaining time on the clock (ends_at - now);
* null = uncapped. A timer already above the cap is never shortened, it just gets 0 added. The timer is an absolute ends_at timestamp.
*/
final class AddTimeRule {
@@ -15,9 +16,10 @@ final class AddTimeRule {
public readonly int $unitMinor,
public readonly ?int $capPerDonation = null,
public readonly ?int $maxTotal = null,
public readonly string $basis = 'base'
public readonly string $basis = 'base',
public readonly ?int $maxTimer = null
) {
if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) {
if ( $unitMinor <= 0 || $secondsPerUnit < 0 || ( null !== $maxTimer && $maxTimer < 1 ) ) {
throw new \InvalidArgumentException( 'Invalid add_time config.' );
}
}
@@ -28,7 +30,8 @@ final class AddTimeRule {
(int) ( $c['unit_minor'] ?? 0 ),
isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null,
isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null,
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base',
isset( $c['max_timer_seconds'] ) ? (int) $c['max_timer_seconds'] : null
);
}
@@ -41,14 +44,18 @@ final class AddTimeRule {
if ( null !== $this->maxTotal ) {
$delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) );
}
// Expired (or never started) timers restart from now.
$start = max( $endsAt, $now );
if ( null !== $this->maxTimer ) {
$delta = min( $delta, max( 0, $this->maxTimer - ( $start - $now ) ) );
}
$delta = max( 0, $delta );
if ( 0 === $delta ) {
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
}
// Expired (or never started) timers restart from now.
return array(
'delta' => $delta,
'ends_at' => max( $endsAt, $now ) + $delta,
'ends_at' => $start + $delta,
'added_total' => $addedTotal + $delta,
);
}
+17 -2
View File
@@ -52,7 +52,7 @@ final class AdminLogicTest extends TestCase {
$r = RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00', 'cap_minutes' => '10', 'max_total_minutes' => '' ), 'USD' );
$this->assertSame( array(), $r['errors'] );
$this->assertSame(
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' ),
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base' ),
$r['config']
);
}
@@ -92,8 +92,23 @@ final class AdminLogicTest extends TestCase {
$this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) );
}
public function test_max_timer_validation_and_summary(): void {
$base = array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00' );
$this->assertNull( RuleConfig::sanitize( 'add_time', $base, 'USD' )['config']['max_timer_seconds'] );
$this->assertNull( RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => ' ' ), 'USD' )['config']['max_timer_seconds'] );
$this->assertSame( 86400, RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => '1440' ), 'USD' )['config']['max_timer_seconds'] );
foreach ( array( '0', '-5', 'abc', '1.5' ) as $bad ) {
$r = RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => $bad ), 'USD' );
$this->assertNotEmpty( $r['errors'], $bad );
$this->assertNull( $r['config'] );
}
$this->assertSame( 'Adds 1 minute for every $1.00, up to 1 day on the clock', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 86400 ), 'USD' ) );
$this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) );
$this->assertSame( array( 'Timer: +25 minutes (the timer never goes above 1 hour)' ), RuleConfig::preview( array( array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 3600 ) ) ), 2500, 'USD' ) );
}
public function test_form_roundtrip(): void {
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' );
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => 86400, 'basis' => 'base' );
$form = RuleConfig::toForm( 'add_time', $cfg, 'USD' );
$back = RuleConfig::sanitize( 'add_time', $form, 'USD' );
$this->assertSame( $cfg, $back['config'] );
+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 ) );
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\ClientIp;
final class ClientIpTest extends TestCase {
private const PROXY = '172.70.1.1';
private const CLIENT = '203.0.113.9';
public function test_direct_mode_uses_remote_addr_and_ignores_headers(): void {
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '5.6.7.8' );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_DIRECT ) );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv ) );
}
public function test_cloudflare_mode_uses_cf_header(): void {
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ) );
}
public function test_cloudflare_mode_without_header_falls_back_to_remote_addr(): void {
$this->assertSame( self::PROXY, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY ), ClientIp::MODE_CLOUDFLARE ) );
}
public function test_invalid_header_values_are_ignored(): void {
foreach ( array( 'not-an-ip', '999.1.1.1', '', '1.2.3.4, 5.6.7.8', '<script>', "1.2.3.4\r\nX: y" ) as $bad ) {
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => $bad );
$this->assertSame( self::PROXY, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ), "accepted bad value: $bad" );
}
}
public function test_x_real_ip_mode(): void {
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_REAL_IP' => self::CLIENT ), ClientIp::MODE_REAL_IP ) );
}
public function test_forwarded_mode_takes_the_last_entry_not_the_spoofable_first(): void {
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => '6.6.6.6, ' . self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_FORWARDED ) );
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => self::CLIENT ), ClientIp::MODE_FORWARDED ) );
}
public function test_ipv6_is_accepted(): void {
$this->assertSame( '2001:db8::1', ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => '2001:db8::1' ), ClientIp::MODE_CLOUDFLARE ) );
}
public function test_unknown_when_nothing_valid(): void {
$this->assertSame( 'unknown', ClientIp::resolve( array(), ClientIp::MODE_CLOUDFLARE ) );
$this->assertSame( 'unknown', ClientIp::resolve( array( 'REMOTE_ADDR' => 'garbage' ) ) );
}
public function test_unrecognised_mode_behaves_like_direct(): void {
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
}
}
+82
View File
@@ -81,6 +81,88 @@ final class RulesEngineTest extends TestCase {
$this->assertSame( 1000 + 100, $this->state->getInt( 1, 'timer_ends_at' ) );
}
private function ends(): int {
return $this->state->getInt( 1, 'timer_ends_at' );
}
public function test_max_timer_clamps_and_records_actual_delta(): void {
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) ); // now=1000
$this->state->setInt( 1, 'timer_ends_at', 2000 ); // 1000s remaining
$e->applyDonation( $this->d( 1, 1000 ) ); // wants +600, room 200
$this->assertSame( 2200, $this->ends() );
$this->assertSame( 200, $this->events->events['1:1'][0] );
$this->assertSame( 200, $this->state->getInt( 1, 'timer_added:1' ) );
}
public function test_max_timer_exactly_at_cap_adds_zero(): void {
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1000 ) ) ) );
$this->state->setInt( 1, 'timer_ends_at', 2000 );
$e->applyDonation( $this->d( 1, 100 ) );
$this->assertSame( 2000, $this->ends() );
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
}
public function test_max_timer_lowered_below_existing_timer_does_not_shorten(): void {
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
$this->state->setInt( 1, 'timer_ends_at', 9000 );
$e->applyDonation( $this->d( 1, 100 ) );
$this->assertSame( 9000, $this->ends() );
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
}
public function test_uncapped_by_default_and_null(): void {
foreach ( array( array(), array( 'max_timer_seconds' => null ) ) as $extra ) {
$e = $this->engine( array( $this->timer( $extra ) ) );
$this->state->setInt( 1, 'timer_ends_at', 10000000 );
$e->applyDonation( $this->d( 1, 100000 ) );
$this->assertSame( 10000000 + 60000, $this->ends() );
}
}
public function test_max_timer_with_other_caps_most_restrictive_wins(): void {
// per-donation 50 is the tightest
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'cap_seconds_per_donation' => 50, 'max_total_seconds' => 400 ) ) ) );
$e->applyDonation( $this->d( 1, 1000 ) );
$this->assertSame( 1050, $this->ends() );
// max_total tightest: 30 left of 40 total, clock has room
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'max_total_seconds' => 40 ) ) ) );
$this->state->setInt( 1, 'timer_added:1', 10 );
$e->applyDonation( $this->d( 1, 1000 ) );
$this->assertSame( 1030, $this->ends() );
$this->assertSame( 40, $this->state->getInt( 1, 'timer_added:1' ) );
// clock cap tightest: only 20 of room
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 120, 'cap_seconds_per_donation' => 300, 'max_total_seconds' => 900 ) ) ) );
$this->state->setInt( 1, 'timer_ends_at', 1100 );
$e->applyDonation( $this->d( 1, 1000 ) );
$this->assertSame( 1120, $this->ends() );
$this->assertSame( 20, $this->state->getInt( 1, 'timer_added:1' ) );
}
public function test_max_timer_with_expired_timer_starts_from_now(): void {
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
$this->state->setInt( 1, 'timer_ends_at', 10 );
$e->applyDonation( $this->d( 1, 1000 ) ); // wants 600
$this->assertSame( 1100, $this->ends() );
}
public function test_max_timer_replay_idempotent_and_reversal_uses_clamped_delta(): void {
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) );
$this->state->setInt( 1, 'timer_ends_at', 2000 );
$d = $this->d( 1, 1000 );
$e->applyDonation( $d );
$e->applyDonation( $d );
$this->assertSame( 2200, $this->ends() );
$e->reverseDonation( $d );
$e->reverseDonation( $d );
$this->assertSame( 2000, $this->ends() );
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
}
public function test_max_timer_invalid_value_rejected_by_rule(): void {
$this->expectException( \InvalidArgumentException::class );
\StreamGoals\Rules\AddTimeRule::fromConfig( array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 0 ) );
}
public function test_reversal_undoes_and_is_not_double_applied(): void {
$e = $this->engine( array( $this->timer(), $this->counter() ) );
$d = $this->d( 10, 2500 );