Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 43106d9edc Automatic Cloudflare detection for rate limiting (trusts CF-Connecting-IP only from Cloudflare ranges)
Test and Release / test (push) Successful in 1m19s
Test and Release / release (push) Failing after 5s
- Core\CidrMatcher (IPv4/IPv6), Core\CloudflareRanges (published ranges, filterable)
- ClientIp 'auto' mode, default for new installs; diagnostics show whether the connection is from Cloudflare

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:54:10 -08:00
shadowdaoandClaude Sonnet 5.5 5ea1e1d273 End-at-target goals (auto-close when target reached) and fit-to-window rewards menu overlay
Test and Release / test (push) Successful in 1m14s
Test and Release / release (push) Successful in 4s
- Core\GoalTargetPolicy; atomic close in the capture path; friendly 'goal reached' message
- In-flight checkouts still capture; new orders for a closed goal are refused
- Rewards menu overlay: card hugs content, text scales to the window, resize-aware, scroll only as a last resort

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:53:07 -08:00
shadowdaoandClaude Sonnet 5.5 1c6d93ad5f Test: schema version assertion is a minimum, not an exact value
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:50:35 -08:00
shadowdaoandClaude Sonnet 5.5 da1365f060 Schema v3: goals.close_at_target and alert_defs table (contract in docs)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:50:26 -08:00
shadowdaoandClaude Sonnet 5.5 f8d6bc2195 README: document rewards
Test and Release / test (push) Successful in 1m16s
Test and Release / release (push) Successful in 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:45:45 -08:00
20 changed files with 425 additions and 27 deletions

No files matched your search

+6
View File
@@ -45,6 +45,12 @@ with the Live credentials and switch the mode to Live in Settings.
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
- **Overlays:** StreamGoals → Overlays. Copy a widget URL into OBS as a **Browser Source** (suggested 800×200
for the goal bar; transparent background is built in). Keep the URL private; "Regenerate token" invalidates it.
- **Rewards (actions for set amounts):** StreamGoals > Rewards. Add things you do on stream for a set amount, for example
"$5: eat an every-flavor bean" or "$25: 25 pushups". Each reward is either *exactly this amount* or *every time the
donation adds up to this amount* (a $10 donation triggers a $5 reward twice). Rewards appear as buttons on the donation
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
optional fee cover, and must be at least your minimum donation.
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
## Privacy and moderation
+2 -2
View File
@@ -38,8 +38,8 @@ body.sg-offline #sg-root{opacity:.6}
@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)}}
.sg-w-actions #sg-root{align-items:flex-start}
.sg-w-actions #sg-root:empty{display:none}
.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden}
.sg-menu-view{flex:1;min-height:0;overflow:hidden}
.sg-menu{height:auto;display:flex;flex-direction:column;overflow:hidden;font-size:calc(1em * var(--sg-menu-scale,1))}
.sg-menu-view{flex:none;min-height:0;overflow:hidden}
.sg-menu-list{list-style:none;margin:0;padding:0}
.sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere}
.sg-menu-item b{color:var(--sg-accent2);font-weight:800}
+40 -12
View File
@@ -146,14 +146,50 @@
}
// ---- actions (reward menu) ----
// Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration).
var actionsSig = null;
// Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the
// LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and
// re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll.
var actionsSig = null, menuEls = null, fitTimer = 0;
var MENU_MIN = 0.5, MENU_MAX = 1.8;
function fitMenu() {
if (!menuEls) return;
var card = menuEls.card, view = menuEls.view, track = menuEls.track, ul = menuEls.ul;
// reset any previous scroll fallback
track.classList.remove('sg-scrolling');
while (track.children.length > 1) track.removeChild(track.lastChild);
view.style.height = '';
var cs = getComputedStyle(root);
var inner = root.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
if (inner <= 0) return;
function fits(scale) {
card.style.setProperty('--sg-menu-scale', String(scale));
return card.offsetHeight <= inner;
}
var lo = MENU_MIN, hi = MENU_MAX, best = null;
if (fits(hi)) { best = hi; }
else if (!fits(lo)) { best = null; }
else { for (var i = 0; i < 9; i++) { var mid = (lo + hi) / 2; if (fits(mid)) { lo = mid; } else { hi = mid; } } best = lo; }
if (best !== null) { card.style.setProperty('--sg-menu-scale', String(best)); return; }
// Even the smallest size overflows: use the smallest and scroll gently inside the window.
card.style.setProperty('--sg-menu-scale', String(MENU_MIN));
var chrome = card.offsetHeight - view.offsetHeight;
view.style.height = Math.max(40, inner - chrome) + 'px';
var dup = ul.cloneNode(true);
dup.setAttribute('aria-hidden', 'true');
track.appendChild(dup);
track.style.setProperty('--sg-scroll-s', Math.max(8, menuEls.count * 3) + 's');
track.classList.add('sg-scrolling');
}
function scheduleFit() { clearTimeout(fitTimer); fitTimer = setTimeout(fitMenu, 120); }
window.addEventListener('resize', scheduleFit);
if (typeof ResizeObserver === 'function') { try { new ResizeObserver(scheduleFit).observe(document.documentElement); } catch (e) { /* resize event is the fallback */ } }
function renderActions(d) {
var list = Array.isArray(d.actions) ? d.actions : [];
var sig = JSON.stringify(list);
if (sig === actionsSig) return;
actionsSig = sig;
root.textContent = '';
menuEls = null;
if (!d.active || !list.length) return;
var card = el('div', 'sg-card sg-menu');
var view = el('div', 'sg-menu-view');
@@ -171,16 +207,8 @@
view.appendChild(track);
card.appendChild(view);
root.appendChild(card);
// Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll.
requestAnimationFrame(function () {
if (ul.scrollHeight > view.clientHeight + 2) {
var dup = ul.cloneNode(true);
dup.setAttribute('aria-hidden', 'true');
track.appendChild(dup);
track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's');
track.classList.add('sg-scrolling');
}
});
menuEls = { card: card, view: view, track: track, ul: ul, count: list.length };
requestAnimationFrame(fitMenu);
}
// ---- polling ----
+8
View File
@@ -73,3 +73,11 @@ PHP (namespace `StreamGoals\Actions`):
- `Recorder::forDonation(int $donationId): void` — called after a donation becomes `completed` (same place the rules engine is applied); matches on the donation's BASE amount (not fee cover) using the goal's enabled actions and records events. Never throws.
Public/overlay: the donate form shows each enabled action as a button (amount + title); the overlay has a new `actions` widget (the menu for the active goal) and alert payloads gain `actions`: `[ {title, times} ]` read from sg_action_events (anonymous donors' actions are still shown; names stay masked).
Amounts must be >= Settings::effectiveMin().
## Schema v3 (Installer, DB_VERSION 3)
- `sg_goals.close_at_target` TINYINT: when 1, the goal is closed to donors as soon as its raised total reaches or exceeds the target (status becomes `complete`, same as the manual "Complete" action).
- `sg_alert_defs` — owner-defined alert presentations (media from the WordPress Media Library; attachment ids, never raw URLs):
id, goal_id (0 = all goals), trigger_type `amount` | `reward`, min_minor (for `amount`: applies when the donation BASE amount >= min_minor; the highest matching min_minor wins),
action_id (for `reward`: applies when that reward triggered; a reward definition wins over an amount definition), title (admin label),
visual_id + visual_type (`image` | `video` | '' none), sound_id (audio attachment, 0 none), volume 0-100, duration_ms (how long an image/GIF stays; videos play to the end, capped),
message (template with {name} {amount} {reward}; '' = default text), enabled, sort, created_at.
+3 -2
View File
@@ -43,7 +43,7 @@ final class GoalsPage {
$pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0;
echo '<tr><td><strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' &middot; <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div></td>';
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
@@ -90,6 +90,7 @@ final class GoalsPage {
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
echo '<tr><th scope="row"><label for="sg_end">Ends</label></th><td><input type="datetime-local" id="sg_end" name="ends_at" value="' . esc_attr( $fmt( $g['ends_at'] ?? null ) ) . '"> <span class="description">Optional. Donations stop after this time.</span></td></tr>';
echo '<tr><th scope="row">Fees</th><td><label><input type="checkbox" name="counts_fees" value="1"' . checked( ! empty( $g['counts_fees'] ), true, false ) . '> Count fees covered by donors towards the goal</label><p class="description">Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.</p></td></tr>';
echo '<tr><th scope="row">End at target</th><td><label><input type="checkbox" name="close_at_target" value="1"' . checked( ! empty( $g['close_at_target'] ), true, false ) . '> Close this goal to donations when the target is reached</label><p class="description">When the raised total reaches or goes over the target, the goal is marked complete and the donation page stops taking donations to it. Donations already in checkout still complete. You can reopen it with &quot;Reopen&quot; (raise the target first if you want more donations: a reopened goal that is still at or over its target closes again after the next donation).</p></td></tr>';
echo '</table><p><button class="button button-primary">' . ( $g ? 'Save goal' : 'Create goal' ) . '</button> <a class="button" href="' . esc_url( Admin::url() ) . '">Cancel</a></p></form>';
Admin::close();
}
@@ -131,7 +132,7 @@ final class GoalsPage {
if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) {
Admin::redirect( $back, 'error', 'The end must be after the start.' );
}
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1 );
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
if ( $id ) {
Store::goals()->update( $id, $data );
} else {
+5 -3
View File
@@ -56,7 +56,7 @@ 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>';
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only 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>';
@@ -80,7 +80,7 @@ final class SettingsPage {
/** 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' );
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_CF_RAY' => 'CF-Ray', '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 ] ) ) {
@@ -91,8 +91,10 @@ final class SettingsPage {
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>';
}
$viaCf = isset( $server['REMOTE_ADDR'] ) && \StreamGoals\Core\CloudflareRanges::isCloudflare( $server['REMOTE_ADDR'], (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
echo '<tr><td>Is this connection from Cloudflare?</td><td>' . ( $viaCf ? '<strong>Yes</strong> - the connection comes from a Cloudflare address' : 'No' ) . '</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>';
echo '</tbody></table>' . ( ! $viaCf && ( isset( $server['HTTP_CF_RAY'] ) || isset( $server['HTTP_CF_CONNECTING_IP'] ) ) ? '<p class="sg-warn">Cloudflare headers were sent, but the connection is not from a known Cloudflare address, so "Automatic" ignores them. If your site really is behind Cloudflare, choose "Cloudflare" above (or update the plugin, as Cloudflare may have added new addresses).</p>' : '' ) . '<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 {
+47
View File
@@ -0,0 +1,47 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
final class CidrMatcher {
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
public static function contains( string $ip, array $cidrs ): bool {
$ipBin = @inet_pton( trim( $ip ) );
if ( false === $ipBin ) {
return false;
}
foreach ( $cidrs as $cidr ) {
if ( self::inRange( $ipBin, (string) $cidr ) ) {
return true;
}
}
return false;
}
private static function inRange( string $ipBin, string $cidr ): bool {
$parts = explode( '/', trim( $cidr ), 2 );
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
return false;
}
$netBin = @inet_pton( $parts[0] );
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
return false;
}
$bits = (int) $parts[1];
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
return false;
}
$fullBytes = intdiv( $bits, 8 );
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
return false;
}
$rest = $bits % 8;
if ( 0 === $rest ) {
return true;
}
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
}
}
+9 -1
View File
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
*/
final class ClientIp {
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
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_AUTO => 'Automatic (recommended): detects Cloudflare',
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',
@@ -25,10 +27,16 @@ final class ClientIp {
);
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
$fromHeader = null;
switch ( $mode ) {
case self::MODE_AUTO:
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
}
break;
case self::MODE_CLOUDFLARE:
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
break;
+25
View File
@@ -0,0 +1,25 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Cloudflare's published proxy address ranges (https://www.cloudflare.com/ips-v4 and /ips-v6), fetched 2026-11-15.
* They change very rarely. Sites can extend them with the `streamgoals_cloudflare_ranges` filter.
* Used ONLY to decide whether a connection really comes from Cloudflare, so a forged CF-Connecting-IP header
* from anywhere else is ignored.
*/
final class CloudflareRanges {
public const RANGES = array(
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18',
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
);
/** @param string[]|null $extra additional ranges (from the filter) */
public static function isCloudflare( string $ip, ?array $extra = null ): bool {
return CidrMatcher::contains( $ip, array_merge( self::RANGES, $extra ?? array() ) );
}
}
+20 -3
View File
@@ -6,7 +6,7 @@ namespace StreamGoals\Core;
/** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */
final class GoalRepository {
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' );
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d', 'close_at_target' => '%d' );
private \wpdb $db;
@@ -21,7 +21,7 @@ final class GoalRepository {
/** @return int new goal id */
public function create( array $data ): int {
$row = array_intersect_key( $data, self::FIELDS );
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 );
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0, 'close_at_target' => 0 );
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
$this->db->insert( $this->table(), $row );
return (int) $this->db->insert_id;
@@ -62,9 +62,26 @@ final class GoalRepository {
if ( ! $goal ) {
return 0;
}
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input
$col = GoalTargetPolicy::amountColumn( $goal ); // whitelisted, not user input
$d = $this->db->prefix . 'sg_donations';
$sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) );
return (int) $sum;
}
/**
* "End at target": if the goal is active, flagged close_at_target and its raised total has reached the
* target, set it to 'complete'. The UPDATE is conditional on status = 'active', so concurrent callers
* change it once. Idempotent and cheap (one SELECT for non-flagged goals). Returns true if THIS call closed it.
*/
public function closeIfTargetReached( int $goalId ): bool {
$goal = $this->find( $goalId );
if ( ! $goal || empty( $goal['close_at_target'] ) || 'active' !== $goal['status'] ) {
return false;
}
if ( ! GoalTargetPolicy::shouldClose( $goal, $this->raised_minor( $goalId ) ) ) {
return false;
}
$n = $this->db->query( $this->db->prepare( "UPDATE {$this->table()} SET status = 'complete' WHERE id = %d AND status = 'active' AND close_at_target = 1", $goalId ) );
return 1 === $n;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** Pure rules for "end at target" goals (no WordPress / database access). */
final class GoalTargetPolicy {
/** Donation column summed towards the goal: total (fees included) or base. Whitelisted values only. */
public static function amountColumn( array $goal ): string {
return ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
}
/** True when the goal should now be auto-closed: flag on, currently active, target set and reached or exceeded. */
public static function shouldClose( array $goal, int $raisedMinor ): bool {
return ! empty( $goal['close_at_target'] )
&& 'active' === ( $goal['status'] ?? '' )
&& (int) ( $goal['target_minor'] ?? 0 ) > 0
&& $raisedMinor >= (int) $goal['target_minor'];
}
/** True for a goal that is closed to donors because it reached its target (flag on + complete). */
public static function isClosedAtTarget( array $goal ): bool {
return ! empty( $goal['close_at_target'] ) && 'complete' === ( $goal['status'] ?? '' );
}
/** Checkbox value from a raw form field: 1 when ticked, else 0. */
public static function flagFromPost( mixed $raw ): int {
if ( is_array( $raw ) || null === $raw ) {
return 0;
}
return in_array( strtolower( trim( (string) $raw ) ), array( '1', 'on', 'true', 'yes' ), true ) ? 1 : 0;
}
}
+22 -1
View File
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '2';
public const DB_VERSION = '3';
public static function activate(): void {
self::install_schema();
@@ -39,6 +39,7 @@ final class Installer {
starts_at DATETIME NULL,
ends_at DATETIME NULL,
counts_fees TINYINT(1) NOT NULL DEFAULT 0,
close_at_target TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id)
) $c;" );
@@ -122,6 +123,26 @@ final class Installer {
KEY status_id (status,id)
) $c;" );
dbDelta( "CREATE TABLE {$p}alert_defs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
goal_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
trigger_type VARCHAR(8) NOT NULL DEFAULT 'amount',
min_minor BIGINT UNSIGNED NOT NULL DEFAULT 0,
action_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
title VARCHAR(120) NOT NULL DEFAULT '',
visual_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
visual_type VARCHAR(6) NOT NULL DEFAULT '',
sound_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
volume TINYINT UNSIGNED NOT NULL DEFAULT 80,
duration_ms INT UNSIGNED NOT NULL DEFAULT 6000,
message VARCHAR(255) NOT NULL DEFAULT '',
enabled TINYINT(1) NOT NULL DEFAULT 1,
sort INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY goal_enabled (goal_id,enabled)
) $c;" );
update_option( 'sg_db_version', self::DB_VERSION );
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ final class Settings {
'message_max_length' => 200,
'min_donation_minor' => 100,
'overlay_token' => '',
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
'visitor_ip_header' => 'auto', // auto | '' (direct) | 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
+22
View File
@@ -93,6 +93,28 @@ final class DonationStore {
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
self::close_goal_if_target_reached( $id );
}
/**
* "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').
*/
public static function close_goal_if_target_reached( int $donationId ): void {
try {
$row = self::find( $donationId );
if ( $row && (int) $row->goal_id > 0 ) {
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
}
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
}
/** 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 ): void {
+3
View File
@@ -84,6 +84,9 @@ final class OrderValidator {
* @throws ValidationException
*/
public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
if ( 'complete' === ( $goal['status'] ?? '' ) ) {
throw new ValidationException( 'goal_inactive', 'This goal is closed and no longer accepting donations. Thank you for your support!', 409 );
}
if ( ! self::goalIsOpen( $goal, $nowTs ) ) {
throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 );
}
+7 -1
View File
@@ -3,6 +3,7 @@ declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
@@ -170,6 +171,11 @@ final class DonateController {
);
}
if ( ! $goals ) {
$reached = $pinned ? DonationStore::goal( $pinned ) : null;
$reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals();
if ( $reached ) {
return '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
}
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
}
@@ -278,7 +284,7 @@ final class DonateController {
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
}
}
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
+2 -1
View File
@@ -67,7 +67,8 @@ final class ActionRepositoryTest extends TestCase {
public function test_installer_schema_defines_both_tables_and_unique_key(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
$this->assertStringContainsString( "DB_VERSION = '2'", $src );
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ), 'DB_VERSION constant not found' );
$this->assertGreaterThanOrEqual( 2, (int) $m[1], 'the actions tables arrived in schema version 2; later versions must keep them' );
$this->assertStringContainsString( 'CREATE TABLE {$p}actions (', $src );
$this->assertStringContainsString( 'CREATE TABLE {$p}action_events (', $src );
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', $src );
+59
View File
@@ -0,0 +1,59 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\CidrMatcher;
use StreamGoals\Core\CloudflareRanges;
final class CidrMatcherTest extends TestCase {
public function test_ipv4_boundaries(): void {
$r = array( '173.245.48.0/20' ); // 173.245.48.0 - 173.245.63.255
$this->assertTrue( CidrMatcher::contains( '173.245.48.0', $r ) );
$this->assertTrue( CidrMatcher::contains( '173.245.63.255', $r ) );
$this->assertFalse( CidrMatcher::contains( '173.245.47.255', $r ) );
$this->assertFalse( CidrMatcher::contains( '173.245.64.0', $r ) );
}
public function test_non_byte_aligned_and_wide_masks(): void {
$this->assertTrue( CidrMatcher::contains( '104.27.255.255', array( '104.24.0.0/14' ) ) ); // /14 spans 104.24 - 104.27
$this->assertFalse( CidrMatcher::contains( '104.28.0.0', array( '104.24.0.0/14' ) ) );
$this->assertFalse( CidrMatcher::contains( '104.23.255.255', array( '104.24.0.0/14' ) ) );
$this->assertTrue( CidrMatcher::contains( '8.8.8.8', array( '0.0.0.0/0' ) ) );
$this->assertTrue( CidrMatcher::contains( '1.2.3.4', array( '1.2.3.4/32' ) ) );
$this->assertFalse( CidrMatcher::contains( '1.2.3.5', array( '1.2.3.4/32' ) ) );
}
public function test_ipv6(): void {
$this->assertTrue( CidrMatcher::contains( '2606:4700::1', array( '2606:4700::/32' ) ) );
$this->assertTrue( CidrMatcher::contains( '2a06:98c7:ffff::1', array( '2a06:98c0::/29' ) ) );
$this->assertFalse( CidrMatcher::contains( '2a06:98c8::1', array( '2a06:98c0::/29' ) ) );
$this->assertFalse( CidrMatcher::contains( '2606:4701::1', array( '2606:4700::/32' ) ) );
}
public function test_families_never_cross_match_and_bad_input_is_false(): void {
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( '2606:4700::/32' ) ) );
$this->assertFalse( CidrMatcher::contains( '2606:4700::1', array( '173.245.48.0/20' ) ) );
foreach ( array( 'garbage', '', '999.1.1.1', "1.2.3.4\nX: y", '1.2.3.4, 5.6.7.8' ) as $bad ) {
$this->assertFalse( CidrMatcher::contains( $bad, array( '0.0.0.0/0' ) ), "matched bad ip: $bad" );
}
foreach ( array( '1.2.3.4', '1.2.3.4/x', '1.2.3.4/33', '1.2.3.4/-1', 'nope/8', '' ) as $badCidr ) {
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( $badCidr ) ), "matched bad cidr: $badCidr" );
}
}
public function test_surrounding_whitespace_is_tolerated(): void {
$this->assertTrue( CidrMatcher::contains( ' 173.245.48.1 ', array( '173.245.48.0/20' ) ) );
}
public function test_cloudflare_ranges(): void {
$this->assertTrue( CloudflareRanges::isCloudflare( '172.70.1.1' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '104.16.0.1' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '2606:4700:3030::1' ) );
$this->assertFalse( CloudflareRanges::isCloudflare( '203.0.113.9' ) );
$this->assertFalse( CloudflareRanges::isCloudflare( '47.151.185.180' ) );
$this->assertTrue( CloudflareRanges::isCloudflare( '203.0.113.9', array( '203.0.113.0/24' ) ), 'filter-supplied ranges extend the list' );
}
}
+24
View File
@@ -56,4 +56,28 @@ final class ClientIpTest extends TestCase {
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
}
public function test_auto_mode_trusts_cf_header_only_from_a_cloudflare_connection(): void {
$srv = array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
$v6 = array( 'REMOTE_ADDR' => '2606:4700:3030::1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( self::CLIENT, ClientIp::resolve( $v6, ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_ignores_a_forged_header_from_a_non_cloudflare_connection(): void {
$srv = array( 'REMOTE_ADDR' => '47.151.185.180', 'HTTP_CF_CONNECTING_IP' => '6.6.6.6', 'HTTP_X_FORWARDED_FOR' => '7.7.7.7' );
$this->assertSame( '47.151.185.180', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_falls_back_when_header_missing_or_invalid(): void {
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1' ), ClientIp::MODE_AUTO ) );
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => 'nope' ), ClientIp::MODE_AUTO ) );
}
public function test_auto_mode_extra_ranges_from_the_filter(): void {
$srv = array( 'REMOTE_ADDR' => '198.18.0.5', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\FeeCalculator;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\PayPal\ValidationException;
final class GoalTargetPolicyTest extends TestCase {
private function goal( array $o = array() ): array {
return array_merge( array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'target_minor' => 10000, 'close_at_target' => 1, 'counts_fees' => 0, 'starts_at' => null, 'ends_at' => null ), $o );
}
public function test_below_equal_and_over_target(): void {
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal(), 9999 ) );
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 10000 ) );
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 25000 ) );
}
public function test_flag_off_or_missing_never_closes(): void {
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'close_at_target' => 0 ) ), 99999 ) );
$g = $this->goal();
unset( $g['close_at_target'] );
$this->assertFalse( GoalTargetPolicy::shouldClose( $g, 99999 ) );
}
public function test_only_active_goals_are_closed(): void {
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'complete' ) ), 20000 ) );
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'paused' ) ), 20000 ) );
}
public function test_target_zero_never_closes(): void {
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 0 ) );
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 500 ) );
}
public function test_base_vs_total_basis(): void {
$this->assertSame( 'base_minor', GoalTargetPolicy::amountColumn( $this->goal() ) );
$this->assertSame( 'total_minor', GoalTargetPolicy::amountColumn( $this->goal( array( 'counts_fees' => 1 ) ) ) );
}
public function test_closed_at_target_detection_and_pause_is_not_closed(): void {
$this->assertTrue( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete' ) ) ) );
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'paused' ) ) ) );
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete', 'close_at_target' => 0 ) ) ) );
}
public function test_checkbox_parsing(): void {
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( '1' ) );
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( 'on' ) );
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( null ) );
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '' ) );
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '0' ) );
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( array( '1' ) ) );
}
public function test_new_orders_for_a_closed_goal_get_a_friendly_409(): void {
try {
OrderValidator::validate( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'complete' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
$this->fail( 'expected refusal' );
} catch ( ValidationException $e ) {
$this->assertSame( 'goal_inactive', $e->errorCode );
$this->assertSame( 409, $e->status );
$this->assertStringContainsString( 'Thank you', $e->getMessage() );
}
}
public function test_paused_goal_keeps_generic_message(): void {
try {
OrderValidator::quote( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'paused' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
$this->fail( 'expected refusal' );
} catch ( ValidationException $e ) {
$this->assertSame( 'This goal is not accepting donations.', $e->getMessage() );
}
}
public function test_goal_open_for_active_flagged_goal(): void {
$this->assertTrue( OrderValidator::goalIsOpen( $this->goal(), 1800000000 ) );
$this->assertFalse( OrderValidator::goalIsOpen( $this->goal( array( 'status' => 'complete' ) ), 1800000000 ) );
}
}